<?php

/**
 * Class Clearance_InvSbController
 * Date: 2020/12/21
 * Note:核放单创建
 */
use Customs\Dg\Hmzb\InvtSb\Xml;
use Customs\Dg\Hmzb\InvtSb\PassportHead;
use Customs\Dg\Hmzb\InvtSb\PassportList;
use Customs\Dg\Hmzb\InvtSb\PassportAcmp;
use Customs\Dg\Hmzb\InvtSb\Send;
class Clearance_InvSbController extends Ec_Controller_Action
{
    protected $tplDirectory = '';

    public function preDispatch() {
        $this->tplDirectory = "clearance/views/inv-sb/";
    }

    /**
     * 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_InvtSb();
        $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(
                'is_id',
                'EtpsPreentNo',
                'PassportTypecd',
                'is_status',
                'VehicleNo',
                'BindTypecd',
                'IoTypecd',
                'DclTime',
                'sb_mode',
                'batch_code',
            );
            $service = new Service_InvtSb();
            $showFields = $service->getFieldsAlias($showFields);
            $count = Service_InvtSb::getByCondition($condition, 'count(*)');
            $return['total'] = $count;
            if ($count > 0) {
                $rows = Service_InvtSb::getByCondition($condition, $showFields, $pageSize, $page, 'is_id desc');
                $return['state'] = $count ? 1 : 0;
                $return['data'] = $rows;
            }
            $return['IoTypecd_stauts'] = Service_InvtSb::getioTypecd();
            $return['passportTypecd_status'] = Service_InvtSb::getpassportTypecd();
            //$return['im_exp_markcd_status'] = Service_InvtList::getImepexpMarkcdStatus();
            $return['status'] = Service_InvtSb::getStatus();
            $return['sb_mode'] = Service_InvtSb::getSbMode();
            $return['size'] = $pageSize;
            $return['page'] = $page;
            die(Zend_Json::encode($return));
        }
        $this->view->passportTypecd = Service_InvtSb::getpassportTypecd();
        $this->view->bindTypecd = Service_InvtSb::getbindTypecd();
        $this->view->rltTbTypecd = Service_InvtSb::getrltTbTypecd();
        $this->view->ioTypecd = Service_InvtSb::getioTypecd();
        echo Ec::renderTpl($this->tplDirectory . "list.tpl", 'layout');
    }
    /**
     * Note:添加
     * User: Yao
     * Date: 2020/8/10
     * Time: 11:54
     */
    public function addAction() {
        //echo "<pre>";
        //error_reporting(E_ALL);
        $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);
                /*print_r($params);
                exit;*/
                $detail = array();
                if(isset($params['detail'])){
                    $data = $params['detail'];
                    unset($params['detail']);
                    $detail = json_decode($data,true);
                }
                //var_dump($data);
                /*var_dump($body);
                exit;*/
                $inv = new Process_InvtSb();
                if(empty($detail)&&$params['bindTypecd']=='3'){
                    throw new Exception('一票多车表体商品项需要填写');
                }
                $headerError = $inv->validateHeadInfo($params,$detail);
                /*var_dump($headerError);
                exit;*/
                $bodyError =[];
                if(empty($headerError)) {
                    if(!empty($detail)&&$params['bindTypecd']=='3'){
                        $bodyError = $inv->validateBodyInfo($detail);
                    }
                }
                $hzRows = explode("/",$params['rltNo']);


