<?php
/**
 * Class Clearance_BaoguanController
 * User: Yao
 * Date: 2021/10/26
 * Note: 报关单列表
 */
class Clearance_BaoguanController extends Ec_Controller_Action
{
    protected $tplDirectory = '';
    public function preDispatch() {
        $this->_userId = Service_User::getUserId();
        $this->tplDirectory = "clearance/views/baoguan/";
    }
    /**
     * Note:获取列表的提交参数，导出和查询都会用到，放在一个地方
     * User: Yao
     * Date: 2019/2/16
     * Time: 11:20
     */
    private function getCondition() {
        $condition = array();
        $dateFor = $this->_request->getParam('dateFor', '');
        $dateTo = $this->_request->getParam('dateTo', '');
        $isSearchDate = false;
        $conditionTemp['dateFor'] = !empty($dateFor) ? $dateFor : '';
        $conditionTemp['dateTo'] = !empty($dateTo) ? $dateTo : '';
        if (!empty($conditionTemp['dateFor'])) {
            $isSearchDate = true;
            $conditionTemp['dateFor'] = date('Y-m-d H:i:s', strtotime($conditionTemp['dateFor']));
        }
        if (!empty($conditionTemp['dateTo'])) {
            $isSearchDate = true;
            $conditionTemp['dateTo'] = date('Y-m-d H:i:s', strtotime($conditionTemp['dateTo']));
        }
        $params = $this->_request->getParams();
        Common_Common::trim_blank($params);
        $condition = $params;
        if ($isSearchDate) {
            if ($params['timeType'] == 1) {
                $condition['add_time_start'] = $conditionTemp['dateFor'];
                $condition['add_time_end'] = $conditionTemp['dateTo'];
            }
        }

        return $condition;
    }

