<?php
class Order_CheckGoodsController extends Ec_Controller_Action{
    
    public function preDispatch(){
        $this->tplDirectory = "order/views/default/";
        $this->serviceClass = new Service_Orders();
    }
    
    public function listAction(){
        echo Ec::renderTpl($this->tplDirectory . "checkgoods_index.tpl", 'layout');
    }
    
    public function addAction(){
        $response = array('status'=>'0','message'=>'操作失败!');
        $code = $this->_request->getParam('code','');
        $dsRow = $orderInfo = Service_Orders::getByField($code,"order_code","*");
        if(empty($orderInfo)){
             $shipOrder= Service_ShipOrder::getByField($code,"tracking_number","*");
            if(empty($shipOrder)){
                $response['message'] = "订单号或服务商单号不存在!";
                die(Zend_Json::encode($response));
            }else{
                $dsRow = $orderInfo = Service_Orders::getByField($shipOrder['order_code'],"order_code","*");
            }
        }else{
            $shipOrder = Service_ShipOrder::getByField($orderInfo['order_code'],'order_code','*');
        }
        $otherFeeInfo = Service_OtherFee::getByField('DSFHF', 'fee_code');//查询点数分货费（DSFHF）
        $dsRow['weight'] = $shipOrder['so_weight'];
        $dsRow['tracking_number'] = $shipOrder['tracking_number'];
        if(!empty($otherFeeInfo)){ 
            $result = Process_DsfhfProcess::deductFee($otherFeeInfo, $dsRow);
            if($result['status'] == '1'){
                $response['status'] = '1';
            }else{
                $response['message'] = array($result['message']);
            }
        }else{
            $response['message'] = '点数分货费未配置!';
        }
        die(Zend_Json::encode($response));
    }
    
    public function downTemplateAction(){
        $fullPath = APPLICATION_PATH."/../data/xls".'/batch-dsfh-template.xls';
        Common_Common::downloadFile($fullPath);
    }
    
    public function batchImportAction(){
        $response = array('status'=>'0','message'=>'操作失败!');
        if (!$this->getRequest()->isPost()) {
            header('content-type: text/html; charset=utf-8');
            exit('非法请求：请求方式不是POST');
        }
        set_time_limit(0); // 不限执行时间
        ini_set('memory_limit', '2048M');//设置内存限制
        
        $fileInfo = $_FILES['code_file'];
        $cache = '';
        $data = array();
        $error = '';
        $table = '';
        
        if (0 !== $fileInfo['error']) {
            $error = '上传订单数据文件失败';
        
            switch ($fileInfo['error']) {
                case UPLOAD_ERR_INI_SIZE:
                    $error .= '：文件大小超过系统配置指定值' . ini_get('upload_max_filesize');
                    break;
                case UPLOAD_ERR_FORM_SIZE:
                    $error .= '：文件大小超过表单指定值（MAX_FILE_SIZE）';
                    break;
                case UPLOAD_ERR_PARTIAL:
                    $error .= '：文件上传不完整';
                    break;
                case UPLOAD_ERR_NO_FILE:
                    $error .= '：没有文件上传';
                    break;
                case UPLOAD_ERR_NO_TMP_DIR:
                    $error .= '：找不到临时目录';
                    break;
                case UPLOAD_ERR_CANT_WRITE:
                    $error .= '：文件写入失败';
                    break;
                default:
                    break;
            }
        } else {
            $ext = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
            $tmp = Process_DsfhfProcess::getCacheDir() . date('YmdHis-') . md5('ORDER-BATCHDSFHF-IMPORT-FILE-' . microtime(TRUE)) . '.' . $ext;
            if (!in_array(strtoupper($ext), array('XLS', 'XLSX'), TRUE)) {
                $error = '不受支持的文件类型：' . $ext;
            } elseif (!move_uploaded_file($fileInfo['tmp_name'], $tmp)) {
                $error = '移动上传订单数据文件时发生异常';
            } else {
                $readData = Process_DsfhfProcess::getData($tmp);
                if (0 === $readData['status']) {
                    $error = $readData['message'];
                } else {
                    $data = $readData['data'];
                }
            }
           
            //数据读取完毕，开始处理
            if(empty($error)){
                $otherFeeInfo = Service_OtherFee::getByField('DSFHF', 'fee_code');//查询点数分货费（DSFHF）
                if(!empty($otherFeeInfo)){
                    foreach($data as $value){
                        $result = Process_DsfhfProcess::deductFee($otherFeeInfo, $value);
                        if($result['status'] == '1'){
                            $response['status'] = '1';
                            $response[$value['order_code']]['status'] = '1';
                        }else{
                            $response['status'] = '1';
                            $response[$value['order_code']]['status'] = '0';
                            $response[$value['order_code']]['message'] = $result['message'];
                        }
                    }
                }else{
                    $response['message'] = '点数分货费未配置!';
                    break;
                }
            }else{
                $response['message'] = $error;
            }
            //返回显示
            if($response['status'] == '1'){
                //$index = 1;
                $statistic_sucess = 0;
                //$result_view = array();
                foreach($response as $key=>$value){
                    if(in_array($key, array('status','message')))continue;
                    //$result_view[$key]['index'] = $index;
                    if($value['status'] == '1'){
                        //$status_view = '成功';
                        $statistic_sucess++;
                    }else{
                        //$status_view = '失败';
                        //nothing to do
                    }
                    //$result_view[$key]['code'] = $key;
                    //$result_view[$key]['status'] = $status_view;
                    //$result_view[$key]['message'] = $value['message'] ? $value['message'] : '';
                    //$index++;
                }
                //$this->view->batchResult = $result_view;
                //$statistic_total = count($response) - 2; //有效不重复的单号数量
                $statistic_total = $data['total_org']; //不重复的单号数量
                echo Ec::renderTpl($this->tplDirectory . "checkgoods_index.tpl", 'layout');
                echo <<<SCRIPT
<script type="text/javascript">
alertTip('本次总共导入{$statistic_total}条数据,成功扣费{$statistic_sucess}条数据!');
</script>
SCRIPT;
            }else{
                echo Ec::renderTpl($this->tplDirectory . "checkgoods_index.tpl", 'layout');
                echo <<<SCRIPT
<script type="text/javascript">
alertTip('{$response['message']}');
</script>
SCRIPT;
            }
           
        }    
    }
    