                if($params['ioTypecd'] == 'I'){
                    if(isset($bodyError['error'])){
                        $fatalError = $bodyError['error'];
                    }
                    if(isset($bodyError['warn_error'])){
                        $warnError = $bodyError['warn_error'];
                    }
                    if(!empty($bodyError)){
                        $error = array_merge($headerError,$fatalError);
                    }else{
                        $error = $headerError;
                    }
                    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,$hzRows,$detail);
                        $db->commit();
                        //$db->rollBack();
                        $return['state'] = 1;
                        $return['message'] = "添加核放单成功：企业内部单号【".$code."】";
                    }
                }else {
                    if(!empty($bodyError)){
                        $error = array_merge($bodyError['error'], $headerError);
                    }
                    if (!empty($error)) {
                        throw new Exception(implode('<br/>', $error));
                    }
                    $code = $inv->doSave($params,$hzRows,$detail);
                    $db->commit();
                    //$db->rollBack();
                    $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->passportTypecd = Service_InvtSb::getpassportTypecd();
        $this->view->bindTypecd = Service_InvtSb::getbindTypecd();
        $this->view->rltTbTypecd = Service_InvtSb::getrltTbTypecd();
        $this->view->ioTypecd = Service_InvtSb::getioTypecd();

        /*$this->view->country = Service_Country::getByCondition([
            'trade_country_not_empty'=>true,
        ]);*/
        $this->view->portcd = Service_InvtList::getImexpPortcd();
        echo Ec::renderTpl($this->tplDirectory . 'add.tpl', 'layout');
    }
    /**
     * Note:从汇单号创建核放单
     * User: Yao
     * Date: 2021/4/30
     * Time: 16:04
     */
    public function createFromSbAction(){
        $imCode = $this->_request->getParam('im_code','');
        if(empty($imCode)){
            $this->_redirect('/default/error/error/error_msg/汇单号为空');
        }
        $mainifest = Service_InvtManifiest::getByField($imCode,'im_code');
        if(empty($mainifest)){
            $this->_redirect('/default/error/error/error_msg/汇单不存在');
        }
        if($mainifest['im_status']!=1){
            $this->_redirect('/default/error/error/error_msg/汇单未生成核注清单');
        }
        $manifestInvt = Service_InvtManifiestInvt::getByCondition([
            'im_id'=>$mainifest['im_id']
        ]);
        $totalNetWeight = 0;
        $rltNo=[];
        foreach($manifestInvt as $mdetail){
            $invt = Service_InvtList::getByField($mdetail['etps_inner_invt_no'],'EtpsInnerInvtNo');
            if(!$invt['BondInvtNo']){
                $this->_redirect('/default/error/error/error_msg/核注清单海关编号不存在');
            }
            $netWeight = Service_InvtListBody::getByCondition([
                'il_id'=>$invt['il_id']
            ],'sum(NetWt) as totalNet');
            $totalNetWeight+=$netWeight[0]['totalNet'];
            $rltNo[]=$invt['BondInvtNo'];
        }
        $this->view->rltNo=implode('/',$rltNo);
        $this->view->totalNetWeight = $totalNetWeight;
        $this->view->passportTypecd = Service_InvtSb::getpassportTypecd();
        $this->view->bindTypecd = Service_InvtSb::getbindTypecd();
        $this->view->rltTbTypecd = Service_InvtSb::getrltTbTypecd();
        $this->view->ioTypecd = Service_InvtSb::getioTypecd();
        $this->view->imCode = $imCode;
        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_InvtSb();
                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 {
                        $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/8/10
     * Time: 11:54
     */
    public function importAction() {
        //echo "<pre>";
        $return = [
            'state' => 0,
            'message' => '',
            'data' => [],
            'error'=>[],
        ];
        try {
            $upload = new Process_Upload();
            $savePath = APPLICATION_PATH . '/../data/inv-sb/';
            $uploadInfo = $upload->uploadXls($savePath, 'inv_file');
            if ($uploadInfo['state'] != 1) {
                throw new Exception($uploadInfo['message']);
            }
            $filePath = $uploadInfo['path'];
            $invsb = new Process_InvSbUpload();
            $invsb->setFilePath($filePath);
            $bodyInfo = $invsb->getBodyInfo();
            $headInfo = $invsb->getHeadInfo();
            $realationInfo = $invsb->getRealation();
            $bussinessType ='';
            foreach ($realationInfo as $relate){
                if(!$bussinessType){
                    $bussinessType =$relate['bussiness_type'];
                }else{
                    if($bussinessType!=$relate['bussiness_type']){
                        throw new Exception('关联单证类型不是同一种');
                    }
                }
            }
            $return['state'] = 1;
            $return['message'] = '上传成功';
            $return['data'] = [
                'head'=>$headInfo,
                'relationInfo'=>$realationInfo,
                '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");
        }
        $invSbList = Service_InvtSb::getByField($id);
        if (empty($invSbList)) {
            $this->redirect("/default/error/error");
        }
        $log = Service_InvtSbLog::getByCondition([
            'is_id'=>$invSbList['is_id']
        ],'*','','',"isl_id desc");
        //查看核放单和核注清单关联关系
        $invtManifestInvt = Service_InvtSbInvtlist::getByCondition([
            'is_id'=>$invSbList['is_id']
        ]);
        //查看核放单表体信息
        Service_InvtSbDetail::getByCondition([
            'is_id'=>$invSbList['is_id']
        ]);

        $this->view->invtManifestInvt = $invtManifestInvt[0];
        $this->view->invList = $invSbList;
        $this->view->PassportTypecd = Service_InvtSb::getpassportTypecd();
        $this->view->bindTypecd = Service_InvtSb::getbindTypecd();
        $this->view->rltTbTypecd = Service_InvtSb::getrltTbTypecd();
        $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->log = $log;
        echo Ec::renderTpl($this->tplDirectory . 'detail.tpl', 'layout');
    }
    /**
     * Note:表体的信息
     * User: Yao
     * Date: 2020/8/10
     * Time: 11:43
     */
    public function getDetailAction(){
        $return = [
            'Rows' => [],
            'total' => 0
        ];

        try{
            $id = $this->_request->getPost('is_id');
            if(empty($id)){
                throw new Exception('参数错误');
            }
            $showColumn = [
                'SeqNo'=>'SeqNo',
                'PassportNo'=>'PassportNo',
                'PassportSeqNo'=>'PassportSeqNo',
                'GdsMtno'=>'GdsMtno',
                'Gdecd'=>'Gdecd',
                'GdsNm'=>'GdsNm',
                'GrossWt'=>'GrossWt',
                'NetWt'=>'NetWt',
                'RltGdsSeqno'=>'RltGdsSeqno',
                'DclUnitcd'=>'DclUnitcd',
                'DclQty'=>'DclQty',
                'Rmk'=>'Rmk',
            ];
            $column = [];
            foreach ($showColumn as $key =>$as){
                $column[]=$key.' as '.$as;
            }
            $invSbList = Service_InvtSbDetail::getByCondition([
                'is_id'=>$id
            ],$column);
            if(empty($invSbList)){
                throw new Exception('表体数据为空');
            }
            $count = Service_InvtSbDetail::getByCondition([
                'is_id'=>$id
            ],'count(*)');
            /*$return['state']  = 1;
            $return['data'] = $invSbList;*/
            $return['Rows'] = $invSbList;
            $return['total'] = $count;


        }catch (Exception $e){
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }
    /**
     * Note:核放单核注关联关系
     */
    public function getInvtSbListAction(){
        $return =[
            'state'=>0,
            'message'=>'fail',
            'data'=>[]
        ];
        try{
            $id = $this->_request->getPost('is_id');
            if(empty($id)){
                throw new Exception('参数错误');
            }
            $invtSb = Service_InvtSb::getByField($id);
            if(empty($invtSb)){
                throw new Exception('核放单不存在');
            }
            $showColumn = [
                'RltInvtNo'=>'RltInvtNo',
            ];
            $column = [];
            foreach ($showColumn as $key =>$as){
                $column[]=$key.' as '.$as;
            }
            $invSbList = Service_InvtSbInvtlist::getByCondition([
                'is_id'=>$id
            ],$column);
            if(empty($invSbList)){
                throw new Exception('表体数据为空');
            }
            foreach($invSbList as $k=>$sbList){
                $invSbList[$k]['RltTbTypecd'] = $invtSb['RltTbTypecd'];
            }
            $return['state']  = 1;
            $return['data'] = $invSbList;
        }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('id');
            if(empty($id)){
                throw new Exception('参数错误');
            }
            $showField = [
                //'status'=>'status',
                'PassportNo'=> 'PassportNo',
                'PassportTypecd' => 'PassportTypecd',//
                'MasterCuscd' => 'MasterCuscd',//
                'DclTypecd' =>'DclTypecd',//
                // 'DclEtpsSccd'=>$headInfo['dcl_etps_sccd'],//
                'IoTypecd' =>'IoTypecd',//监管方式代码
                'BindTypecd' => 'BindTypecd',
                'RltTbTypecd' =>'RltTbTypecd',
                'RltNo' =>'RltNo',
                'AreainOriactNo' =>'AreainOriactNo',
                'AreainEtpsno' =>'AreainEtpsno',
                'AreainEtpsNm' =>'AreainEtpsNm',
                'AreainEtpsSccd' =>'AreainEtpsSccd',
                'VehicleNo'=>'VehicleNo',
                'VehicleIcNo'=>'VehicleIcNo',
                'ContainerNo' =>'ContainerNo',
                'VehicleWt'=>'VehicleWt',
                'VehicleFrameNo'=>'VehicleFrameNo',
                'VehicleFrameWt'=>'VehicleFrameWt',
                'ContainerType'=>'ContainerType',
                'ContainerWt'=>'ContainerWt',
                'TotalWt'=>'TotalWt',
                'TotalGrossWt'=>'TotalGrossWt',
                'TotalNetWt'=>'TotalNetWt',
                'TotalNetWt'=>'TotalNetWt',
                'DclErConc'=>'DclErConc',
                'DclTime'=>'DclTime',
                'DclEtpsno'=>'DclEtpsno',
                'DclEtpsNm'=>'DclEtpsNm',
                'DclEtpsSccd'=>'DclEtpsSccd',
                'InputCode'=>'InputCode',
                'InputSccd'=>'InputSccd',
                'InputName'=>'InputName',
                'EtpsPreentNo'=>'EtpsPreentNo',
                'Rmk'=>'Rmk',
                'Col1'=>'Col1',
                'Col2'=>'Col2',
                'sb_mode'=>'sb_mode',
            ];
            $column = [];
            foreach ($showField as $key=>$filed ){
                $column[]= $key.' as '.$filed;
            }
            $invList = Service_InvtSb::getByField($id,'is_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:
     * Date: 2020/8/21
     * Time: 17:15
     */
    public function makeXmlAction(){
        //echo "<pre>";
        $id = $this->_request->getParam('id');
        $invtSbList = Service_InvtSb::getByField($id);
        //print_r($invtSbList);
        if(empty($invtSbList)){
            $this->_redirect('/default/error/error');
        }
        $xml = new Xml();
        $invHead = new PassportHead();
        $invHead->setFromArray($invtSbList);

        //核放单和和核注单的关联关系
        $invSbListBody = Service_InvtSbInvtlist::getByCondition([
            'is_id'=>$invtSbList['is_id']
        ]);
        //($invSbListBody);

        $xml->setPassportHead($invHead);
        if(!empty($invSbListBody)){
            foreach ($invSbListBody as $body){
                $passportAcmpType = new PassportAcmp();
                $passportAcmpType->setFromArray([
                    'RtlBillTypecd'=>$invtSbList['RltTbTypecd'],
                    'RtlBillNo'=>$body['RltInvtNo'],
                ]);
                $xml->addPassportAcmp($passportAcmpType);
            }
        }
        //一票多车情况看核放单有商品表体
        $invSbDetail = Service_InvtSbDetail::getByCondition([
            'is_id'=>$invtSbList['is_id'],
            //'ios_status_neq'=>4
        ]);
        /*print_r($invSbDetail);
        exit;*/
        if(!empty($invSbDetail)){
            foreach ($invSbDetail as $sbdetail){
                $passportListType= new PassportList();
                $passportListType->setFromArray($sbdetail);
                $xml->addPassportList($passportListType);
            }
        }
        $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 {
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            $id = $this->_request->getParam('id');
            $deliveryCode = $this->_request->getParam('delivery_info');
            $giftRecodeList = $this->_request->getParam('gift_recode_list','');
            if (empty($id)) {
                throw new Exception('参数错误');
            }
            $invtSbList = Service_InvtSb::getByFieldLock($id);
            if (empty($invtSbList)) {
                throw new Exception('核放单类型错误');
            }
            if($invtSbList['is_status']!='-1'){
                throw new Exception("核放单状态不是待发送,不能发送");
            }
            if(empty($invtSbList['Rmk'])){
                if(empty($deliveryCode)) {
                    if ($invtSbList['sb_mode'] == 1) {
                        throw new Exception('请填写非保赠品的核放单号');
                    }
                    if ($invtSbList['sb_mode'] == 2) {
                        throw new Exception('请填写非保赠品商品项号关系');
                    }
                }else{
                    $updateSb = [];
                    if($invtSbList['sb_mode'] ==1){
                        $invtDelivery = Service_InvtDeliveryBase::getByField($deliveryCode,'del_no');
                        if(empty($invtDelivery)){
                            throw new Exception('非保正品核放单号不存在');
                        }
                        $updateSb['del_no'] = $deliveryCode;
                        $updateSb['Rmk'] ='非金二核放单'.$deliveryCode;
                    }else if($invtSbList['sb_mode'] ==2){
                        $updateSb['del_no'] = $deliveryCode;
                        if(empty($giftRecodeList)){
                            throw new Exception('请填写大促赠品项号关系');
                        }
                        $updateSb['Rmk'] =$giftRecodeList;
                    }
                    if(!empty($updateSb)){
                        Service_InvtSb::update($updateSb,$invtSbList['is_id']);
                        $log = [
                            'is_id' => $invtSbList['is_id'],
                            'is_node' => '发送海关，添加非金二核放单信息',
                            'ls_text' => '更新信息：'.json_encode($updateSb),
                            'add_time' => date("Y-m-d H:i:s",time()),
                            //'status_to' => '1',
                        ];
                        Service_InvtSbLog::add($log);
                    }
                }
            }

            $xml = new Xml();
            $invHead = new PassportHead();
            $invHead->setFromArray($invtSbList);

            //核放单和和核注单的关联关系
            $invSbListBody = Service_InvtSbInvtlist::getByCondition([
                'is_id'=>$invtSbList['is_id']
            ]);
            //print_r($invSbListBody);

            $xml->setPassportHead($invHead);

            if(!empty($invSbListBody)){
                foreach ($invSbListBody as $body){
                    $passportAcmpType = new PassportAcmp();
                    $passportAcmpType->setFromArray([
                        'RtlBillTypecd'=>$invtSbList['RltTbTypecd'],
                        'RtlBillNo'=>$body['RltInvtNo'],
                    ]);
                    $xml->addPassportAcmp($passportAcmpType);
                }
            }

            //一票多车情况看核放单有商品表体
            $invSbDetail = Service_InvtSbDetail::getByCondition([
                'is_id'=>$invtSbList['is_id'],
                //'ios_status_neq'=>4
            ]);
            /*print_r($invSbDetail);
            exit;*/
            if(!empty($invSbDetail)){
                foreach ($invSbDetail as $sbdetail){
                    $passportListType= new PassportList();
                    $passportListType->setFromArray($sbdetail);
                    $xml->addPassportList($passportListType);
                }
            }
            /*var_dump($xml);
            exit;*/
            $xmlString = $xml->toXml();

            $sendApi = new Send();
            $result = $sendApi->send($xmlString);
            if($result['state']=='1'){
                $upRow = array(
                    'is_status'=>'1'
                );
                Service_InvtSb::update($upRow,$invtSbList['is_id']);
            }
            $return['state'] = $result['state'];
            $return['message'] =$result['message'];
            $db->commit();
        }catch (Exception $e){
            $return['message'] = $e->getMessage();
            $db->rollBack();
        }
        die(Zend_Json::encode($return));
    }
    /**
     * @todo 取消核放单
     */
    public function concelAction(){
        $return = [
            'state'=>0,
            'message'=>'fail',
            'data'=>[]
        ];
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try{
            $is_id = $this->_request->getParam('id');
            if(empty($is_id)){
                throw new Exception('请选择要提交核放单号');
            }
            $invSbList = Service_InvtSb::getByField($is_id);
            if(empty($invSbList)){
                throw new Exception('参数错误');
            }
            $inv = new Process_InvtSb();
            $result = $inv->concel($invSbList);
            if($result !== true){
                throw new Exception('取消失败');
            }
            $return['state'] = 1;
            $message = "操作成功";

            $return['message'] = $message;
            $db->commit();
            //$db->rollBack();
        }catch (Exception $e){
            $return['message'] = $e->getMessage();
            $db->rollBack();
        }
        die(Zend_Json::encode($return));
    }
    public function exportCheckAction(){
        $id = $this->_request->getParam('id');
        if(empty($id)){
            $this->_redirect("/default/error/error");
        }
        $invtSb = Service_InvtSb::getByField($id);
        if(empty($invtSb)){
            $this->_redirect("/default/error/error");
        }
        $invtsDetail = Service_InvtSbInvtlist::getByCondition([
            'is_id'=>$invtSb['is_id']
        ]);
        $invtNo=[];
        foreach ($invtsDetail as $detail){
                $invtInfo = Service_InvtList::getByField($detail['RltInvtNo'],'BondInvtNo');
                if($invtInfo['ImpexpMarkcd'] =='E' && $invtInfo['InvtType'] =='8'){
                    $invtNo[]=$invtInfo['EtpsInnerInvtNo'];
                }
        }
        $excel = new \XLSXWriter();
        $excel->writeSheetHeader('sheet1',[
            '订单号'=>'string',
            '运单号'=>'string',
            '清单号'=>'string',
            '企业内部核注单号'=>'string',
            '备案序号'=>'string',
            '数量'=>'integer',
            '单位'=>'string',
            '单价'=>'string',
            '总价'=>'string',
            '海关编码'=>'string'
        ]);
        if(!empty($invtNo)){
            $exportList = Service_InvtOrderSb::getExportCheckInfo($invtNo);
            foreach ($exportList as $list){
                $excel->writeSheetRow('sheet1',[
                    $list['reference_no'],
                    $list['tracking_number'],
                    $list['form_id_port'],
                    $list['EtpsInnerInvtNo'],
                    $list['item_record_no'],
                    $list['qty'],
                    $list['unit'],
                    $list['price'],
                    sprintf("%.2f",$list['price']*$list['qty']),
                    $list['gcode'],
                ]);
            }
        }
        $fileName=$invtSb['VehicleNo'].date("Y-m-d").'查验信息.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Type: application/force-download');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $excel->writeToStdOut();
    }
    public function passAction(){
        $return = [
            'state'=>0,
            'message'=>'fail',
            'data'=>[]
        ];
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try{
            $etpsNo = $this->_request->getParam('etps_no');
            if(empty($etpsNo)){
                throw new Exception('参数错误');
            }
            $invSbList = Service_InvtSb::getByField($etpsNo,'EtpsPreentNo');
            if(empty($invSbList)){
                throw new Exception('参数错误');
            }
            $inv = new Process_InvtSb();
            $result = $inv->pass($invSbList);
            if($result !== true){
                throw new Exception('取消失败');
            }
            $return['state'] = 1;
            $message = "操作成功";
            $return['message'] = $message;
            $db->commit();
            //$db->rollBack();
        }catch (Exception $e){
            $return['message'] = $e->getMessage();
            $db->rollBack();
        }
        die(Zend_Json::encode($return));
    }
}