<?php

/**
 * Class Clearance_DesMessageController
 * User: Yao
 * Date: 2019/12/27
 * Note:核注清单
 */

use Customs\Dg\Hmzb\Ent\EntHead;
use Customs\Dg\Hmzb\Ent\EntBody;
use Customs\Dg\Hmzb\Ent\Xml;
use Customs\Dg\Hmzb\Ent\Send;

class Clearance_InvEntController extends Ec_Controller_Action
{
    protected $tplDirectory = '';

    public function preDispatch() {
        $this->tplDirectory = "clearance/views/inv-ent/";
    }

    /**
     * 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_InvtEntHead();
        $condition = $service->getMatchFields($params);
        if ($isSearchDate) {
            $condition['add_time_start'] = $conditionTemp['dateFor'];
            $condition['add_time_end'] = $conditionTemp['dateTo'];
        }
        if($params['order_code']){
            $condition['order_code'] = $params['order_code'];
        }
        if($params['reference_no']){
            $orderList = Service_Orders::getByCondition([
                'reference_no'=>$params['reference_no']
            ]);
            if(!empty($orderList)){
                foreach ($orderList as $order){
                    $condition['order_code_list'][]=$order['order_code'];
                }
            }else{
                $condition['ieh_id'] = -1;
            }
        }
        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(
                'ieh_id',
                'decl_type',
                'pre_ent_no',
                'target',
                'ent_no',
                'io_flag',
                'add_time',
                'update_time',
                'ent_status',
                'gross_weight',
                'net_weight',
                'ent_status',
                'inv_status',
                'inv_mode',
                'ems_no'
            );
            $service = new Service_InvtEntHead();
            $showFields = $service->getFieldsAlias($showFields);
            $count = Service_InvtEntHead::getByCondition($condition, 'count(*)');
            $return['total'] = $count;
            if ($count > 0) {
                $rows = Service_InvtEntHead::getByCondition($condition, $showFields, $pageSize, $page, 'ieh_id desc');
                $return['state'] = $count ? 1 : 0;
                $return['data'] = $rows;
            }
            $return['target'] = Service_InvtEntHead::getTarget();
            $return['zbStatus'] = Service_InvtEntHead::getZbStatus();
            $return['status'] = Service_InvtEntHead::getStatus();
            $return['ioFlag'] = Service_InvtEntHead::getIoFlag();
            $return['inv_mode'] = Service_InvtEntHead::getInvMode();
            $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 confirmAction() {
        $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_InvtEntHead::getByField($invId);
                    if (empty($invList)) {
                        throw new Exception('参数错误');
                    }
                    $inv = new Process_InvEnt();
                    $result = $inv->confirm($invList);
                    if ($result !== true) {
                        throw new Exception('确认失败:' . $result);
                    }
                    $db->commit();
                    $success++;
                } catch (Exception $e) {
                    $db->rollBack();
                    $return['data'][] = $invList['pre_ent_no'] . $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');
            $entNo = $this->_request->getParam('ent_no');
            $imCode = $this->_request->getParam('im_code');
            $relateEntNo = $this->_request->getParam('relate_ent_no');

            //核注信息
            $delNo = $this->_request->getParam('delNo','');
            $veNo = $this->_request->getParam('veNo','');


            if (empty($invtId)) {
                throw new Exception('请选择要提交的核注清单');
            }
            $invList = Service_InvtEntHead::getByField($invtId);
            if (empty($invList)) {
                throw new Exception('参数错误');
            }
            if (empty($invList['ent_no'])) {
                if (empty($entNo)) {
                    throw new Exception('请填写申请单编号');
                }
                if (empty($delNo)) {
                    throw new Exception('请填写核放单编号');
                }
                if (empty($entNo)) {
                    throw new Exception('请填写申请单编号');
                }
                Service_InvtEntHead::update([
                    'ent_no' => $entNo,
                    'del_no'=>$delNo,
                    've_no'=>$veNo
                ], $invList['ieh_id']);
                $log = [
                    'ieh_id' => $invList['ieh_id'],
                    'note' => '完成核注清单填写申请单编号'."核注单号{$entNo},核放单号:{$delNo},车牌号:{$veNo}",
                    'add_time' => date("Y-m-d H:i:s"),
                    'status_from' => $invList['ent_status'],
                    'status_to' => $invList['ent_status'],
                    'operater' => Service_User::getUserId()
                ];
                Service_InvtEntLog::add($log);
            }
            if($invList['inv_mode'] == 3 ){
                if(empty($relateEntNo)){
                    throw new Exception('请填写关联的大促非金二预录入申请单编号');
                }
                $relateEntNo = trim($relateEntNo);
                $entHead = Service_InvtEntHead::getByField($relateEntNo,'pre_ent_no');
                if(empty($entHead)){
                    throw new Exception('大促非金二预录入申请单编号信息不存在');
                }
                if($entHead['inv_mode']!=2){
                    throw new Exception($relateEntNo.'不是大促非金二核注清单');
                }
                Service_InvtEntHead::update([
                    'relate_ent_no' => $relateEntNo,
                ], $invList['ieh_id']);
            }
            $inv = new Process_InvEnt();
            if($invList['inv_mode']==2) {
                if (empty($imCode)) {
                    throw new Exception('请填写关联汇单信息');
                }
                $imCodeList = preg_split('/\n|,/', $imCode);
                $imCodeList = array_map(function ($v) {
                    return preg_replace('/\r/', '', $v);
                }, $imCodeList);
                $imCodeList = array_filter($imCodeList);
                $error = [];
                foreach ($imCodeList as $imCode){
                    $checkIm = Service_InvtManifiest::getByField($imCode,'im_code');
                    if(empty($checkIm)){
                        $error[]=$imCode.'汇单信息不存在';
                    }
                }
                if(!empty($error)){
                    throw new Exception(implode(',',$error));
                }
                $result = $inv->complete($invList, $imCodeList);
            }else{
                $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: 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'];
                $orderData = $params['order_data'];

                unset($params['detail'], $params['order_data']);
                $body = json_decode($data, true);
                $orderListInfo = json_decode($orderData, true);
                $inv = new Process_InvEnt();
                if (empty($body)) {
                    throw new Exception('请添加表体信息');
                }
                $headerError = $inv->validateHeadInfo($params);
                $bodyError = [];
                $error = $headerError;
                if (empty($headerError)) {
                    if ($params['io_flag'] == '1') {
                        $bodyError = $inv->validateInBodyInfo($body, $params['bwl_no']);
                        $error = array_merge($bodyError['error'], $headerError);
                    } else {
                        $bodyError = $inv->validateOutBodyInfo($body, $params['bwl_no']);
                        $error = array_merge($bodyError, $headerError);
                    }
                }
                $orderError = $inv->valiateOrderData($orderListInfo);
                $error = array_merge($error, $orderError);
                if (!empty($error)) {
                    throw new Exception(implode('<br/>', $error));
                }
                $code = $inv->doSave($params, $body, $orderListInfo);
                $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->target = Service_InvtEntHead::getTarget();
        $this->view->country = Service_Country::getByCondition([
            'trade_country_not_empty' => true,
        ]);
        $wrapType = Service_WrapType::getKeyVal();
        $this->view->entType = Service_InvtEntHead::getEntType();
        $this->view->supvmod = Service_InvtList::getsupvModecd();
        $this->view->warpType = $wrapType;
        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_InvEnt();
                if (empty($params['ieh_id'])) {
                    throw  new Exception('系统异常');
                }
                if (empty($body)) {
                    throw new Exception('请添加表体信息');
                }
                $headerError = $inv->validateHeadInfo($params);
                $bodyError = [];
                if (empty($headerError)) {
                    if ($params['io_flag'] == '1') {
                        $bodyError = $inv->validateInBodyInfo($body, $params['ems_no']);
                        $bodyError = $bodyError['error'];
                    } else {
                        $bodyError = $inv->validateOutBodyInfo($body, $params['ems_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-ent/';
            $uploadInfo = $upload->uploadXls($savePath, 'inv_file');
            if ($uploadInfo['state'] != 1) {
                throw new Exception($uploadInfo['message']);
            }
            $filePath = $uploadInfo['path'];
            $inv = new Process_InvEntUpload();
            $inv->setFilePath($filePath);
            $headInfo = $inv->getHeadInfo();
            $bodyInfo = $inv->getBodyInfo();
            $orderInfo = $inv->getOrderInfo();
            $invProcess = new Process_InvEnt();
            if (empty($bodyInfo)) {
                throw new Exception('请上传表体信息');
            }
            $headerError = $invProcess->validateHeadInfo($headInfo,1);
            $bodyError = [];
            if (empty($headerError)) {
                if ($headInfo['io_flag'] == '1') {
                    $bodyError = $invProcess->validateInBodyInfo($bodyInfo, $headInfo['bwl_no']);
                } else {
                    $bodyError = $invProcess->validateOutBodyInfo($bodyInfo, $headInfo['bwl_no']);
                }
            }
            if ($headInfo['io_flag'] == '1') {
                $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,
                        'order_data' => $orderInfo,
                    ];
                } else {
                    $return['state'] = 1;
                    $return['message'] = '上传成功';
                    $return['data'] = [
                        'head' => $headInfo,
                        'body' => $bodyInfo,
                        'order_data' => $orderInfo,
                    ];
                }
            } else {
                $error = array_merge($headerError, $bodyError);
                if (!empty($error)) {
                    $return['error'] = $error;
                } else {
                    $return['state'] = 1;
                    $return['message'] = '上传成功';
                    $return['data'] = [
                        'head' => $headInfo,
                        'body' => $bodyInfo,
                        'order_data' => $orderInfo,
                    ];
                }
            }
        } 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_InvtEntHead::getByField($id);
        if (empty($invList)) {
            $this->redirect("/default/error/error");
        }
        $log = Service_InvtEntLog::getByCondition([
            'ieh_id' => $invList['ieh_id']
        ], '*', '', '', "iel_id desc");
        $this->view->invList = $invList;
        $this->view->ioFlag = Service_InvtEntHead::getIoFlag();//进出标志
        $this->view->target = Service_InvtEntHead::getTarget();//货物流向
        $this->view->entType = Service_InvtEntHead::getEntType();//业务类型
        $this->view->zbStatus = Service_InvtEntHead::getZbStatus();
        $this->view->sysStatus = Service_InvtEntHead::getStatus();
        $this->view->invMode = Service_InvtEntHead::getInvMode();
        $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('参数错误');
            }
            $invList = Service_InvtEntBody::getByCondition([
                'ieh_id' => $id
            ], '*');
            if (empty($invList)) {
                throw new Exception('表体数据为空');
            }
            $entOrder = Service_InvtEntOrder::getByCondition([
                'ieh_id' => $id
            ]);
            $return['state'] = 1;
            $return['data']['list'] = $invList;
            $return['data']['order'] = $entOrder;
        } 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('ieh_id');
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $invList = Service_InvtEntHead::getByField($id, 'ieh_id');
            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: 2021/5/15
     * Time: 9:41
     */
    public function getEntAction() {

        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        try {
            $entId = $this->_request->getParam('ent_id');
            if (empty($entId)) {
                throw new Exception('参数错误');
            }
            $entIdList = explode(',', $entId);
            foreach ($entIdList as $id) {
                $entHead = Service_InvtEntHead::getByField($id);
                if (empty($entHead)) {
                    throw new Exception('非金二申请单信息不存在');
                }
                $return['data'][] = $entHead;
            }
            $return['state'] = 1;
        } 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');
        $invtHead = Service_InvtEntHead::getByField($id);
        if (empty($invtHead)) {
            $this->_redirect('/default/error/error');
        }
        $xml = new Xml();
        $entHead = new EntHead();
        $uperHead = array_change_key_case($invtHead, CASE_UPPER);
        $entHead->setFromArray($uperHead);
        $entBodyList = Service_InvtEntBody::getByCondition([
            'ieh_id' => $invtHead['ieh_id']
        ]);
        $xml->setHead($entHead);
        foreach ($entBodyList as $body) {
            $entBody = new EntBody();
            $entBody->setFromArray(array_change_key_case($body, CASE_UPPER));
            $xml->addPassportList($entBody);
        }
        $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('id');
            $invtHead = Service_InvtEntHead::getByField($id);
            if (empty($invtHead)) {
                $this->_redirect('/default/error/error');
            }
            $xml = new Xml();
            $entHead = new EntHead();
            $uperHead = array_change_key_case($invtHead, CASE_UPPER);
            $entHead->setFromArray($uperHead);
            $entHead->PRE_ENT_NO = '';
            $entBodyList = Service_InvtEntBody::getByCondition([
                'ieh_id' => $invtHead['ieh_id']
            ]);
            $xml->setHead($entHead);
            foreach ($entBodyList as $body) {
                $entBody = new EntBody();
                $entBody->setFromArray(array_change_key_case($body, CASE_UPPER));
                $xml->addPassportList($entBody);
            }
            $xmlString = $xml->toXml();
            $sendApi = new 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/5/18
     * Time: 15:23
     */
    public function exportAction() {
        set_time_limit(3600);
        require_once "PHPExcel.php";
        require_once "PHPExcel/IOFactory.php";
        $path = APPLICATION_PATH . '/../data/xls/inv_ent_import.xls';
        $excel = PHPExcel_IOFactory::load($path);
        $headSheet = $excel->getSheet(0);
        $bodySheet = $excel->getSheet(1);
        //$orderSheet = $excel->getSheet(4);
        $id = $this->_request->getParam('id');
        $invent = Service_InvtEntHead::getByField($id);
        if ($invent) {
            $invtBody = Service_InvtEntBody::getByCondition([
                'ieh_id' => $invent['ieh_id']
            ]);
            $headSheet->setCellValue('A2', $invent['ent_no']);//申请单编号
            $headSheet->setCellValue('B2', $invent['target']);//货物流向
            $headSheet->setCellValue('C2', $invent['ent_type']);//业务类型
            $headSheet->setCellValue('D2', $invent['io_flag']);//进出标记
            $headSheet->setCellValue('E2', $invent['port_code']);//进境口岸
            $headSheet->setCellValue('F2', $invent['location_code']);//监管场所代码
            $headSheet->setCellValue('G2', $invent['h2000_ems_no']);//H2000电子账册编号
            $headSheet->setCellValue('H2', $invent['ems_no']);//H2000电子账册编号
            $headSheet->setCellValue('I2', $invent['relate_entry_id']);//关联报关单编号
            $headSheet->setCellValue('J2', $invent['location_type']);//区域/场所类型
            $headSheet->setCellValue('K2', $invent['relate_other_type']);//关联其他单证类型
            $headSheet->setCellValue('L2', $invent['relate_other_no']);//关联其他单证编号
            $headSheet->setCellValue('M2', $invent['trade_code']);//区内经营单位编码
            $headSheet->setCellValue('N2', $invent['trade_name']);//区内经营单位名称
            $headSheet->setCellValue('O2', $invent['trade_code_out']);//区外经营单位编码
            $headSheet->setCellValue('P2', $invent['trade_name_out']);//区外经营单位名称
            $headSheet->setCellValue('Q2', $invent['app_er']);//申请人姓名
            $headSheet->setCellValue('R2', $invent['trade_mode']);//监管方式
            $headSheet->setCellValue('S2', $invent['consignee_code']);//收发货单位代码
            $headSheet->setCellValue('T2', $invent['consignee_name']);//收发货单位名称
            $headSheet->setCellValue('U2', $invent['ie_date']);//进出口日期
            $headSheet->setCellValue('V2', $invent['wrap_type']);//包装种类
            $headSheet->setCellValue('W2', $invent['trade_country']);//起运/运抵国
            $headSheet->setCellValue('X2', $invent['trans_mode']);//成交方式
            $headSheet->setCellValue('Y2', $invent['gross_weight']);//毛重(KG)
            $headSheet->setCellValue('Z2', $invent['net_weight']);//净重(KG)
            $headSheet->setCellValue('AA2', $invent['decl_time']);//申报时间
            $headSheet->setCellValue('AB2', $invent['remark']);//备注
            $index = 2;
            foreach ($invtBody as $body) {
                $bodySheet->setCellValue('A' . $index, $body['g_no']);//商品序号
                $bodySheet->setCellValue('B' . $index, $body['ems_g_no']);//账册项号
                $bodySheet->setCellValueExplicit('C' . $index, $body['code_ts'],PHPExcel_Cell_DataType::TYPE_STRING);//商品编码
                $bodySheet->setCellValue('D' . $index, $body['g_name']);//商品名称
                $bodySheet->setCellValue('E' . $index, $body['g_model']);//规格型号
                $bodySheet->setCellValue('F' . $index, $body['origin_country']);//产销国
                $bodySheet->setCellValue('G' . $index, $body['curr']);//成交币制
                $bodySheet->setCellValue('H' . $index, $body['price']);//申报单价
                $bodySheet->setCellValue('I' . $index, $body['total_price']);//申报总价
                $bodySheet->setCellValue('J' . $index, $body['qty']);//申报数量
                $bodySheet->setCellValue('K' . $index, $body['use_to']);//用途
                $bodySheet->setCellValue('L' . $index, $body['cut_mode']);//征免免税方式
                $bodySheet->setCellValueExplicit('M' . $index, $body['unit'],PHPExcel_Cell_DataType::TYPE_STRING);//申报单位
                $bodySheet->setCellValue('N' . $index, $body['qty_1']);//法定数量
                $bodySheet->setCellValueExplicit('O' . $index, $body['unit_1'],PHPExcel_Cell_DataType::TYPE_STRING);//商品序号
                $bodySheet->setCellValue('P' . $index, $body['in_ent_no']);//关联进区申请单编号
                $bodySheet->setCellValue('Q' . $index, $body['in_ent_g_no']);//关联进区商品序号
                $bodySheet->setCellValue('R' . $index, $body['entry_g_no']);//报关单商品序号
                $bodySheet->setCellValue('S' . $index, $body['h2000_ems_g_no']);//H2000商品序号
                $bodySheet->setCellValue('T' . $index, $body['h2000_ems_g_type']);//H2000表体类型
                $bodySheet->setCellValue('U' . $index, $body['rmk']);//备注
                $index++;
            }
            $entOrderList = Service_InvtEntOrder::getByCondition([
                'ieh_id'=>$invent['ieh_id']
            ]);
            /*$orderSheet->setCellValue("A1",'订单号');
            $orderSheetIndex = 2;
            foreach ($entOrderList as $entOrder){
                $orderSheet->setCellValue('A' . $orderSheetIndex, $entOrder['order_code']);//
                $orderSheetIndex++;
            }*/
        }
        $filename = date("Y-m-d") . mt_rand(100, 999) . '非金二核注清单信息.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');
    }

