<?php

#use App\models\Logistic\Pri\PriEnter;
use App\models\Logistic\Pri\PriPreData;

class Cis_MakePreController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "cis/views/pre-entry/";
    }

    /**
     * @todo 生成预录入数据（出），出货总单或者出区派车单生成预录入数据
     */
    public function ecreateAction()
    {
        if ($this->_request->isPost()) {
            $return = [
                'state' => 0,
                'message' => 'fail',
                'success' => [],
                'error' => [],
            ];
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                //echo "<pre>";
                $params = $this->_request->getParams();
                $codeList = $this->_request->getParam('codlist');
                //print_r($params);
                if (empty($codeList)) {
                    throw new Exception('单号为空');
                }
                $searchType = $this->_request->getParam('search_type');
                $codeArray = preg_split('/\n|,/', $codeList);
                $codeArray = array_map(function ($v) {
                    return preg_replace('/\r|\s/', '', $v);
                }, $codeArray);
                $codeArray = array_filter($codeArray);
                if (count($codeArray) > 1) {
                    throw new Exception('暂不支持多个出货单生成预录入数据');
                }
                $params['codlist'] = $codeArray;
                $type = $this->_request->getParam('type', '');
                if (empty($type)) {
                    throw new Exception('请选择类型');
                }
                $pdProcess = new Api_Pre_PreDataProcess();
                $result = $pdProcess->createPreDataBySbcode($params);
                //var_dump($result);
                $return['error'] = $result['error'];
                if ($result['state'] != 1) {
                    throw new Exception('生成预录入数据错误:' . $result['message']);
                }
                $return['success'] = $result['success'];
                $return['message'] = "创建预录入单号成功：单号：" . $result['code'];
                $return['fail'] = array_diff($codeArray, $result['success']);
                $return['state'] = 1;
                $db->commit();
                //$db->rollBack();
            } catch (Exception $e) {
                //echo $e;
                $return['message'] = $e->getMessage();
                $db->rollBack();
            }
            die(Zend_Json::encode($return));
        }
        /*$pp = Common_SelectMap::getdestination_port();
        print_r($pp);*/
        //$com = Common_SelectMap::getBgCompany();
        $iePort = Service_IePort::getKeyVal();
        $this->view->district_code = Common_SelectMap::getdistrict_code();
        $this->view->type = Common_SelectMap::getEformType();
        $this->view->destination_port = Common_SelectMap::getdestination_port();
        $this->view->bgCompany = Common_SelectMap::getBgCompany();
        $this->view->country = Service_Country::getByCondition(['trade_country_notempty' => 1]);
        $this->view->iePort = $iePort;
        $this->view->aTransMode = Service_TransMode::getAll();

        echo Ec::renderTpl($this->tplDirectory . 'ecreate.tpl', 'layout');
    }

    /**
     * @todo 生成预录入数据（入），入库单或者派车单生成预录入数据
     */
    public function icreateAction()
    {
        if ($this->_request->isPost()) {
            $return = [
                'state' => 0,
                'message' => 'fail',
                'success' => [],
                'error' => [],
            ];
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {

                $bg_company = $this->_request->getParam('bg_company', '');
                $code = $this->_request->getParam('codlist', '');

                $error = [];

                $intoArea = Service_IntoArea::getByCode($code);

                if (empty($intoArea)) {
                    $error[] = '不存在入区派车单【' . $code . '】';
                }
                if ($bg_company == '') {
                    $error[] = "必须选择传输公司";
                }
                $duty_mode = $this->_request->getParam('duty_mode', '');
                $trade_area_code = $this->_request->getParam('trade_area_code', ''); //贸易国
                $destination_port = $this->_request->getParam('destination_port', ''); //指运港
                $destination_country = $this->_request->getParam('destination_country', '');//最终目的国
                if ($duty_mode == '') {
                    $error[] = "征免性质必填";
                }
                if ($trade_area_code == '') {
                    $error[] = "贸易国（地区）必填";
                }
                if ($destination_port == '') {
                    $error[] = "指运港必填";
                }
                if ($destination_country == '') {
                    $error[] = "最终目的国必填";
                }

                if (!empty($error)) {
                    $return['error'] = $error;
                    die(Zend_Json::encode($return));
                }


                $intoAreaDetail = Service_IntoArea::getDetailByCode($code);


                //print_r($this->_request->getParams());

                $preEnter = new PriPreData();
                $params = [
                    'ref_no' => $code,
                    'ie_flag' => 'I',
                    'ie_port' => '',
                    'platenumber' => $intoArea['car_number'],
                    'bg_company' => $bg_company,
                    'duty_mode'=>$duty_mode,
                    'trade_area_code'=>$trade_area_code,
                    'destination_port'=>$destination_port,
                    'destination_country'=>$destination_country
                ];
                $preEnter->setCompanyCode($bg_company);
                foreach ($intoAreaDetail as $detail) {
                    //$preEnter->setReceivingCode($detail['receiving_code']);
                    $preEnter->addReceivingCode($detail['receiving_code']);
                    $receivingInfo = $preEnter->getReceivingInfo($detail['receiving_code']);
                    $params['ie_port'] = $receivingInfo['ie_port'];
                    $params['pt_code'] = $receivingInfo['form_type'];
                }
                $preEnter->setParams($params);
                $preEnter->makePriEnter();
                $error = $preEnter->getError();
                if (!empty($error)) {
                    $return['error'] = $error;
                    //有错误回滚
                    $db->rollBack();
                } else {
                    $return['state'] = 1;
                    $return['message'] = "生成成功";
                    $db->commit();
                }
                //$db->commit();
            } catch (Exception $e) {
                $return['message'] = $e->getMessage();
                $db->rollBack();
            }
            die(Zend_Json::encode($return));
        }

        $this->view->district_code = Common_SelectMap::getdistrict_code();
        $this->view->type = Common_SelectMap::getEformType();
        $this->view->destination_port = Common_SelectMap::getdestination_port();
        $this->view->country = Service_Country::getByCondition(['trade_country_notempty' => 1]);

        $this->view->bgCompany = Common_SelectMap::getBgCompany();
        echo Ec::renderTpl($this->tplDirectory . 'icreate.tpl', 'layout');
    }

}
