<?php

/**
 * Class Clearance_DesMessageController
 * User: Yao
 * Date: 2019/12/27
 * Note:核注清单
 */
class Clearance_InvController extends Ec_Controller_Action
{
    protected $tplDirectory = '';

    public function preDispatch() {
        $this->tplDirectory = "clearance/views/inv/";
    }

    /**
     * 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);
        $service = new Service_InvtList();
        $condition = $service->getMatchFields($params);
        if ($isSearchDate) {
            $condition['dateFor'] = $conditionTemp['dateFor'];
            $condition['dateTo'] = $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();
            $showFields = array(
                'il_id',
                'BondInvtNo',
                'EtpsInnerInvtNo',
                'DclTypecd',
                'ImpexpMarkcd',
                'add_time',
                'batch_code',
                'status',
                'PutrecNo',
            );
            $service = new Service_InvtList();
            $showFields = $service->getFieldsAlias($showFields);
            $count = Service_InvtList::getByCondition($condition, 'count(*)');
            $return['total'] = $count;
            if ($count > 0) {
                $rows = Service_InvtList::getByCondition($condition, $showFields, $pageSize, $page, 'il_id desc');
                $return['state'] = $count ? 1 : 0;
                $return['data'] = $rows;
            }
            $return['dcl_typecd_stauts'] = Service_InvtList::getdclTypecdStatus();
            $return['im_exp_markcd_status'] = Service_InvtList::getImepexpMarkcdStatus();
            $return['status'] = Service_InvtList::getStatus();
            $return['size'] = $pageSize;
            $return['page'] = $page;
            die(Zend_Json::encode($return));
        }
        echo Ec::renderTpl($this->tplDirectory . "list.tpl", 'layout');
    }

    /**
     * Note:批量确认
     * User: Yao
     * Date: 2020/8/8
     * Time: 10:04
     */
    public function batchConfirmAction() {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        try {
            $invtIdList = $this->_request->getParam('invt_id');
            if (empty($invtIdList)) {
                throw new Exception('请选择要提交的核注清单');
            }
            $total = 0;
            $success = 0;
            $invtIdList = explode(',', $invtIdList);
            foreach ($invtIdList as $invId) {
                $total++;
                $db = Common_Common::getAdapter();
                $db->beginTransaction();
                try {
                    $invList = Service_InvtList::getByField($invId);
                    if (empty($invList)) {
                        throw new Exception('参数错误');
                    }
                    $invtManifest = Service_InvtManifiestInvt::getByField($invList['EtpsInnerInvtNo'], 'etps_inner_invt_no');
                    if ($invtManifest) {
                        $manifest = Service_InvtManifiest::getByField($invtManifest['im_id']);
                        if ($manifest['im_type'] == '2' && $invList['ImpexpMarkcd'] == 'I') {
                            $invtManifestList = Service_InvtManifiestInvt::getByCondition([
                                'im_id' => $manifest['im_id']
                            ]);
                            foreach ($invtManifestList as $mInv) {
                                if ($mInv['etps_inner_invt_no'] != $invList['EtpsInnerInvtNo']) {
                                    // $manifest = Service_InvtList::getByField($mInv['etps_inner_invt_no'], 'EtpsInnerInvtNo');
                                    // if ($manifest['ImpexpMarkcd'] == 'E' && $manifest['zb_status'] != 1) {
                                    //     throw new Exception($manifest['EtpsInnerInvtNo'].'需综保系统先核扣成功才可以确认');
                                    // }
                                }
                            }
                        }
                    }
                    $inv = new Process_Inv();
                    $result = $inv->confirm($invList);
                    if ($result !== true) {
                        throw new Exception('确认失败:' . $result);
                    }
                    $db->commit();
                    //$db->rollBack();
                    $success++;
                } catch (Exception $e) {
                    $db->rollBack();
                    $return['data'][] = $invList['EtpsInnerInvtNo'] . $e->getMessage();
                }
            }
            $return['state'] = 1;
            $return['message'] = "操作成功【" . $success . "】条记录,失败【" . ($total - $success) . "】条记录";
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * Note:核注清单完成
     * User: Yao
     * Date: 2020/8/8
     * Time: 10:58
     */
    public function completeAction() {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $invtId = $this->_request->getParam('inv_id');
            $boundInvtNo = $this->_request->getParam('bound_invt_no');
            if (empty($invtId)) {
                throw new Exception('请选择要提交的核注清单');
            }
            $invList = Service_InvtList::getByField($invtId);
            if (empty($invList)) {
                throw new Exception('参数错误');
            }
            if(empty($invList['BondInvtNo'])){
                if(empty($boundInvtNo)){
                    throw new Exception('核注清单海关编号为空');
                }else{
                    $update = [
                        'BondInvtNo'=>trim($boundInvtNo)
                    ];
                    Service_InvtList::update($update,$invList['il_id']);
                }

            }
            $inv = new Process_Inv();
            $result = $inv->complete($invList);
            if ($result !== true) {
                throw new Exception('完成失败');
            }
            $return['state'] = 1;
            $return['message'] = "操作成功";
            $db->commit();
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
            $db->rollBack();
        }
        die(Zend_Json::encode($return));
    }
    /**
     * Note:获取核注清单信息
     * User: Yao
     * Date: 2021/5/7
     * Time: 11:39
     */
    public function getAction() {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $invtId = $this->_request->getParam('inv_id');
            if (empty($invtId)) {
                throw new Exception('请选择核注清单');
            }
            $invList = Service_InvtList::getByField($invtId);
            if (empty($invList)) {
                throw new Exception('参数错误');
            }
            $return['data']['BondInvtNo']=$invList['BondInvtNo'];
            $return['state'] = 1;
            $return['message'] = "操作成功";
            $db->commit();
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
            $db->rollBack();
        }
        die(Zend_Json::encode($return));
    }


