<?php
class Custom_HsElementController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "custom/views/customs/";
        $this->serviceClass = new Service_HsElement();
    }

    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);
            unset($params);
            $count = $this->serviceClass->getByCondition($condition, 'count(*)');
            $return['total'] = $count;

            if ($count) {
                $showFields=array(
                'he_id',
                'hs_code',
                'he_code',
                'he_name',
                'he_sort',
                'he_add_time',
                'he_update_time',
                'he_status',
                );
                $showFields = $this->serviceClass->getFieldsAlias($showFields);
                $rows = $this->serviceClass->getByCondition($condition,$showFields, $pageSize, $page, array('he_id desc'));
                $return['data'] = $rows;
                $return['state'] = 1;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        echo Ec::renderTpl($this->tplDirectory . "hs_element_index.tpl", 'layout');
    }

    public function editAction()
    {
        $return = array(
            'state' => 0,
            'message' => '',
            'errorMessage'=>array('Fail.')
        );

        if ($this->_request->isPost()) {
            $params = $this->_request->getParams();
            $row = array(
                
              'he_id'=>'',
              'hs_code'=>'',
              'he_code'=>'',
              'he_name'=>'',
              'he_sort'=>'',
              'he_add_time'=>'',
              'he_update_time'=>'',
            );
            $row=$this->serviceClass->getMatchEditFields($params,$row);
            unset($params);
            $paramId = $row['he_id'];
            if (!empty($row['he_id'])) {
                unset($row['he_id']);
            }
            $errorArr = $this->serviceClass->validator($row);

            if (!empty($errorArr)) {
                $return = array(
                    'state' => 0,
                    'message'=>'',
                    'errorMessage' => $errorArr
                );
                die(Zend_Json::encode($return));
            }

            if (!empty($paramId)) {
                $result = $this->serviceClass->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, 'he_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 uploadTemplateAction(){
        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".'/hsCodesImport.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;
    }

    public function batchImportAction(){
        $result = array("ask"=>1,"message"=>"",'error'=>array(),'data'=>array());
        $xlsData = Service_Product::getXLSData($_FILES,'filename');
        //var_dump($xlsData);
        //exit;
        /*if(count($xlsData[0])!=2||($xlsData[0][0]!="客户代码"||$xlsData[0][1]!="产品sku")){
            $result['ask'] = "0";
            $result['error'][] = "文件格式错误，首行不是按照客户代码,产品sku排列!";
            die(json_encode($result));
        }*/
        foreach($xlsData as $key=>$value){
            if($key==0) continue;
            $existError = 0;
            $hsCode = $value[0];
            $p_name = $value[1];
            $resultData = array(
                'hs_code'=>$hsCode,
                'p_name'=>$p_name,
                'ok'=>1
            );
            if($hsCode==""){
                $existError = 1;
                $resultData['message'] .= "海关编码为空;";
            }
            if($value[2]==""){
                $existError = 1;
                $resultData['message'] .= "法定单位为空;";
            }
            if($existError) {
                $resultData['ok'] = '0';
                $result['data'][] = $resultData;
                continue;
            }
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try{
                $hsCodeRow = array(
                    'hs_code'=>$hsCode,
                    'p_name'=>$p_name==""?"":$p_name,
                    'hs_code_status'=>1,
                );
                $existHsCode = Service_Hscodes::getByField($hsCode,'hs_code',"*");
                if($existHsCode){
                    throw new Exception("海关编码[".$hsCode."]已存在");
                }
                $he_id = Service_Hscodes::add($hsCodeRow);
                $pu_name = $value[2];
                $puRow = Service_ProductUom::getByField($pu_name,'pu_name',"*");
                $hsUomRow = array(
                    'hs_code'=>$hsCode,
                    'pu_code_law'=>$puRow['pu_code'],
                    'hu_add_time'=>date("Y-m-d H:i:s"),
                    'hu_update_time'=>date("Y-m-d H:i:s"),
                    'hu_status'=>'1',
                );
                $pu_name_second = $value[3];
                if($pu_name_second!=""){
                    $puRowSecond = Service_ProductUom::getByField($pu_name_second,'pu_name',"*");
                    $hsUomRow['pu_code_second'] = $puRowSecond['pu_code'];
                }
                Service_HsUom::add($hsUomRow);
                $count = count($value);
                for($i=4;$i<$count;$i++){
                    if($value[$i]=="") break;
                    $heElementRow = array(
                        'hs_code'=>$hsCode,
                        'he_code'=>$value[$i],
                        'he_name'=>$value[$i],
                        'he_sort'=>$i-4,
                        'he_add_time'=>date("Y-m-d H:i:s"),
                        'he_update_time'=>date("Y-m-d H:i:s"),
                        'he_status'=>'1',
                    );
                    Service_HsElement::add($heElementRow);
                }
                $db->commit();
                $resultData['ok'] = 1;
                $resultData['message'] = "海关编码[".$hsCode."]新增成功!";
            }catch (Exception $e){
                $db->rollBack();
                $resultData['ok'] = '0';
                $resultData['message'] = "海关编码[".$hsCode."]新增失败:".$e->getMessage();
            }
            $result['data'][] = $resultData;
        }
        die(json_encode($result));
    }
}