<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Administrator
 * Date: 18-4-11
 * Time: 下午2:12
 * To change this template use File | Settings | File Templates.
 */
class Customer_AutoPackController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "customer/views/default/";
        $this->serviceClass = new Service_AutopackInfo();
    }

    public function listAction(){
        if ($this->_request->isPost()) {
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;

            $return = array(
                "state" => 0,
                "message" => "No Data"
            );

            $params = $this->_request->getParams();

            $condition = $this->serviceClass->getMatchFields($params);

            $count = $this->serviceClass->getByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields=array(
                    'api_id',
                    'customer_code',
                    'sm_code',
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getByCondition($condition,$showFields, $pageSize, $page, array('api_id desc'));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        $this->view->SM=Common_DataCache::getShippingMethodSimple();
        $shipMethod = Service_ShippingMethod::getByCondition(array('sm_channel'=>'0'),"*");
        $sm = array();
        $smCodeArr = array();
        foreach($shipMethod as $key=>$value){
            $o = array(
                'sm_code'=>$value['sm_code'],
                'sm_name_cn'=>$value['sm_name_cn']
            );
            if(!in_array($value['sm_code'],$smCodeArr)){
                $sm[] = $o;
                $smCodeArr[] = $value['sm_code'];
            }
        }
        $sm=Common_Common::multisort($sm);
        $this->view->shipMethod = $sm;
        echo Ec::renderTpl($this->tplDirectory . "auto-pack-index.tpl", 'layout');
    }

    public function editAction()
    {
        $return = array(
            'state' => 0,
            'message' => '',
            'errorMessage'=>array('Fail.')
        );
        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            $row = array(
                'api_id' => '',
                'customer_code' => '',
                'customer_id' => '',
                'sm_code' => '',
            );
            $row = $this->serviceClass->getMatchEditFields($params, $row);
            unset($params);
            $paramId = $row['api_id'];
            if (!empty($row['api_id'])) {
                unset($row['api_id']);
            }
            $errorArr = $this->serviceClass->validator($row);
            if (!empty($errorArr)) {
                $return = array(
                    'state' => 0,
                    'message'=>'',
                    'errorMessage' => $errorArr
                );
                die(Zend_Json::encode($return));
            }
            $customerRow = Service_Customer::getByField($row['customer_code'],"customer_code","*");
            $row['customer_id']=$customerRow['customer_id'];
            //unset($smRow);
            if (!empty($paramId)) {
                //unset($row['price_batch_number']); /* price_batch_number 不允许修改 */
                $result = $this->serviceClass->update($row, $paramId);
                //  $result1 = $this->serviceHistoryClass->update($row, $paramId);
            } else {
                $result = $this->serviceClass->add($row);
            }
            if ($result) {
                $return['state'] = 1;
                $return['message'] = array('Success.');
            }
        }
        die(Zend_Json::encode($return));
    }

    public function getByJsonAction()
    {
        $result = array('state' => 0, 'message' => 'Fail', 'data' => array());
        $paramId = $this->_request->getParam('paramId', '');
        if (!empty($paramId) && $rows = $this->serviceClass->getByField($paramId, 'api_id')) {
            $rows=$this->serviceClass->getVirtualFields($rows);
            $result = array('state' => 1, 'message' => '', 'data' => $rows);
        }
        die(Zend_Json::encode($result));
    }

    public function deleteAction()
    {
        $result = array(
            "state" => 0,
            "message" => "Fail."
        );
        if ($this->_request->isPost()) {
            $paramId = $this->_request->getPost('paramId');
            if (!empty($paramId)) {
                if ($this->serviceClass->delete($paramId)) {
                    $result['state'] = 1;
                    $result['message'] = 'Success.';
                }
            }
        }
        die(Zend_Json::encode($result));
    }

    public function batchImportAction(){
        set_time_limit(0);
        $result = array("ask"=>1,"message"=>"",'error'=>array(),'data'=>array());
        $xlsData = Service_SmCustomerMap::getXLSData($_FILES,'filename');
        if(count($xlsData[0])!=2 ||$xlsData[0][0]!="客户代码"||$xlsData[0][1]!="运输代码"){
            $result['ask'] = "0";
            $result['error'][] = "文件格式错误，首行不是按照客户代码,运输代码排列!";
            die(json_encode($result));
        }
        foreach($xlsData as $key=>$value){
            if($key==0) continue;
            $customer_code = $value[0];
            $sm_code = $value[1];
            $resultData = array(
                'customer_code'=>$customer_code,
                'sm_code'=>$sm_code,
            );
            if($customer_code==""){
                $resultData['message'] = "客户代码不能为空！";
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }
            $customerRow = Service_Customer::getByField($customer_code,'customer_code',"*");
            if(empty($customerRow)){
                $resultData['message'] = "客户代码".$customer_code."不存在！";
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }
            if($sm_code==""){
                $resultData['message'] = "运输代码不能为空！";
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }
            $shippingMethod = Service_ShippingMethod::getByField($sm_code,'sm_code',"*");
            if(empty($shippingMethod)){
                $resultData['message'] = "运输代码".$sm_code."不存在！";
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }
            if($shippingMethod['sm_channel']=="1"){
                $resultData['message'] = "运输代码".$sm_code."是自有渠道！";
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }
            $row = array(
                'customer_code'=>$customer_code,
                'sm_code'=>$sm_code,
                'customer_id'=>$customerRow['customer_id'],
            );
            $existRow = Service_AutopackInfo::getByCondition($row,"count(*)");
            if($existRow){
                $resultData['message'] = "此配置已存在";
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }
            $apiid = Service_AutopackInfo::add($row);
            if($apiid){
                $resultData['ok'] = '1';
                $resultData['message'] = "添加成功!";
            }else{
                $resultData['ok'] = '0';

            }
            $result['data'][] = $resultData;
        }
        die(json_encode($result));
    }

    public function batchImportTemplateAction(){
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT');
        header('Cache-Control: no-cache, must-revalidate');
        header('Pragma: no-cache');
        $fullPath = APPLICATION_PATH."/../data/xls".'/autopackimport.xls';
        //方法2
        $filename = basename($fullPath);
        header("Content-Type: APPLICATION/OCTET-STREAM");
        //Force the download
        $header="Content-Disposition: attachment; filename=".$filename.";";
        header($header );
        //  header("Content-Transfer-Encoding: binary");
        //  header("Content-Length: ".$len);
        echo file_get_contents($fullPath);
        exit;
    }

}