    /**
     * Note:添加
     * User: Yao
     * Date: 2020/8/10
     * Time: 11:54
     */
    public function addAction() {
        $return = [
            'state' => 0,
            'message' => ''
        ];
        $id = $this->_request->getParam('id', '');
        if ($this->_request->isPost()) {
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                $params = $this->_request->getParams();
                Common_Common::trim_blank($params);
                $data = $params['detail'];
                unset($params['detail']);
                $body = json_decode($data, true);
                $inv = new Process_Inv();
                if (empty($body)) {
                    throw new Exception('请添加表体信息');
                }
                $headerError = $inv->validateHeadInfo($params);
                $bodyError = [];
                if (empty($headerError)) {
                    if ($params['impexp_markcd'] == 'I') {
                        $bodyError = $inv->validateInBodyInfo($body, $params['bwl_no']);
                    } else {
                        $bodyError = $inv->validateOutBodyInfo($body, $params['bwl_no']);
                    }
                }
                if ($params['impexp_markcd'] == 'I') {

                    $fatalError = $bodyError['error'];
                    $warnError = $bodyError['warn_error'];
                    $error = array_merge($headerError, $fatalError);
                    if (!empty($error)) {
                        throw new Exception(implode('<br/>', $error));
                    } elseif (!empty($warnError) && $params['force_submit'] != 1) {
                        $return['state'] = 2;
                        throw new Exception(implode('<br/>', $warnError));
                    } else {
                        $code = $inv->doSave($params, $body);
                        $db->commit();
                        $return['state'] = 1;
                        $return['message'] = "添加成功：企业内部单号【" . $code . "】";
                    }
                } else {
                    $error = array_merge($bodyError, $headerError);
                    if (!empty($error)) {
                        throw new Exception(implode('<br/>', $error));
                    }
                    $code = $inv->doSave($params, $body);
                    $db->commit();
                    $return['state'] = 1;
                    $return['message'] = "添加成功：企业内部单号【" . $code . "】";
                }

            } catch (Exception $e) {
                $db->rollBack();
                $return['message'] = $e->getMessage();
            }
            die(Zend_Json::encode($return));
        }
        $this->view->ilId = empty($id) ? '' : $id;
        $this->view->transMethod = Service_InvtList::getTrspMethod();
        $this->view->country = Service_Country::getByCondition([
            'trade_country_not_empty' => true,
        ]);
        $this->view->portcd = Service_InvtList::getImexpPortcd();
        $this->view->supvmod = Service_InvtList::getsupvModecd();
        $this->view->dclusType = Service_InvtList::getDclcusType();
        $this->view->decType=Service_InvtList::getDecType();
        $this->view->invtType = Service_InvtList::getInvtType();//清单类型
        echo Ec::renderTpl($this->tplDirectory . 'add.tpl', 'layout');
    }

    /**
     * Note:编辑
     * User: Yao
     * Date: 2020/8/12
     * Time: 15:35
     */
    public function editAction() {
        $return = [
            'state' => 0,
            'message' => ''
        ];
        if ($this->_request->isPost()) {
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                $params = $this->_request->getParams();
                Common_Common::trim_blank($params);
                $data = $params['detail'];
                unset($params['detail']);
                $body = json_decode($data, true);
                $inv = new Process_Inv();
                if (empty($params['il_id'])) {
                    throw  new Exception('系统异常');
                }
                if (empty($body)) {
                    throw new Exception('请添加表体信息');
                }
                $headerError = $inv->validateHeadInfo($params);
                $bodyError = [];
                if (empty($headerError)) {
                    if ($params['impexp_markcd'] == 'I') {
                        $bodyError = $inv->validateInBodyInfo($body, $params['bwl_no']);
                        $bodyError = $bodyError['error'];
                    } else {
                        $bodyError = $inv->validateOutBodyInfo($body, $params['bwl_no']);
                    }
                }
                $error = array_merge($bodyError, $headerError);
                if (!empty($error)) {
                    throw new Exception(implode('<br/>', $error));
                }
                $code = $inv->doEdit($params, $body);
                $db->commit();
                $return['state'] = 1;
                $return['message'] = "编辑成功：企业内部单号【" . $code . "】";
            } catch (Exception $e) {
                $db->rollBack();
                $return['message'] = $e->getMessage();
            }
            die(Zend_Json::encode($return));
        }
    }

    /**
     * Note:反填备案序号
     * User: Yao
     * Date: 2020/9/2
     * Time: 16:59
     */
    public function refillRecodeAction() {
        $return = [
            'state' => 0,
            'message' => ''
        ];
        if ($this->_request->isPost()) {
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                $params = $this->_request->getParams();
                Common_Common::trim_blank($params);
                $data = $params['detail'];
                unset($params['detail']);
                $body = json_decode($data, true);
                $inv = new Process_Inv();
                if (empty($params['il_id'])) {
                    throw  new Exception('系统异常');
                }
                if (empty($body)) {
                    throw new Exception('请添加表体信息');
                }
                $headerError = $inv->validateHeadInfo($params);
                $bodyError = [];
                if (empty($headerError)) {
                    if ($params['impexp_markcd'] == 'I') {
                        $bodyError = $inv->validateInBodyInfo($body, $params['bwl_no']);
                    } else {
                        throw new Exception('出区核注清单不支持此操作');
                    }
                }
                $error = array_merge($bodyError['error'], $headerError);
                if (!empty($error)) {
                    throw new Exception(implode('<br/>', $error));
                }
                $code = $inv->reFillRecodeNo($params, $body);
                $db->commit();
                $return['state'] = 1;
                $return['message'] = "反填备案号成功：企业内部单号【" . $code . "】";
            } catch (Exception $e) {
                $db->rollBack();
                $return['message'] = $e->getMessage();
            }
            die(Zend_Json::encode($return));
        }
    }

    /**
     * Note:导入数据模板
     * User: Yao
     * Date: 2020/8/10
     * Time: 11:54
     */
    public function importAction() {
        $return = [
            'state' => 0,
            'message' => '',
            'data' => [],
            'error' => [],
        ];
        try {
            $upload = new Process_Upload();
            $savePath = APPLICATION_PATH . '/../data/inv-list/';
            $uploadInfo = $upload->uploadXls($savePath, 'inv_file');
            if ($uploadInfo['state'] != 1) {
                throw new Exception($uploadInfo['message']);
            }
            $filePath = $uploadInfo['path'];
            $inv = new Process_InvUpload();
            $inv->setFilePath($filePath);
            $headInfo = $inv->getHeadInfo();
            $bodyInfo = $inv->getBodyInfo();

            $invProcess = new Process_Inv();
            $headInfo = $inv->convertToDbInfo($headInfo);
            if (empty($bodyInfo)) {
                throw new Exception('请上传表体信息');
            }
            $headerError = $invProcess->validateHeadInfo($headInfo);
            $bodyError = [];
            if (empty($headerError)) {
                if ($headInfo['impexp_markcd'] == 'I') {
                    $bodyError = $invProcess->validateInBodyInfo($bodyInfo, $headInfo['bwl_no']);
                } else {
                    $bodyError = $invProcess->validateOutBodyInfo($bodyInfo, $headInfo['bwl_no']);
                }
            }
            if ($headInfo['impexp_markcd'] == 'I') {
                $fatalError = $bodyError['error'];
                $warnError = $bodyError['warn_error'];
                $error = array_merge($headerError, $fatalError);
                if (!empty($error)) {
                    $return['error'] = $error;
                } elseif (!empty($warnError)) {
                    $return['error'] = $warnError;
                    $return['state'] = 2;
                    $return['message'] = '上传信息请确认是否上传';
                    $return['data'] = [
                        'head' => $headInfo,
                        'body' => $bodyInfo
                    ];
                } else {
                    $return['state'] = 1;
                    $return['message'] = '上传成功';
                    $return['data'] = [
                        'head' => $headInfo,
                        'body' => $bodyInfo
                    ];
                }
            } else {
                $error = array_merge($headerError, $bodyError);
                if (!empty($error)) {
                    $return['error'] = $error;
                } else {
                    $return['state'] = 1;
                    $return['message'] = '上传成功';
                    $return['data'] = [
                        'head' => $headInfo,
                        'body' => $bodyInfo
                    ];
                }
            }
        } catch (Exception $e) {
            $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('id', '');
        if (empty($id)) {
            $this->redirect("/default/error/error");
        }
        $invList = Service_InvtList::getByField($id);
        if (empty($invList)) {
            $this->redirect("/default/error/error");
        }
        $stripCountry =[];
        if($invList['StshipTrsarvNatcd']) {
            $stripCountry = Service_Country::getByField($invList['StshipTrsarvNatcd'], 'trade_country');
        }
        $log = Service_InvtListLog::getByCondition([
            'il_id' => $invList['il_id']
        ], '*', '', '', "ill_id desc");
        $invtManifestInvt = Service_InvtManifiestInvt::getByCondition([
            'etps_inner_invt_no'=>$invList['EtpsInnerInvtNo'],
        ]);
        $this->view->invtManifestInvt = $invtManifestInvt[0];
        $this->view->invList = $invList;
        $this->view->dcltypecd = Service_InvtList::getdclTypecdStatus();//申报类型
        $this->view->invtType = Service_InvtList::getInvtType();//清单类型
        $this->view->dclusFlag = Service_InvtList::getDclusFlag();//
        $this->view->bwlType = Service_InvtList::getbwlType();
        $this->view->supvModecd = Service_InvtList::getsupvModecd();
        $this->view->trspModeecd = Service_InvtList::getTrspMethod();
        $this->view->mtpckEndprdMarkcd = Service_InvtList::getMtpckEndprdMarkd();
        $this->view->imepxpMarkcd = Service_InvtList::getImepexpMarkcdStatus();
        $this->view->impexpPortcd = Service_InvtList::getImexpPortcd();
        $this->view->genDecFlag = Service_InvtList::getGenDecFlag();
        $this->view->status = Service_InvtList::getStatus();
        $this->view->dclusType = Service_InvtList::getDclcusType();
        $this->view->decType=Service_InvtList::getDecType();
        $this->view->stripCountry = $stripCountry;
        $this->view->log = $log;
        echo Ec::renderTpl($this->tplDirectory . 'detail.tpl', 'layout');
    }

    /**
     * Note:表体的信息
     * User: Yao
     * Date: 2020/8/10
     * Time: 11:43
     */
    public function getDetailAction() {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        try {
            $id = $this->_request->getPost('inv_id');
            if (empty($id)) {
                throw new Exception('参数错误');
            }
            $showColumn = [
                'GdsSeqno' => 'gds_seqno',
                'EntryGdsSeqno' => 'entry_gds_seqno',
                'GdsMtno' => 'gds_mtno',
                'PutrecSeqno' => 'putrec_seqno',
                'ApplyNo' => 'ApplyTbSeqno',
                'Gdecd' => 'gdecd',
                'GdsNm' => 'gds_nm',
                'GdsSpcfModelDesc' => 'gds_spcf_model_desc',
                'Natcd' => 'natcd',
                'DestinationNatcd' => 'destination_natcd',
                'DclUnitcd' => 'dcl_unitcd',
                'DclQty' => 'dcl_qty',
                'LawfUnitcd' => 'lawf_unitcd',
                'LawfQty' => 'lawf_qty',
                'SecdLawfUnitcd' => 'secd_lawf_unitcd',
                'SecdLawfQty' => 'secd_lawf_qty',
                'DclCurrcd' => 'dcl_currcd',
                'DclUprcAmt' => 'dcl_uprc_amt',
                'DclTotalAmt' => 'dcl_total_amt',
                'UsdStatTotalAmt' => 'usd_stat_total_amt',
                'LvyrlfModecd' => 'lvyrlf_modecd',
                'GrossWt' => 'gross_wt',
                'NetWt' => 'net_wt',
                'UcnsVerno' => 'ucns_verno',
                'Rmk' => 'rmk',
            ];
            $column = [];
            foreach ($showColumn as $key => $as) {
                $column[] = $key . ' as ' . $as;
            }
            $invList = Service_InvtListBody::getByCondition([
                'il_id' => $id
            ], $column);
            if (empty($invList)) {
                throw new Exception('表体数据为空');
            }
            $return['state'] = 1;
            $return['data'] = $invList;
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * Note:表头信息
     * User: Yao
     * Date: 2020/8/10
     * Time: 18:20
     */
    public function getHeadInfoAction() {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        try {
            $id = $this->_request->getPost('inv_id');
            if (empty($id)) {
                throw new Exception('参数错误');
            }
            $showField = [
                'status' => 'status',
                'DclTypecd' => 'dcl_typecd',
                'BizopEtpsno' => 'bizop_etps_no',//经营企业编号
                'BizopEtpsNm' => 'bizop_etps_nm',//经营企业名称
                'BizopEtpsSccd' => 'bizop_etps_sccd',//经营企业社会信用代码
                // 'DclEtpsSccd'=>$headInfo['dcl_etps_sccd'],//申报企业社会信用代码
                'SupvModecd' => 'supv_modecd',//监管方式代码
                'TrspModecd' => 'trsp_modecd',
                'DclcusFlag' => 'dclcus_flag',
                'MtpckEndprdMarkcd' => 'mtpck_endprd_markcd',
                'ImpexpMarkcd' => 'impexp_markcd',
                'ImpexpPortcd' => 'impexp_portcd',
                'GenDecFlag' => 'gen_dec_flag',
                'bwl_type' => 'bwl_type',
                'InvtType' => 'invt_type',
                'bwl_no' => 'bwl_no',
                'add_time' => 'add_time',
                'StshipTrsarvNatcd' => 'stship_trsarv_natcd',
                'Rmk' => 'remark',
                'EntryNo'=>'entry_no',
                'RcvgdEtpsno' => 'rcvgd_etps_no',
                'DclcusTypecd'=>'dclcus_typecd',
                'RvsngdEtpsSccd' => 'rvsngd_etps_sccd',
                'RcvgdEtpsNm' => 'rcvgd_etps_nm',
                'RltInvtNo' => 'rlt_invt_no',
                'RltPutrecNo' => 'rlt_putrec_no',
                'RltEntryNo' => 'rlt_entry_no',
                'CorrEntryDclEtpsNo'=>'corr_entry_dcl_etps_no',
                'CorrEntryDclEtpsNm'=>'corr_entry_dcl_etps_nm',
                'CorrEntryDclEtpsSccd'=>'corr_entry_dcl_etps_sccd',
                'DecType'=>'dec_type',
            ];
            $column = [];
            foreach ($showField as $key => $filed) {
                $column[] = $key . ' as ' . $filed;
            }
            $invList = Service_InvtList::getByField($id, 'il_id', $column);
            if (empty($invList)) {
                throw new Exception('数据为空');
            }
            $return['state'] = 1;
            $return['data'] = $invList;
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    public function concelAction() {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $invtId = $this->_request->getParam('inv_id');
            if (empty($invtId)) {
                throw new Exception('请选择要提交的核注清单');
            }
            $invList = Service_InvtList::getByField($invtId);
            if (empty($invList)) {
                throw new Exception('参数错误');
            }
            $inv = new Process_Inv();
            $result = $inv->concel($invList);
            if ($result !== true) {
                throw new Exception('取消失败');
            }
            $return['state'] = 1;
            $message = "操作成功";
            if ($invList['status'] == 2 && $invList['ImpexpMarkcd'] == 'E') {
                $message .= ":请到综保系统取消该核注清单";
            }
            $return['message'] = $message;
            $db->commit();
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
            $db->rollBack();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * Note:
     * User: Yao
     * Date: 2020/8/21
     * Time: 17:15
     */
    public function makeXmlAction() {
        $id = $this->_request->getParam('id');
        $invtList = Service_InvtList::getByField($id);
        if (empty($invtList)) {
            $this->_redirect('/default/error/error');
        }
        $xml = new Api_Inv_Xml();
        $invHead = new Api_Inv_InvtHeadType();
        $invHead->setFromArray($invtList);
        $invListBody = Service_InvtListBody::getByCondition([
            'il_id' => $invtList['il_id']
        ]);
        $xml->setInvtHeadType($invHead);
        foreach ($invListBody as $body) {
            $invtListType = new Api_Inv_InvtListType();
            $invtListType->setFromArray($body);
            $xml->addInvtListType($invtListType);
        }
        $xmlString = $xml->toXml();
        header("Content-Type:text/xml;charsert=utf-8");
        echo $xmlString;
    }

    /**
     * Note:发送报文到综保系统
     * User: Yao
     * Date: 2020/8/24
     * Time: 17:04
     */
    public function sendAction() {
        $return = [
            'state' => 0,
            'message' => '',
        ];
        try {
            $id = $this->_request->getParam('inv_id');
            if (empty($id)) {
                throw new Exception('参数错误');
            }
            $invtList = Service_InvtList::getByField($id);
            if (empty($invtList)) {
                throw new Exception('参数错误');
            }
            $xml = new Api_Inv_Xml();
            $invHead = new Api_Inv_InvtHeadType();
            $invHead->setFromArray($invtList);
            $invListBody = Service_InvtListBody::getByCondition([
                'il_id' => $invtList['il_id']
            ]);
            $xml->setInvtHeadType($invHead);
            foreach ($invListBody as $body) {
                $invtListType = new Api_Inv_InvtListType();
                $invtListType->setFromArray($body);
                $xml->addInvtListType($invtListType);
            }
            $xmlString = $xml->toXml();
            $sendApi = new Api_Inv_Send();
            $result = $sendApi->send($xmlString);
            $return['state'] = $result['state'];
            $return['message'] = $result['message'];
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * Note:上传211报文
     * User: Yao
     * Date: 2021/1/26
     * Time: 14:58
     */
    public function uploadInv211Action() {
        $return = [
            'state' => 0,
            'check_res'=>0,
            'message' => 'error'
        ];
        try {
            $file = $_FILES['inv211'];
            if (empty($file)) {
                throw new Exception('上传文件为空');
            }
            if (!$file['size']) {
                throw new Exception('上传文件为空');
            }
            $tmpName = $file['tmp_name'];
            if (!$tmpName) {
                throw new Exception("上传文件为空");
            }
            if(!empty($file['error'])){
                throw new Exception('上传文件失败');
            }
            $fileName = $file['name'];
            $check = $this->_request->getParam('pre_check');
            $content = file_get_contents($tmpName);
            $data = simplexml_load_string(trim($content));
            $dataArray = Common_Common::objectToArray($data);
            $bussinessData = $dataArray['DataInfo']['BussinessData'];
            $hdeApprResult = $bussinessData['INV211']['BondInvtBsc'];
            $seqNo = $hdeApprResult['invtPreentNo'];
            if (empty($seqNo)) {
                throw new Exception('报文格式错误，统一编号为空');
            }
            $invtList = Service_InvtList::getByField($seqNo, 'SeqNo');
            if (empty($invtList)) {
                throw new Exception('统一编号为空');
            }
            if($check){
                $return=[
                    'state' =>1,
                    'check_res'=>1,
                    'data'=>[
                        'invt_no'=>$invtList['EtpsInnerInvtNo']
                    ]
                ];

                die(Zend_Json::encode($return));
            }else{
                $desDirectory =  $path = APPLICATION_PATH . '/../data/zb-xml/' . date("Y-m") . '/res/';
                if(!is_dir($desDirectory)){
                    mkdir($desDirectory,0777,true);
                }
                if(move_uploaded_file($file['tmp_name'],$desDirectory.'/'.$fileName)){
                    $db = Common_Common::getAdapter();
                    $db->beginTransaction();
                    try{
                        $invSend = new Api_Inv_Send();
                        $invSend->parseInv211($dataArray,$desDirectory.'/'.$fileName);
                        $db->commit();
                    }catch (Exception $e){
                        $db->rollBack();
                        throw new Exception('解析数据保存失败:'.$e->getMessage());
                    }

                }
            }
            $return['state'] = 1;
            $return['message'] = '解析反填备案序号成功，请查看';
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }
    /**
     * Note:导出核注清单
     * User: Yao
     * Date: 2021/7/19
     * Time: 9:28
     */
    function exportAction(){
        set_time_limit(3600);
        require_once "PHPExcel.php";
        require_once "PHPExcel/IOFactory.php";
        $path = APPLICATION_PATH . '/../data/xls/invt.xls';
        $excel = PHPExcel_IOFactory::load($path);
        $headSheet = $excel->getSheet(0);
        $bodySheet = $excel->getSheet(1);
        $orderSheet = $excel->getSheet(4);
        $id = $this->_request->getParam('inv_id');
        $invtList = Service_InvtList::getByField($id);
        if ($invtList) {
            $invtBody = Service_InvtListBody::getByCondition([
                'il_id' => $invtList['il_id']
            ]);
            $headSheet->setCellValue('B7', $invtList['InvtType']);//清单类型
            $headSheet->setCellValue('B9', $invtList['SupvModecd']);//监管方式
            $headSheet->setCellValue('B10', $invtList['ImpexpMarkcd']);//进出口标记（必填）
            $headSheet->setCellValue('B11', $invtList['ImpexpPortcd']);//进出境关别（必填）
            $headSheet->setCellValue('D9', $invtList['TrspModecd']);//运输方式（必填）
            $headSheet->setCellValue('D10', $invtList['DclcusFlag']);//报关标记（必填）
            $headSheet->setCellValue('D13', $invtList['GenDecFlag']);//是否生成报关单
            $headSheet->setCellValue('F9', $invtList['MtpckEndprdMarkcd']);//料件成品标记（必填）
            $headSheet->setCellValue('F6', $invtList['PutrecNo']);//底账海关编号（必填）
            $index = 2;
            foreach ($invtBody as $body) {
                $bodySheet->setCellValue('A' . $index, $body['GdsSeqno']);//序号
                $bodySheet->setCellValue('B' . $index, $body['PutrecSeqno']);//备案序号
                $bodySheet->setCellValue('C' . $index, $body['GdsMtno']);//商品料号
                $bodySheet->setCellValueExplicit('D' . $index, $body['Gdecd'],PHPExcel_Cell_DataType::TYPE_STRING);//商品编码(必填)
                $bodySheet->setCellValue('E' . $index, $body['GdsNm']);//商品名称
                $bodySheet->setCellValue('F' . $index, $body['GdsSpcfModelDesc']);//规格型号
                $bodySheet->setCellValueExplicit('G' . $index, $body['DclUnitcd'],PHPExcel_Cell_DataType::TYPE_STRING);//申报单位
                $bodySheet->setCellValueExplicit('H' . $index, $body['LawfUnitcd'],PHPExcel_Cell_DataType::TYPE_STRING);//法定单位
                $bodySheet->setCellValueExplicit('I' . $index, $body['SecdLawfUnitcd'],PHPExcel_Cell_DataType::TYPE_STRING);//法定第二单位
                $bodySheet->setCellValueExplicit('J' . $index, $body['Natcd'],PHPExcel_Cell_DataType::TYPE_STRING);//国别
                $bodySheet->setCellValue('K' . $index, $body['DclUprcAmt']);//申报单价
                $bodySheet->setCellValue('L' . $index, $body['DclTotalAmt']);//申报总价
                $bodySheet->setCellValueExplicit('M' . $index, $body['DclCurrcd'],PHPExcel_Cell_DataType::TYPE_STRING);//申报币制
                $bodySheet->setCellValue('N' . $index, $body['DclQty']);//申报数量
                $bodySheet->setCellValue('O' . $index, $body['LawfQty']);//法定数量
                $bodySheet->setCellValueExplicit('P' . $index, $body['SecdLawfQty'],PHPExcel_Cell_DataType::TYPE_STRING);//第二法定数量
                $bodySheet->setCellValue('Q' . $index, $body['WtSfVal']>0?:'');//重量比例因子
                $bodySheet->setCellValue('R' . $index, $body['FstSfVal']>0?:'');//第一比例因子
                $bodySheet->setCellValue('S' . $index, $body['SecdSfVal']>0?:'');//第二比例因子
                $bodySheet->setCellValue('T' . $index, $body['GrossWt']>0?:'');//毛重
                $bodySheet->setCellValue('U' . $index, $body['NetWt']);//净重
                $bodySheet->setCellValue('V' . $index, $body['UseCd']);//用途
                $bodySheet->setCellValue('W' . $index, $body['LvyrlfModecd']);//征免方式
                $bodySheet->setCellValue('X' . $index, $body['UcnsVerno']);//单耗版本号
                $bodySheet->setCellValue('Y' . $index, $body['EntryGdsSeqno']);//报关单商品序号
                $bodySheet->setCellValue('Z' . $index, $body['ApplyNo']);//申请表序号
                $bodySheet->setCellValue('AA' . $index, $body['Rmk']);//备注
                $bodySheet->setCellValue('AB' . $index, $body['DestinationNatcd']);//最终目的国
                $index++;
            }
            $invOrder= Service_InvtOrderSb::getByCondition([
                'EtpsInnerInvtNo'=>$invtList['EtpsInnerInvtNo'],
                'ios_status_neq'=>4,
            ]);
            $index = 2;
            foreach ($invOrder as $io){
                $orderSheet->setCellValue('A' . $index, $io['form_id_port']);//核注清单编号
                $index++;
            }
        }
        $filename =  $invtList['EtpsInnerInvtNo'].'.xls';
        $filename = mb_convert_encoding($filename, 'gbk');
        $writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Type: application/force-download');
        header("Content-Disposition: attachment;filename=\"$filename\"");
        header("Content-Transfer-Encoding: binary");
        header('Cache-Control: max-age=0');
        $writer->save('php://output');
    }

    /**
     * Note:手工放行
     * User: Yao
     * Date: 2021/10/18
     * Time: 10:56
     */
    public function passAction(){
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            $invtId = $this->_request->getParam('passs_inv_id');
            $seqNo = $this->_request->getParam('seg_no');
            $boundInvtNo = $this->_request->getParam('bound_invt_no');
            if (empty($invtId)) {
                throw new Exception('请选择核注清单');
            }
            $invList = Service_InvtList::getByField($invtId);
            if (empty($invList)) {
                throw new Exception('参数错误');
            }
            if(empty($invList['BondInvtNo'])){
                if(empty($boundInvtNo)){
                    throw new Exception('核注清单海关编号为空');
                }
            }
            if($invList['ImpexpMarkcd']!='E' && $invList['']!='8'){
                //throw new Exception('非BBC核注清单，无法进行此操作');
            }
            if(empty($seqNo)){
                throw new Exception("请填写清单预录入统一编号");
            }
            $update=[
                'BondInvtNo'=>trim($boundInvtNo),
                'SeqNo'=>$seqNo,
                'zb_status'=>'5',
            ];
            $result= Service_InvtList::update($update,$invtId);
            if (!$result) {
                throw new Exception('放行失败，请检查该核注清单是否已经放行');
            }
            $log = [
                'il_id' => $invList['il_id'],
                'note' => '手工放行',
                'add_time' => date("Y-m-d H:i:s"),
                'status_from' => $invList['status'],
                'status_to' =>$invList['status'],
                'operater'=>Service_User::getUserId(),
            ];
            Service_InvtListLog::add($log);
            $return['state'] = 1;
            $return['message'] = "操作成功";
            $db->commit();
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
            $db->rollBack();
        }
        die(Zend_Json::encode($return));
    }

    public function differAction(){
        $file1 = 'E:/ftp/INV101.1658067114.20.xml';
        $file2 ='E:/资料信息/报文回执/报文回执/核注单/Sas/SentBox/2022-07-15/SAS_INV101_EPORT_202207151121289583_202207151121536020329/SAS_INV101_EPORT_202207151121289583.xml';
        $content = file_get_contents($file1);
        $array1 = Common_Common::simpleXmlToArray($content);
        $content2 = file_get_contents($file2);
        $array2 = Common_Common::simpleXmlToArray($content2);
        echo "<Pre>";
//        var_dump($array2);
        $headInfo = $array2['Object']['Package']['DataInfo']['BussinessData']['InvtMessage']['InvtHeadType'];
        $invtList = $array2['Object']['Package']['DataInfo']['BussinessData']['InvtMessage']['InvtListType'];

        $head2 = $array1['BussinessData']['InvtMessage']['InvtHeadType'];
        $invtList2 = $array1['BussinessData']['InvtMessage']['InvtListType'][0];


        $headInfo = array_keys($headInfo);
        $head2 = array_keys($head2);
        var_dump(array_diff($headInfo,$head2)+array_diff($head2,$headInfo));
        $invtList2 = array_keys($invtList2);
        $invtList = array_keys($invtList);
        var_dump(array_diff($invtList,$invtList2)+array_diff($invtList2,$invtList));
    }

    /**
     * @date 2022/7/18
     * @todo 解析测试文件
     * @auther 46935
     */
    public function paserAction(){
        error_reporting(E_ALL);
        $file ='E:/资料信息/报文回执/报文回执/核注单/Sas/InBox/Receipt_CUS0000E0100002022071515583400531920045_20220715155856808554549.INV';
        $file ='E:/资料信息/报文回执/报文回执/核注单/Sas/InBox/test.xml';
        $file ='E:/www/zhwms/branches/data/开发文档/Failed_INV101.1658317197.34.xml_2022072019451107906888.xml';
        $parser = new Api_Inv_Send();
        $content = file_get_contents($file);
        $parser->parseCommonResponse(Common_Common::simpleXmlToArray($content),$file);
    }

}