    /**/
    public function listAction() {
        if ($this->_request->isPost()) {
            $return = array(
                "state" => 0,
                "message" => "No Data"
            );
            $page = $this->_request->getParam('page', 1);
            $pageSize = $this->_request->getParam('pageSize', 20);

            $page = $page ? $page : 1;
            $pageSize = $pageSize ? $pageSize : 20;
            $condition = $this->getCondition();
            $service = new Service_DesMessageHead();
            $showFields = [
                'dmh_id',
                'dmh_no',
                'seq_no',
                'ieflag',
                'iedate',
                'bill_no',
                'overseas_consignor_ename',
                'trade_country',
                'traf_name',
                'desp_date',
                'add_time',
                'des_status',
            ];
            $showFields =$service->getFieldsAlias($showFields);
            $count = Service_DesMessageHead::getByCondition($condition, 'count(*)');
            $return['total'] = $count;
            if ($count > 0) {
                $rows = Service_DesMessageHead::getByCondition($condition, $showFields, $pageSize, $page, 'dmh_id desc');
                $return['state'] = $count ? 1 : 0;
                $return['data'] = $rows;
            }
            $return['size'] = $pageSize;
            $return['page'] = $page;
            die(Zend_Json::encode($return));
        }
        echo Ec::renderTpl($this->tplDirectory . "list.tpl", 'layout');
    }
    /**
     * Note:导入报关单
     * User: Yao
     * Date: 2021/10/26
     * Time: 15:01
     */
    function importAction(){
        //error_reporting(E_ALL);
        //echo "<pre>";
        $return = [
            'state' => 0,
            'message' => '',
            'data' => [],
            'error' => [],
        ];
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            //echo "<pre>";
            $upload = new Process_Upload();
            $savePath = APPLICATION_PATH . '/../data/baoguan/';
            $uploadInfo = $upload->uploadXls($savePath, 'baoguan_file');
            if ($uploadInfo['state'] != 1) {
                throw new Exception($uploadInfo['message']);
            }
            $filePath = $uploadInfo['path'];
            $inv = new Process_BaoguanUpload();
            $inv->setFilePath($filePath);
            $baseInfo = $inv->getBaseInfo();
            $container = $inv->getContainers();
            //var_dump($container);
            $goodsLimitVin = $inv->getGoodslimitVin();
            $requestcert= $inv->getDecrequestCert();
            $goodsLimitType = $inv->getGoodsLimit();

            //自有文本
            $messageDecfreetxt = $inv->getMessageDecfreetxt();

            $invProcess = new Process_Baoguan();
            if(empty($baseInfo['head']) ||empty($baseInfo['bodyInfo'])){
                throw new Exception('基本信息或者商品信息为空');
            }
            $invProcess->setBaseinfo($baseInfo);
            $invProcess->setContainer($container);
            $invProcess->setGoodsLimitVin($goodsLimitVin);
            $invProcess->setDecrequestRert($requestcert);
            $invProcess->setGoodsLimitType($goodsLimitType);
            $invProcess->setMessageDecfreetxt($messageDecfreetxt);
            $error = $invProcess->validInfo();
            //print_r($baseInfo);
            //var_dump($error);
            //exit;
            if(!empty($error)){
                throw new Exception(implode("|",$error));
            }
            //经过校验和处理之后的数据
            $baseInfo = $invProcess->getBaseinfo();
            $goodsLimitVin = $invProcess->getGoodsLimitVin();
            //print_r($baseInfo);
            //exit;
            $invProcess->add($baseInfo['head'],$baseInfo['bodyInfo']);
            if(!empty($container)){
                $invProcess->addContainer($container);
            }
            if(!empty($goodsLimitVin)){
                $invProcess->addGoodsLimitVin($goodsLimitVin);
            }
            if(empty($requestcert)){
                $invProcess->addDecrequestRert($requestcert);
            }
            if(!empty($goodsLimitType)){
                $invProcess->addGoodsLimitType($goodsLimitType);
            }
            if(!empty($messageDecfreetxt)){
                $invProcess->addMessageDecfreetxt($messageDecfreetxt);
            }
            $return['state'] = 1;
            $return['message'] ='上传成功';
            $db->commit();
            //$db->rollBack();
        } catch (Exception $e) {
            $db->rollBack();
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * Note:详情查看
     * User: Yao
     * Date: 2019/12/27
     * Time: 14:48
     */
    public function viewAction() {
        $id = $this->_request->getParam('dmh_id', '');
        if (empty($id)) {
            $this->redirect("/default/error/error");
        }
        $baoguan = Service_DesMessageHead::getByField($id);
        if (empty($baoguan)) {
            $this->redirect("/default/error/error");
        }
        $detailTotal = Service_DesMessageList::getByCondition([
            'dmh_id' => $baoguan['dmh_id'],
        ],'count(*)');
        $goodsLimitType = Service_DesMessageGoodslimittype::getByCondition([
            'dmh_id'=>$baoguan['dmh_id']
        ]);
        $log = Service_DesMesssageLog::getByCondition([
            'dmh_id'=>$baoguan['dmh_id']
        ]);
        $this->view->goodsLimitType = $goodsLimitType;
        $this->view->baoguan = $baoguan;
        $this->view->detailTotal = $detailTotal;
        $this->view->log =$log;
        echo Ec::renderTpl($this->tplDirectory . 'detail.tpl', 'layout');
    }
    /**
     * Note:获取基本信息
     * User: Yao
     * Date: 2021/10/30
     * Time: 13:52
     */
    public function detailAction(){
        $return = [
            'state' => 0,
            'message' => '',
            'data' => [],
            'error' => [],
        ];
        try{
            $page = $this->_request->getParam('page','1');
            $pageSize = $this->_request->getParam('page_size','20');
            $pageSize = $pageSize>200?200:$pageSize;
            $dmhId = $this->_request->getParam('dmh_id');
            if(empty($dmhId)){
                throw new Exception('参数错误');
            }
            $detail = Service_DesMessageList::getByCondition([
                'dmh_id'=>$dmhId
            ],'*',$pageSize,$page);
            $return['data'] = $detail;
            $return['state'] =1 ;
            $return['message'] ='获取成功';
        }catch (Exception $e){
            $return['message'] = $e->getMessage();
            die(Zend_Json::encode($return));
        }
        die(Zend_Json::encode($return));
    }
    /**
     * @todo 生成报文
     */
    public function getXmlAction(){
        $return = [
            'state' => 0,
            'message' => '',
            'data' => [],
            'error' => [],
        ];
        error_reporting(E_ALL);
        header("Content-type:text/xml");
        //var_dump('dddd');
        //exit;
        //echo "<pre>";
        $dmhId = $this->_request->getParam('dmh_id');
        //$dmhId = 19;
        /*$dri = new Api_Des_Receiving();
        $xml = $dri->getXmlById($dmhId);
        file_put_contents($dmhId.'_20211211003.xml',$xml);
        echo $xml;
        exit;*/

        if ($this->_request->isPost()) {
            try{
                $dmhId = $this->_request->getParam('dmh_id');
                if(empty($dmhId)){
                    throw new Exception('参数错误');
                }
                $dri = Api_Des_Receiving($dmhId);
                $dri->getXmlById();
            }catch (Exception $e){
                $return['message'] = $e->getMessage();
                die(Zend_Json::encode($return));
            }
            die(Zend_Json::encode($return));
        }
    }
    /**
     * @todo 发送报文
     */
    public function sendXmlAction(){
        $return = [
            'state' => 0,
            'message' => '',
            'data' => [],
            'error' => [],
        ];
        //error_reporting(E_ALL);
        //header("Content-type:text/xml");
        //var_dump('dddd');
        //exit;
        $dmhId = $this->_request->getParam('dmh_id');
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        if ($this->_request->isPost()) {
            try{
                $dmhId = $this->_request->getParam('dmh_id');
                if(empty($dmhId)){
                    throw new Exception('参数错误');
                }
                $dmhRow = Service_DesMessageHead::getByField($dmhId);
                if(!(!empty($dmhRow) && $dmhRow['des_status']=='-1')){
                    throw new Exception('报关单必须存在且为未发送状态!');
                }
                $dri = new Api_Des_Receiving();
                $sendresult = $dri->sendbaoguandan($dmhId);
                $sendresultReturn = $dri->getResult();
                //var_dump($sendresult);
                if($sendresult){
                    $return['message'] = "发送单一任务成功";
                    $return['state'] = 1;
                    $row = array(
                        'des_status'=>'1',
                        'update_time'=>date("Y-m-d H:i:s",time())
                    );
                    Service_DesMessageHead::update($row,$dmhId,'dmh_id');
                    //写日志
                    $messageLog = array(
                        'note'=>"发送单一窗口报文",
                        'add_time'=>date("Y-m-d H:i:s",time()),//$dmhRow['des_status'],
                        'state_from'=>$dmhRow['des_status'],
                        'state_to'=>'1',
                        'user_id'=>$this->_userId,
                        'type'=>'-1',
                        'file_path'=>$dri->getFile(),
                    );
                    Service_DesMesssageLog::add($messageLog);
                }else{
                    throw new Exception("发送单一任务失败:".$sendresultReturn['message']);
                }
                $db->rollBack();
                //$db->commit();
            }catch (Exception $e){
                $return['message'] = $e->getMessage();
                $db->rollBack();
                die(Zend_Json::encode($return));
            }
            die(Zend_Json::encode($return));
        }
    }
    /**
     * @todo 处理报关单
     */
    public function parseAction(){
        /*$dri = new Api_Des_Receiving();
        $sendresult = $dri->parsebaoguandan();
        var_dump($sendresult);*/
    }
    /**
     * @todo 删除报关单
     */
    public function deletebaoguanAction(){
        $return = [
            'state' => 0,
            'message' => '',
            'data' => [],
            'error' => [],
        ];
        //error_reporting(E_ALL);
        //header("Content-type:text/xml");
        //var_dump('dddd');
        //exit;
        $dmhId = $this->_request->getParam('dmh_id');
        $error = [];
        if ($this->_request->isPost()) {
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try{
                if($dmhId>0){
                    $decMessageHead = Service_DesMessageHead::getByField($dmhId,'dmh_id');
                    if(empty($decMessageHead)){
                        $error[] = "参数无效找不到对应的报关单表头信息";
                    }else{
                        if($decMessageHead['des_status']!='-1'){
                            $error[] = "报关单状态不能删除";
                        }
                        if($decMessageHead['bpedbh_id']>0){
                            $bgedh = Service_BgPriEntryDataDetailBodyHead::getByField($decMessageHead['bpedbh_id'],'bpedbh_id');
                        }
                    }
                }else{
                    $error[] = "参数错误";
                }
                if(!empty($error)){
                    throw new Exception(implode("|",$error));
                }else{
                    Service_DesMessageHead::delete($dmhId,'dmh_id');
                    Service_DesMessageList::delete($dmhId,'dmh_id');
                    Service_DesMessageContainers::delete($dmhId,'dmh_id');
                    //更新信息
                    if(!empty($bgedh)){
                        $preDataHeadUpdate = array(
                            'bg_status'=>'-1',
                            'baoguan_code'=>''
                        );
                        Service_BgPriEntryDataDetailBodyHead::update($preDataHeadUpdate,$bgedh['bpedbh_id'],'bpedbh_id');
                        //添加日志
                        $detailLog = array(
                            'bped_id'=>$bgedh['bped_id'],
                            'bpedbh_id'=>$bgedh['bpedbh_id'],
                            'change_status'=>'bg_status',
                            'status_from'=>$bgedh['bg_status'],
                            'status_to'=>'-1',
                            'ip'=>Common_Common::getIP(),
                            'content'=>"报关单删除,更新预录入数据状态",
                        );
                        Service_BgPriEntryDataDetailLog::add($detailLog);
                    }
                }
                $return['state'] = 1;
                $return['message'] = "删除成功";
                //$db->rollBack();
                $db->commit();
            }catch (Exception $e){
                $return['message'] = $e->getMessage();
                $db->rollBack();
            }
            die(json_encode($return));
        }
    }

}