    public function deleteAction(){
        $return=[
            'state'=>1,
            'messsage'=>''
        ];
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try{
            $entId = $this->_request->getParam('ent_id');
            if(empty($entId)){
                throw new Exception('清单信息不存在');
            }
            $invEnt = Service_InvtEntHead::getByField($entId);
            if(empty($invEnt)){
                throw new Exception('清单信息不存在');
            }
            if($invEnt['ent_status']!=1 && $invEnt['ent_status']!=-1){
                throw new Exception('核注清单不是草稿确认状态');
            }
            $invProcess = new Process_InvEnt();
            $result = $invProcess->concel($invEnt);
            if($result!==true){
                throw new Exception('取消失败');
            }
            $return['state'] = 1;
            $return['message'] ='取消成功';
            $db->commit();
        }catch (Exception $e){
            $db->rollBack();
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }
    /**
     * Note:导出差异大促与实际出货差异信息
     * User: Yao
     * Date: 2021/6/15
     * Time: 15:04
     */
    public function exportDifferAction(){
        require_once "PHPExcel.php";
        require_once "PHPExcel/IOFactory.php";
        $entId = $this->_request->getParam('id');
        if(empty($entId)){
            $this->_redirect("/default/error/error");
        }
        $entHeadInfo = Service_InvtEntHead::getByField($entId);
        if(empty($entHeadInfo)){
            $this->_redirect("/default/error/error");
        }
        $entBodyInfo = Service_InvtEntBody::getByCondition([
            'ieh_id'=>$entId
        ]);
        $outInfo = Service_InvtEntOrder::getGiftInfo($entId);
        $outInfoProductMap =[];
        foreach ($outInfo as $outProduct){
            $outInfoProductMap[$outProduct['product_id']] = $outProduct;
        }
        $excel = new PHPExcel();
        $bodySheet = $excel->getSheet(0);
        $index =1;
        $bodySheet->setCellValue('A' . $index, '商品序号');//商品序号
        $bodySheet->setCellValue('B' . $index, '账册项号');//账册项号
        $bodySheet->setCellValue('C' . $index, '商品编码');//商品编码
        $bodySheet->setCellValue('D' . $index, '商品名称');//商品名称
        $bodySheet->setCellValue('E' . $index, '规格型号');//规格型号
        $bodySheet->setCellValue('F' . $index, '产销国');//产销国
        $bodySheet->setCellValue('G' . $index, '成交币制');//成交币制
        $bodySheet->setCellValue('H' . $index, '申报单价');//申报单价
        $bodySheet->setCellValue('I' . $index, '申报总价');//申报总价
        $bodySheet->setCellValue('J' . $index,'申报数量');//申报数量
        $bodySheet->setCellValue('K' . $index, '用途');//用途
        $bodySheet->setCellValue('L' . $index, '征免免税方式');//征免免税方式
        $bodySheet->setCellValue('M' . $index, '申报单位');//申报单位
        $bodySheet->setCellValue('N' . $index, '法定数量');//法定数量
        $bodySheet->setCellValue('O' . $index, '法定单位');//商品序号
        $bodySheet->setCellValue('P' . $index, '关联进区申请单编号');//关联进区申请单编号
        $bodySheet->setCellValue('Q' . $index, '关联进区商品序号');//关联进区商品序号
        $bodySheet->setCellValue('R' . $index, '报关单商品序号');//报关单商品序号
        $bodySheet->setCellValue('S' . $index, 'H2000商品序号');//H2000商品序号
        $bodySheet->setCellValue('T' . $index, 'H2000表体类型');//H2000表体类型
        $bodySheet->setCellValue('U' . $index, '备注');//备注
        $bodySheet->setCellValue('V' . $index, '实际出货数量');//备注
        $bodySheet->setCellValue('W' . $index, '产品条码');//备注
        $index++;
        foreach ($entBodyInfo as $body){
            $billBook = Service_BillBook::getByCondition([
                'recorde_no'=>$body['ems_g_no'],
                'warehous_account_no'=>$entHeadInfo['ems_no'],
            ]);
            $billBookProduct = Service_BillBookProduct::getByField($billBook[0]['id'],'bill_book_id');
            $productId = $billBookProduct['product_id'];
            $outProductInfo =$outInfoProductMap[$productId];
            if($outProductInfo){
                unset($outInfoProductMap[$productId]);
            }
            $bodySheet->setCellValue('A' . $index, $body['g_no']);//商品序号
            $bodySheet->setCellValue('B' . $index, $body['ems_g_no']);//账册项号
            $bodySheet->setCellValue('C' . $index, $body['code_ts']);//商品编码
            $bodySheet->setCellValue('D' . $index, $body['g_name']);//商品名称
            $bodySheet->setCellValue('E' . $index, $body['g_model']);//规格型号
            $bodySheet->setCellValue('F' . $index, $body['origin_country']);//产销国
            $bodySheet->setCellValue('G' . $index, $body['curr']);//成交币制
            $bodySheet->setCellValue('H' . $index, $body['price']);//申报单价
            $bodySheet->setCellValue('I' . $index, $body['total_price']);//申报总价
            $bodySheet->setCellValue('J' . $index, $body['qty']);//申报数量
            $bodySheet->setCellValue('K' . $index, $body['use_to']);//用途
            $bodySheet->setCellValue('L' . $index, $body['cut_mode']);//征免免税方式
            $bodySheet->setCellValue('M' . $index, $body['unit']);//申报单位
            $bodySheet->setCellValue('N' . $index, $body['qty_1']);//法定数量
            $bodySheet->setCellValue('O' . $index, $body['unit_1']);//商品序号
            $bodySheet->setCellValue('P' . $index, $body['in_ent_no']);//关联进区申请单编号
            $bodySheet->setCellValue('Q' . $index, $body['in_ent_g_no']);//关联进区商品序号
            $bodySheet->setCellValue('R' . $index, $body['entry_g_no']);//报关单商品序号
            $bodySheet->setCellValue('S' . $index, $body['h2000_ems_g_no']);//H2000商品序号
            $bodySheet->setCellValue('T' . $index, $body['h2000_ems_g_type']);//H2000表体类型
            $bodySheet->setCellValue('U' . $index, $body['rmk']);//备注
            $bodySheet->setCellValue('V' . $index, $outProductInfo['total_quanitty']?:0);//实际出货数量
            $bodySheet->setCellValue('W' . $index, $outProductInfo['product_barcode']);//商品条码
            $index++;
        }
        if(!empty($outInfoProductMap)){
            foreach ($outInfoProductMap as $outBody){
                $productInfo = Service_Product::getByField($outBody['product_id']);
                $billBookProduct = Service_BillBookProduct::getBillRecord($outBody['product_id']);
                $billBook =[];
                if(!empty($billBookProduct)){
                    foreach ($billBookProduct as $bp){
                        $billBook = Service_BillBook::getByCondition([
                            'id'=>$bp['bill_book_id'],
                            'warehous_account_no'=>$entHeadInfo['ems_no'],
                        ]);
                        if(!empty($billBook)){
                            break;
                        }
                    }
                }
                $outQuantity = $outBody['total_quanitty']?:0;
                $bodySheet->setCellValue('A' . $index, '');//商品序号
                $bodySheet->setCellValue('B' . $index, $billBook['ems_g_no']);//商品序号
                $bodySheet->setCellValue('C' . $index, $billBook['hs_code']?:$productInfo['hs_code']);//商品编码
                $bodySheet->setCellValue('D' . $index, $billBook['product_title']?:$productInfo['product_title']);//商品名称
                $bodySheet->setCellValue('E' . $index, $billBook['specification']?:$productInfo['special']);//规格型号
                $bodySheet->setCellValue('F' . $index, $billBook['country_code']);//产销国
                $bodySheet->setCellValue('G' . $index, $billBook['decalar_currency']);//成交币制
                $bodySheet->setCellValue('H' . $index, $billBook['price']);//申报单价
                $bodySheet->setCellValue('I' . $index, $billBook['price']*$outQuantity);//申报总价
                $bodySheet->setCellValue('J' . $index, 0);//申报数量
                $bodySheet->setCellValue('K' . $index, $productInfo['use_way']);//用途
                $bodySheet->setCellValue('L' . $index, '');//征免免税方式
                $bodySheet->setCellValue('M' . $index, $billBook['decalare_unit']);//申报单位
                $bodySheet->setCellValue('N' . $index, $billBook['legal_unit']);//法定数量
                $bodySheet->setCellValue('O' . $index, '');//商品序号
                $bodySheet->setCellValue('U' . $index, '商品sku:'.$productInfo['product_sku'].'客户代码：'.$productInfo['customer_code']);//备注
                $bodySheet->setCellValue('V' . $index, $outQuantity);//实际出货数量
                $bodySheet->setCellValue('W' . $index, $productInfo['product_barcode']);//实际出货数量
                $index++;
            }
        }
        $filename = date("Y-m-d") . mt_rand(100, 999) . '大促差异数量.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/9/19
     * Time: 16:41
     */
    public function makeDamaoInvAction(){
        $return =[
            'state'=>0,
            'message'=>''
        ];
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try{
            $cmCode = $this->_request->getParam('cm_code');
            $etpsInfo = $this->_request->getParam('etps_info');
            $grossWeight = $this->_request->getParam('gross_weight');
            $netWeight = $this->_request->getParam('net_weight');
            if(empty($cmCode)){
                throw new Exception('载货单号不存在');
            }
            if(empty($etpsInfo)){
                throw new Exception('请选择企业信息');
            }
            if(empty($grossWeight) || !preg_match("/^(([1-9][0-9]*)+(\.[0-9]{1,2})?)$/",$grossWeight)){
                throw new Exception('请填写毛重，且不超过两位小数');
            }
            if(empty($netWeight)|| !preg_match("/^(([1-9][0-9]*)+(\.[0-9]{1,2})?)$/",$netWeight)){
                throw new Exception('请填写净重,且不超过两位小数000');
            }
            $etpsConfig = new Api_Inv_Config();
            $etpsHead = $etpsConfig->getInvHeadConfig($etpsInfo);
            if(empty($etpsHead)){
                throw new Exception('企业信息错误');
            }
            $process = new Process_InvDamaoOrder();
            $process->setHeadInfo($etpsHead);
            $invtEntNo = $process->createInvEntBySbCode($cmCode,$grossWeight,$netWeight);
            $db->commit();
            //$db->rollBack();
            $return['state'] = 1;
            $return['message'] ='核注清单号：'.$invtEntNo;
        }catch (Exception $e){
            $db->rollBack();
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));

    }

}