    public function addOvernightParkingFeeAction(){
       $response = array('status'=>'0','message'=>'操作失败!');
       $operation_type_code = $this->_request->getParam('operation_type','');
       $operation_type_arr = Process_DsfhfProcess::return_operation_type();
       $customer_code = $this->_request->getParam('customer_code','');
       $fee_generate_time = $this->_request->getParam('fee_generate_time','');
       $code = $this->_request->getParam('code','');
       $quantity = $this->_request->getParam('quantity','');
       $customerData = Service_Customer::getByField($customer_code, 'customer_code', array('customer_id'));
       if(empty($customerData)){
           $response['message'] = "客户代码不存在!";
           die(Zend_Json::encode($response));
       }
       $otherFeeInfo = Service_OtherFee::getByField($operation_type_arr[$operation_type_code], 'fee_code');//根据杂费代码查询配置
       $params = array('customer_code'=>$customer_code,'fee_generate_time'=>$fee_generate_time,'code'=>$code,'quantity'=>$quantity);//参数数组
       if(!empty($otherFeeInfo)){
           $result = Process_DsfhfProcess::deductOvernightParkingFee($otherFeeInfo, $params);
           if($result['status'] == '1'){
               $response['status'] = '1';
           }else{
               $response['message'] = array($result['message']);
           }
       }else{
           if($operation_type_code == '1'){
               $response['message'] = '过夜停车费未配置!';
           }elseif($operation_type_code == '2'){
               $response['message'] = "海关库内查验(吨车或20')费未配置!";
           }elseif($operation_type_code == '3'){
               $response['message'] = "海关库内查验(40'或45')费未配置!";
           }else{
               $response['message'] = "报关单删单费未配置!";
           }
           
       }
       die(Zend_Json::encode($response));
    }
    
    public function addChangeOrderFeeAction(){
       $response = array('status'=>'0','message'=>'操作失败!');
       $operation_type_code = $this->_request->getParam('operation_type_co','');
       $operation_type_arr = Process_DsfhfProcess::return_operation_type_co();
       $type_co = $this->_request->getParam('type_co','');
       $code_co = $this->_request->getParam('code_co','');
       $quantity_co = $this->_request->getParam('quantity_co','');
       
       if($type_co == '1'){
           $receivingRow = Service_Receiving::getByField($code_co,"receiving_code","*");
           $coRow['customer_code']  = $receivingRow['customer_code']; //对应单，客户代码
           $coRow['reference_no']   = $receivingRow['reference_no']; //客户参考号
           $coRow['total_quantity'] = $receivingRow['pack_no']; //总件数  
           $coRow['type_co']        = '1';//改单类型
           if(empty($receivingRow)){
               $response['message'] = "改单类型选择错误或者入区单号不存在!";
               die(Zend_Json::encode($response));
           }
       }
       if($type_co == '2'){
           $orderInfo = Service_Orders::getByField($code_co,"order_code","*");
           $shipOrder = Service_ShipOrder::getByField($code_co,'order_code','tracking_number');
           $coRow['customer_code']  = $orderInfo['customer_code']; //对应单，客户代码
           $coRow['reference_no']   = $orderInfo['reference_no']; //客户参考号
           $coRow['total_quantity'] = $orderInfo['parcel_quantity']; //总件数
           $coRow['sm_code']        = $orderInfo['sm_code']; //运输方式
           $coRow['tracking_number']= $shipOrder['tracking_number']; //跟踪号
           $coRow['type_co']        = '2';//改单类型
           if(empty($orderInfo)){
               $response['message'] = "改单类型选择错误或者订单号不存在!";
               die(Zend_Json::encode($response));
           }
       }
       $coRow['code']     = $code_co; //单号
       $coRow['quantity'] = $quantity_co; // 份数
       $otherFeeInfo = Service_OtherFee::getByField($operation_type_arr[$operation_type_code], 'fee_code');//根据杂费代码查询配置
       if(!empty($otherFeeInfo)){
           $result = Process_DsfhfProcess::deductChangOrderFee($otherFeeInfo,$coRow);
           if($result['status'] == '1'){
               $response['status'] = '1';
           }else{
               $response['message'] = array($result['message']);
           }
       }else{
           if($operation_type_code == '1'){
               $response['message'] = '改单费--数据未发送海关杂费未配置!';
           }elseif($operation_type_code == '2'){
               $response['message'] = '改单费--数据已发送海关杂费未配置!';
           }
       }
       die(Zend_Json::encode($response));
    }
    
}