<?php

use App\models\Logistic\Pri\PriEnter;
use App\models\Logistic\Upload\BaoGuanDan;
class Cis_PreEntryController extends Ec_Controller_Action
{
    public function preDispatch()
    {
        $this->tplDirectory = "cis/views/pre-entry/";
    }

    /**
     * @todo
     */
    public function listAction()
    {
        $params = $this->_request->getParams();
        $cisEntry = new Service_BgPriEntryData();
        $page = $this->_request->getParam('page', 1);
        $pageSize = $this->_request->getParam('pageSize', 20);

        $page = $page ? $page : 1;
        $pageSize = $pageSize ? $pageSize : 20;
        if ($this->_request->isPost()) {
            $matchSearchCondition = $cisEntry->getMatchFields($params);
            if (!empty($params['dateFor'])) {
                $matchSearchCondition['add_time_start'] = date("Y-m-d H:i:s", strtotime($params['dateFor']));
            }
            if (!empty($params['dateTo'])) {
                $matchSearchCondition['add_time_end'] = date("Y-m-d H:i:s", strtotime($params['dateTo']));
            }
            $count = Service_BgPriEntryData::getByCondition($matchSearchCondition, 'count(*)');
            $return = [
                "state" => 0,
                "message" => "No Data"
            ];
            if ($count) {
                $iePort = Service_IePort::getKeyVal();
                $preType = Service_FormType::getKeyVal();
                $return['total'] = $count;
                $showFields = array(
                    'bped_id',
                    'ref_no',
                    'declare_port',
                    'ie_port',
                    'pre_status',
                    'pt_code',
                    'ie_flag',
                    'pack_number',
                    'net_weight',
                    'gross_weight',
                    'mf_status',
                    'hf_status',
                    'add_time',
                    'company_code',
                );
                $showFields = $cisEntry->getFieldsAlias($showFields);
                $rows = $cisEntry->getByCondition($matchSearchCondition, $showFields, $pageSize, $page, array('bped_id desc'));
                $bgCompanys = Service_BgCompany::getAll();
                $bgKeyCompanys = [];
                foreach ($bgCompanys as $k=>$bp){
                    $bgKeyCompanys[$bp['company_code']] = $bp;
                }
                $return['data'] = $rows;
                $return['ie_port'] = $iePort;
                $return['pre_type'] = $preType;
                $return['state'] = 1;
                $return['companys'] = $bgKeyCompanys;
                $return['message'] = "";
            }
            die(Zend_Json::encode($return));
        }
        $this->view->iePort = Service_IePort::getKeyVal();
        $this->view->formType = Service_FormType::getKeyVal();
        $this->view->preStatus = Common_Status::getStatusMap('bg_pri_entry_data', 'pre_status');
        $this->view->passportTypecd = Service_InvtSb::getpassportTypecd();
        $this->view->bindTypecd = Service_InvtSb::getbindTypecd();
        $this->view->bgCompany = Service_BgCompany::getAll();
        echo Ec::renderTpl($this->tplDirectory . 'list.tpl', 'layout');
    }

    public function getDetailAction()
    {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => [],
        ];
        if ($this->_request->isPost()) {
            try {
                $id = $this->_request->getParam('id');
                if (empty($id)) {
                    throw new \Exception("参数错误");
                }
                $detail = Service_BgPriEntryDataDetailBodyHead::getByCondition([
                    'bped_id' => $id
                ], [
                    'bpedbh_id',
                    'bped_id',
                    'bpd_ref_no',
                    'pack_no',
                    'net_wt',
                    'gross_wt',
                    'hz_status',
                    'bg_status',
                    'add_time',
                    'inv_no',
                    'baoguan_code'
                ]);
                $return['data'] = $detail;
                $return['state'] = 1;
            } catch (\Exception $e) {
                $return['messag'] = $e->getMessage();
            }
        }
        die(Zend_Json::encode($return));
    }

    /**
     * note:报关单核注清单表头
     * Auther:Yao
     * Date:2022/6/27 16:27
     */
    public function detailHeadAction()
    {
        $id = $this->_request->getParam('head_id');
        if ($this->_request->isPost()) {
            $return = [
                'state' => 0,
                'message' => 'fail',
                'data' => [],
            ];
            $params = $this->_request->getParams();
            $id = $this->_request->getParam('id');
            $update = [
                'bpedbh_id',
                'bpd_ref_no',
                'pt_code',
                'ie_flag',
                'declare_port',
                'ie_port',
                'enty_port_code',
                'ems_no',
                'ems_cop_no',
                'cop_gb_code',
                'platenumber',
                'traf_name',
                'traf_mode',
                'voyage_no',
                'bill_no',
                'wrap_type',
                'net_wt',
                'gross_wt',
                'pack_no',
                'duty_mode',
                'trade_mode',
                'trans_mode',
                'trade_country',
                'trade_area_code',
                'destination_port',
                'num',
                'turn_no',
                'trade_co',
                'trade_name',
                'agent_code',
                'agent_name',
                'owner_code',
                'owner_name',
                'rlt_entry_rvsngd_etps_sccd',
                'rlt_entry_rcvgd_etpsno',
                'rlt_entry_rcvgd_etps_nm',
                'rlt_entry_bizop_etps_sccd',
                'rlt_entry_bizop_etpsno',
                'rlt_entry_bizop_etps_nm',
            ];
            $save = [];
            foreach ($update as $up) {
                if (isset($params[$up]) || $params[$up] !== null) {
                    $save[$up] = $params[$up];
                }
            }
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                if (empty($id)) {
                    throw new \Exception("参数错误");
                }
                Service_BgPriEntryDataDetailBodyHead::update($save, $id, 'bpedbh_id');
                $db->commit();
                $return['state'] = 1;
                $return['message'] = 'success';
            } catch (\Exception $e) {
                $db->rollBack();
                $return['message'] = $e->getMessage();
            }
            die(Zend_Json::encode($return));

        }
        $this->view->iePort = Service_IePort::getKeyVal();
        $this->view->formType = Service_FormType::getKeyVal();
        $this->view->ieType = Common_SelectMap::getIEtype();
        $this->view->wrapType = Common_SelectMap::customWrapType();
        $this->view->portCodeInternal = Service_PortCodeInternal::getKeyVal();
        $this->view->trafMode = Common_SelectMap::trafMode();
        $this->view->tradeMode = Service_TradeMode::getKeyVal();
        $this->view->dutyMode = Common_SelectMap::dutyMode();
        $this->view->trans_mode = Service_TransMode::getKeyVal();
        $this->view->country = Service_Country::tradeMap();
        $this->view->destinationPort = Common_SelectMap::getdestination_port();
        $this->view->headInfo = $headInfo = Service_BgPriEntryDataDetailBodyHead::getByField($id, 'bpedbh_id');
        $this->view->id = $id;
        echo Ec::renderTpl($this->tplDirectory . 'detail-head.tpl', 'layout');
    }

    /**
     * note:预录入数据核注单详细
     * Auther:Yao
     * Date:2022/6/27 16:27
     */
    public function detailBodyAction()
    {
        $headId = $this->_request->getParam('head_id');
        $this->view->headId = $headId;

        echo Ec::renderTpl($this->tplDirectory . 'detail-body.tpl', 'layout');
    }

    public function ajaxGetDetailBodyAction()
    {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        try {
            if (!$this->_request->isXmlHttpRequest()) {
                throw new \Exception("非法请求");
            }
            $id = $this->_request->getParam('id');
            if (empty($id)) {
                throw new \Exception("参数错误");
            }
            $detail = Service_BgPriEntryDataDetailBodyDetail::getByCondition([
                'bpedbh_id' => $id
            ], '*');
            if ($detail) {
                $return['data'] = $detail;
                $return['state'] = 1;
                $return['message'] = 'sucess';
            } else {
                $return['message'] = 'No Data';
            }
        } catch (\Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));

    }

    /**
     * @todo 随附单证信息
     */
    public function ajaxGetDetailBodyLicensedocuAction()
    {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        try {
            if (!$this->_request->isXmlHttpRequest()) {
                throw new \Exception("非法请求");
            }
            $id = $this->_request->getParam('id');
            if (empty($id)) {
                throw new \Exception("参数错误");
            }
            $detail = Service_BgPriEntryDataDetailBodyLicensedocu::getByCondition([
                'bpedbh_id' => $id
            ], '*');
            if ($detail) {
                $return['data'] = $detail;
                $return['state'] = 1;
                $return['message'] = 'sucess';
            } else {
                $return['message'] = 'No Data';
            }
        } catch (\Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * @todo 修改表体信息
     */
    public function editDetaiBodyAction()
    {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        try {
            if (!$this->_request->isXmlHttpRequest()) {
                throw new \Exception("非法请求");
            }
            $id = $this->_request->getParam('bpedbdd_id');
            if (empty($id)) {
                throw new \Exception("参数错误");
            }
            $detail = Service_BgPriEntryDataDetailBodyDetail::getByField($id);
            if (empty($detail)) {
                throw new \Exception('详细信息不存在');
            }
            $data = $this->_request->getParams();

            Common_Common::trim_blank($data);
            unset($data['module'],$data['controller'],$data['action']);
            Service_BgPriEntryDataDetailBodyDetail::update($data, $id);
            $return['state'] = 1;
            $return['message'] ='编辑成功';
        } catch (\Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * @todo 删除表体信息
     */
    public function deleteDetailBodyAction()
    {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        try {
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            if (!$this->_request->isXmlHttpRequest()) {
                throw new \Exception("非法请求");
            }
            $id = $this->_request->getParam('id');
            if (empty($id)) {
                throw new \Exception("参数错误");
            }
            if (!is_array($id)) {
                $id = explode(',', $id);
            }
            foreach ($id as $i) {
                $affectRow = Service_BgPriEntryDataDetailBodyDetail::delete($i);
                if (!$affectRow) {
                    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:随附单证
     * Auther:Yao
     * Date:2022/6/27 16:31
     */
    public function detailLicensedocuAction()
    {
        $id = $this->_request->getParam('head_id');
        if ($this->_request->isPost()) {
            $id = $this->_request->getParam('bpedbl_id');
            $headId = $this->_request->getParam('bpedbh_id');
            $return = [
                'state' => 0,
                'message' => 'fail'
            ];
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                $params = $this->_request->getParams();
                Common_Common::trim_blank($params);
                if (!$headId) {
                    throw new \Exception('参数错误');
                }
                if (!$id) {
                    $save = [
                        'bpedbh_id' => $headId,
                        'docu_code' => $params['docu_code'],
                        'cert_code' => $params['cert_code']
                    ];
                    Service_BgPriEntryDataDetailBodyLicensedocu::add($save);
                    $message = '添加成功';
                } else {
                    $oldRow = Service_BgPriEntryDataDetailBodyLicensedocu::getByField($id);
                    if (empty($oldRow)) {
                        throw new \Exception('随附单证信息不存在');
                    }
                    $save = [
                        'bpedbh_id' => $headId,
                        'docu_code' => $params['docu_code'],
                        'cert_code' => $params['cert_code']
                    ];
                    Service_BgPriEntryDataDetailBodyLicensedocu::update($save, $id);
                    $message = '修改成功';
                }
                $db->commit();
                $return['state'] = 1;
                $return['message'] = $message;
            } catch (\Exception $e) {
                $return['message'] = $e->getMessage();
            }
            die(Zend_Json::encode($return));
        }
        $this->view->headId = $id;
        echo Ec::renderTpl($this->tplDirectory . 'detail-licensedocu.tpl', 'layout');
    }

    /**
     * @todo 删除随附单证
     */
    public function detailContainersAction()
    {
        $id = $this->_request->getParam('head_id');
        if ($this->_request->isPost()) {
            $id = $this->_request->getParam('bpedd_id');
            $headId = $this->_request->getParam('bpedbh_id');
            $return = [
                'state' => 0,
                'message' => 'fail'
            ];
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try {
                $params = $this->_request->getParams();
                Common_Common::trim_blank($params);
                if (!$headId) {
                    throw new \Exception('参数错误');
                }
                if (!$id) {
                    $save = [
                        'container_id' => $params['container_id'],
                        'container_md' => $params['container_md'],
                        'goods_no' => $params['goods_no'],
                        'lcl_flag' => $params['lcl_flag'],
                        'goods_conta_wt' => $params['goods_conta_wt'],
                        'container_wt' => $params['container_wt'],
                        'bpedbh_id' => $headId,
                    ];
                    Service_BgPriEntryDataDetailBodyContainers::add($save);
                    $message = '添加成功';
                } else {
                    $oldRow = Service_BgPriEntryDataDetailBodyContainers::getByField($id);
                    if (empty($oldRow)) {
                        throw new \Exception('随附单证信息不存在');
                    }
                    $save = [
                        'container_id' => $params['container_id'],
                        'container_md' => $params['container_md'],
                        'goods_no' => $params['goods_no'],
                        'lcl_flag' => $params['lcl_flag'],
                        'goods_conta_wt' => $params['goods_conta_wt'],
                        'container_wt' => $params['container_wt'],
                        'bpedbh_id' => $headId,
                    ];
                    Service_BgPriEntryDataDetailBodyContainers::update($save, $id);
                    $message = '修改成功';
                }
                $db->commit();
                $return['state'] = 1;
                $return['message'] = $message;
            } catch (\Exception $e) {
                $return['message'] = $e->getMessage();
            }
            die(Zend_Json::encode($return));
        }
        $this->view->headId = $id;
        echo Ec::renderTpl($this->tplDirectory . 'detail-containers.tpl', 'layout');
    }

    /**
     * @todo 获取集装箱详细信息
     */
    public function ajaxGetDetailBodyContainersAction()
    {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        try {
            if (!$this->_request->isXmlHttpRequest()) {
                throw new \Exception("非法请求");
            }
            $id = $this->_request->getParam('id');
            if (empty($id)) {
                throw new \Exception("参数错误");
            }
            $detail = Service_BgPriEntryDataDetailBodyContainers::getByCondition([
                'bpedbh_id' => $id
            ], '*');
            if ($detail) {
                $return['data'] = $detail;
                $return['state'] = 1;
                $return['message'] = 'sucess';
            } else {
                $return['message'] = 'No Data';
            }
        } catch (\Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    public function detailPageAction()
    {
        $id = $this->_request->getParam('id');
        $detailHead = Service_BgPriEntryDataDetailBodyHead::getByField($id, 'bpedbh_id');
        $this->view->id = $id;
        $this->view->headId = $detailHead['bpedbh_id'];
        echo Ec::renderTpl($this->tplDirectory . 'pre-entry-data-detail.tpl', 'layout');
    }

    /**
     * @todo 删除集装箱信息
     */
    public function deleteContainersAction()
    {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'data' => []
        ];
        try {
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            if (!$this->_request->isXmlHttpRequest()) {
                throw new \Exception("非法请求");
            }
            $id = $this->_request->getParam('id');
            if (empty($id)) {
                throw new \Exception("参数错误");
            }
            if (!is_array($id)) {
                $id = explode(',', $id);
            }
            foreach ($id as $i) {
                $affectRow = Service_BgPriEntryDataDetailBodyContainers::delete($i);
                if (!$affectRow) {
                    throw new \Exception("系统错误，数据不存在或者已删除");
                }
            }
            $return['state'] = 1;
            $return['message'] = '删除成功';
            $db->commit();
        } catch (\Exception $e) {
            $db->rollBack();
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));

    }

    /**
     * @date 2022/7/5
     * @todo 生成核注清单
     * @auther 46935
     */
    public function makeInvAction()
    {
        $return = [
            'state' => 0,
            'message' => 'fail'
        ];
        try {
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            $headId = $this->_request->getParam('id');
            $preDataInfo = Service_BgPriEntryDataDetailBodyHead::getByField($headId);
            if($preDataInfo['hz_status']=='1'||$preDataInfo['inv_no']!=''){
                throw new Exception("该预录入数据已经生成核注单");
            }
            //获取主表数据
            $prientryData =  Service_BgPriEntryData::getByField($preDataInfo['bped_id'],'bped_id');
            $formType = Service_FormType::getByField($preDataInfo['pt_code'],'form_type');



            $inv = new Process_Inv();
            $preProcess = new PriEnter();
            $companyInfo = $preProcess->getCompanyInfo($headId);
            $inv->setFormType($preDataInfo['pt_code']);
            $apinvtpro = new Api_Pre_PreDataToInvtProcess($headId);
            $data = $apinvtpro->getBaseInfo();
            $errors = $apinvtpro->getError();
            if(!empty($errors)){
                $errorinfo = array_map(function ($value) {
                    return "<p>" . $value . "</p>";
                }, $errors);
                throw new \Exception(implode("", $errorinfo));
            }
            $headInfo =  $data['headerInfo'];
            $bodyInfos = $data['bodyInfos'];
            if(empty($headInfo)||empty($bodyInfos)){
                throw new Exception("表头或者表体信息为空");
            }
            $headerError = $inv->validateHeadInfo($headInfo);
            if (!empty($headerError)) {
                $error = array_map(function ($value) {
                    return "<p>" . $value . "</p>";
                }, $headerError);
                throw new \Exception(implode("", $error));
            }
            $predDetaiBody = Service_BgPriEntryDataDetailBodyDetail::getByCondition([
                'bpedbh_id' => $headId
            ]);
            if (empty($predDetaiBody)) {
                throw new \Exception('表体信息不存在');
            }
            $invBody = $bodyInfos;
            /*foreach ($predDetaiBody as $body) {
                $productInfo = Service_Product::getByField($body['product_id']);
                $invBody[] = [
                    // 'SeqNo'=>$value['seq_no'],
                    'gds_seqno' => $body['g_no'],//商品序号
                    'putrec_seqno' => $body['contr_item'],//备案序号
                    'gds_mtno' => $body['goods_id'],//商品料号
                    'gdecd' => $body['code_ts'],//商品编码
                    'gds_nm' => $body['gname'],//商品名称
                    'gds_spcf_model_desc' => $body['gmodel'],//商品规格型号
                    'dcl_unitcd' => $body['gunit'],//申报计量单位
                    'lawf_unitcd' => $body['first_unit'],//法定计量单位
                    'secd_lawf_unitcd' => $body['second_unit'],//法二计量单位
                    'natcd' => $body['origin_country'],//原产国
                    'dcl_uprc_amt' => $body['decl_price'],//企业申报单价
                    'dcl_total_amt' => $body['decl_total'],//企业申报总价
//                    'usd_stat_total_amt'=>$body[''],//美元统计总金额
                    'dcl_currcd' => $body['trade_curr'],//币制
                    'lawf_qty' => $body['first_qty'],//法定数量
                    'secd_lawf_qty' => $body['second_qty'],//第二法定数量
//                    'wt_sf_val'=>$body[''],//重量比例引线
//                    'fst_sf_val'=>$body[''],//第一比例因子
//                    'secd_sf_val'=>$body[''],//第二比例因子
                    'dcl_qty' => $body['gqty'],//申报数量
                    'gross_wt' => sprintf("%.3f", $productInfo['product_weight'] * $body['gqty']),//毛重
                    'net_wt' => sprintf("%.3f", $productInfo['product_net_weight'] * $body['gqty']),//净重
                    'use_cd' => $body['purpose'],//用途代码
                    'lvyrlf_modecd' => $body['duty_mode'],//征免方式
                    'ucns_verno' => '',//单耗版本号
                    'entry_gds_seqno' => '',//报关单商品序号
//                    'apply_tb_seqno'=>$body[''],//流转申报表序号
                    'destination_natcd' => $body['dest_code'],//最终目的国
                    'rmk' => '',//备注
                    'product_id' => $body['product_id'],//商品ID
                ];
            }*/
            if($preDataInfo['ie_flag'] == 'I'){
                $bodyError = $inv->validateInBodyInfo($invBody, $preDataInfo['ems_no']);
            }else{
                $bodyError = $inv->validateOutBodyInfo($invBody, $preDataInfo['ems_no']);
            }

            if (!empty($bodyError['error'])) {
                $error = array_map(function ($value) {
                    return "<p>" . $value . "</p>";
                }, $bodyError['error']);
                throw new \Exception(implode("", $error));
            }
            $code = $inv->doSave($headInfo, $invBody);
            Service_BgPriEntryDataDetailBodyHead::update([
                'inv_no' => $code,
                'hz_status'=>'1'
            ], $headId);
            Service_InvtList::update(['bpedbh_id'=>$headId],$code,'EtpsInnerInvtNo');
            $db->commit();
            //$db->rollBack();
            $return['state'] = 1;
            $return['message'] = "转核注成功：" . $code;
        } catch (\Exception $e) {
            $db->rollBack();
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * note:生产核放单
     * Auther:Yao
     * Date:2022/7/5 17:46
     */
    public function makeInvSbAction()
    {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'error' => []
        ];
        $db = Common_Common::getAdapter();
        try {
            $db->beginTransaction();
            $preProcess = new PriEnter();
            $companyInfo = $preProcess->getCompanyInfo();
            $dataId = $this->_request->getParam('id');
            $priDataInfo = Service_BgPriEntryData::getByField($dataId);
            if (!empty($priDataInfo['inv_sb_code'])) {
                throw new \Exception("该录入数据已生成核放单");
            }
            $headInfo = Service_BgPriEntryDataDetailBodyHead::getByCondition([
                'bped_id' => $dataId
            ]);
            if (empty($headInfo)) {
                throw new \Exception("");
            }
            $rltNo = [];
            foreach ($headInfo as $h) {
                if (empty($h['inv_no'])) {
                    throw new \Exception("核注清单还未生成");
                }
                $rltNo[] = $h['inv_no'];
            }
            $params = $this->_request->getParams();
            Common_Common::trim_blank($params);
            $invHead = [
                'PassportNo' => '',
                'sb_mode' => '-1',
                'passportTypecd' => $params['passportTypecd'],
                'masterCuscd' => $priDataInfo['ie_port'],//主管关区代码
//                'DclTypecd' => "1",//
                'ioTypecd' => "I",//进出标志代码
                'bindTypecd' => '',//关联单证类型代码
                'rltTbTypecd' => '1',//关联单据类型,默认核注清单
                'rltNo' => implode("/", $rltNo),//关联单证编号
                'AreainOriactNo' => $headInfo['AreainOriactNo'],//区内账册编号
                'areainEtpsno' => $companyInfo['rcvgd_etps_no'],//区内企业编码
                'areainEtpsNm' => $companyInfo['rcvgd_etps_nm'],//区内企业名称
                'areainEtpsSccd' => $companyInfo['rvsngd_etps_sccd'],//区内企业社会信用代码
                'vehicleNo' => $params['vehicleNo'],//承运车车牌号
                'vehicleIcNo' => '',//IC卡号
                'containerNo' => $params['containerNo'],//集装箱号
                'vehicleWt' => $params['vehicleWt'],//车自重
                'vehicleFrameNo' => $params['vehicleFrameNo'],//车架号
                'vehicleFrameWt' => $params['vehicleFrameWt'],//车架重
                'containerType' => $params['containerType'],//集装箱箱型
                'containerWt' => $params['containerWt'],//集装箱重
                'totalWt' => $params['totalGrossWt'] + $params['vehicleWt'] + $params['vehicleFrameWt'],//总重量
                'totalGrossWt' => $params['totalGrossWt'],//货物总毛重
                'totalNetWt' => $params['totalNetWt'],//货物总净重
                'DclErConc' => $params['DclErConc'],//申请人及联系方式

                'DclTime' => date("Y-m-d H:i:s", time()),//申报时间
                'DclEtpsno' => $companyInfo['declare_customs_code'],//申报企业编号
                'DclEtpsNm' => $companyInfo['declare_company_name'],//申报企业名称
                'DclEtpsSccd' => $companyInfo['declare_social_credit_code'],//申报企业社会信用代码
                'InputCode' => '',//录入单位代码
                'InputSccd' => '',//录入单位社会信用代码
                'InputName' => '',//
                'rmk' => $params['remark'],//
//                'del_no' => $headInfo['sb_mode'],//
            ];
            $invInvo = Service_BgPriEntryDataDetailBodyHead::getByCondition([
                'bped_id' => $dataId
            ]);
            $invSb = [];
            foreach ($invInvo as $inv) {
                $invSb[] = $inv['inv_no'];
            };
            $invProcess = new Process_InvtSb();
            $error = $invProcess->validateHeadInfo($invHead, $invSb);
            if (!empty($error)) {
                throw new \Exception(implode("<br/>", $error));
            }
            $invCode = $invProcess->doSave($invHead, $invSb);
            if ($invCode) {
                $return['state'] = 1;
                $return['message'] = "生成核放单成功:" . $invCode;
                Service_BgPriEntryData::update([
                    'inv_sb_code' => $invCode
                ], $dataId);
            } else {
                $return['message'] = "生成核放单失败";
            }
            //$db->commit();
            $db->rollBack();
        } catch (\Exception $e) {
            $db->commit();
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * @todo 生成报关单
     */
    public function makeBaoguanAction()
    {
        $return = [
            'state' => 0,
            'message' => 'fail',
            'error' => [],
            'code' => '',
        ];
        //echo "<pre>";
        $db = Common_Common::getAdapter();
        try {
            $db->beginTransaction();
            $dataId = $this->_request->getParam('id');
            $preDataInfo = Service_BgPriEntryDataDetailBodyHead::getByField($dataId);
            if (empty($preDataInfo)) {
                throw new \Exception("参数无效");
            }
            if ($preDataInfo['bg_status'] == '1'||$preDataInfo['baoguan_code']!='') {
                throw new \Exception("该录入数据已生成报关单");
            }
            $preProcess = new Api_Pre_PreDataToBaoguanProcess($dataId);
            $res = $preProcess->makebaoguan();
            if ($res['state'] == '1') {
                $return['state'] = 1;
                $return['code'] = $res['code'];
                $code = $res['code'];
                Service_BgPriEntryDataDetailBodyHead::update([
                    'baoguan_code' => $code,
                    'bg_status'=>'1'
                ], $dataId);
                //更新报关单增加预录入表头
                Service_DesMessageHead::update(['bpedbh_id'=>$dataId],$code,'dmh_no');
                $return['message'] = '生成报关单成功';
            } else {
                $return['message'] = $res['message'];
            }
            //$db->commit();
            $db->rollBack();
        } catch (\Exception $e) {
            $db->rollBack();
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * @todo 删除预录入数据
     */
    public function deletePreAction(){
        $return = [
            'state' => 0,
            'message' => 'fail',
            'error' => [],
            'code' => '',
        ];
        //echo "<pre>";
        $db = Common_Common::getAdapter();
        try {
            $db->beginTransaction();
            $dataId = $this->_request->getParam('id');
            $apdp = new Api_Pre_PreDataProcess();
            $param = array(
                'id'=>$dataId
            );
            //$apdp->setParam($param);
            $res = $apdp->deletePreData($param);
            if($res){
                $return['state'] = 1;
                $return['message'] = "删除成功";
            }else{
                $return['error'] = $apdp->getError();
            }
            $db->commit();
            //$db->rollBack();
            //$db->commit();
        } catch (\Exception $e) {
            //$db->commit();
            $db->rollBack();
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }


    /**
     * @date 2022/7/11
     * @todo 导入报关单
     * @auther 46935
     */
    public function importAction()
    {
        $return = [
            'state' => 0,
            'message' => '',
            'data' => [],
            'error' => [],
        ];
        try {
            $upload = new Process_Upload();
            $formType = $this->_request->getParam('form_type');
            if(empty($formType)){
                throw new Exception("请选择业务类型");
            }
            $companyCode = $this->_request->getParam('company_code');
            if(empty($companyCode)){
                throw new Exception("请选择配置企业");
            }
            $savePath = APPLICATION_PATH . '/../data/baoguan/';
            $uploadInfo = $upload->uploadXls($savePath, 'data_file');
            if ($uploadInfo['state'] != 1) {
                throw new Exception($uploadInfo['message']);
            }
            $filePath = $uploadInfo['path'];
            $baoguanProcess = new Process_CisBaoguanDanUpload();
            $baoguanProcess->setFilePath($filePath);
            $headInfo = $baoguanProcess->getBaseInfo();
            $bodyInfo = $baoguanProcess->getBodyInfo();
            $companyInfo = Service_BgCompany::getByField($companyCode,'company_code');
            if (empty($bodyInfo)) {
                throw new Exception('报关单商品信息不存在');
            }
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try{
                //return Common_GetNumbers::getCode('ASN', '', $this->_pro);
                if($headInfo['bpd_ref_no']!=''){
                    $bpdNumber = $headInfo['bpd_ref_no'];
                }else{
                    $bpdNumber = Common_GetNumbers::getOnlyCode('QG',$formType);
                }
                $bgpdh = Service_BgPriEntryDataDetailBodyHead::getByField($bpdNumber,'bpd_ref_no');
                if(!empty($bgpdh)){
                    throw new Exception("改单号已经存在".$bpdNumber);
                }
                $formTypeInfo = Service_FormType::getByField($formType,'form_type');
                if(empty($formTypeInfo)){
                    throw new Exception('业务类型错误');
                }
                //$defaultValue = json_decode($formTypeInfo['default_value'],true);
                $formRow = Service_FormType::getFormDefaultRow($formType,'form_type');
                if($formRow['state']=='99'){
                    throw new Exception($formRow['message']);
                }
                $defaultRow = $return['data'];
                $ie_port = '5349';
                $trade_mode="";
                if(!empty($defaultRow)){
                    $ie_port =$defaultRow['ie_port'];
                    $trade_mode=$defaultRow['trade_mode'];
                }

                $ieFlag= $formType=='IN1D'?'I':'E';
                $dataInfo = [
                    'ref_no'=>$bpdNumber,
                    'pt_code'=>$formTypeInfo['form_type'],
                    'declare_port'=>$headInfo['declare_port'],//?
                    'ie_port'=>$headInfo['declare_port'],//?
                    'pack_number'=>$headInfo['pack_no'],
                    'net_weight'=>$headInfo['net_wt'],
                    'company_code'=>$companyCode,
                    'gross_weight'=>$headInfo['gross_wt'],
                    'add_time'=>date("Y-m-d H:i:s"),
                    'pre_status'=>'-1',
                    'ie_flag'=>$ieFlag,
                ];
                $dataId = Service_BgPriEntryData::add($dataInfo);
                $headInfo['bped_id'] = $dataId;
                $headInfo['add_time'] = date("Y-m-d H:i:s");
                $headInfo['bpd_ref_no'] = $bpdNumber;
                $headInfo['pt_code']=$formTypeInfo['form_type'];
                $headInfo['ems_no']=$companyInfo['bwl_no'];
                $headInfo['ie_port']=$ie_port;
                $headInfo['ie_flag']=$ieFlag;
                //$headInfo['trade_mode'] = $trade_mode;
                $headInfo['agent_code'] = $companyInfo['declare_customs_code'];
                $headInfo['agent_name'] = $companyInfo['declare_company_name'];
                $headInfo['num'] =1;
//                $headInfo['rlt_entry_bizop_etps_sccd']=$companyInfo['bizop_etps_sccd'];
                $headInfo['rlt_entry_bizop_etpsno']=$headInfo['owner_code'];
                $headInfo['rlt_entry_bizop_etps_nm']=$headInfo['owner_name'];
                $headInfo['rlt_entry_rvsngd_etps_sccd']=$companyInfo['rvsngd_etps_sccd'];//?
                $headInfo['rlt_entry_rcvgd_etpsno']=$headInfo['owner_code']; //$companyInfo['rcvgd_etps_no'];//?
                $headInfo['rlt_entry_rcvgd_etps_nm']=$headInfo['owner_name']; //$companyInfo['rcvgd_etps_nm'];//?
                unset($headInfo['docu_code']);
                $headId = Service_BgPriEntryDataDetailBodyHead::add($headInfo);
                foreach ($bodyInfo as $body){
                    $body['bpedbh_id'] =$headId;
                    $body['product_type'] = 2;
                    $condition =[];
                    if($body['goods_id']){
                        $condition['goods_id'] = $body['goods_id'];
                    }else{
                        $condition['gmodel']=$body['gmodel'];
                        $condition['gname']=$body['gname'];
                        $condition['hs_code']=$body['code_ts'];
                        $condition['origin_country']=$body['origin_country'];
                    }
                    $gProduct = Service_BgProduct::getByCondition($condition,'*',1,1);
                    $productId='';
                    if($gProduct){
                        $gProduct = $gProduct[0];
                        $productId = $gProduct['cp_id'];
                        if($gProduct['contr_item'] && !$body['contr_item']){
                            $body['contr_item'] =$gProduct['contr_item'];
                        }
                    }
                    $body['product_id']=$productId;
                    //$body['product_type'] ='1';
                    Service_BgPriEntryDataDetailBodyDetail::add($body);
                }
                $db->commit();
                //$db->rollBack();
                $return['state'] =1 ;
                $return['message'] ='导入成功';
            }catch (\Exception $e){
                $db->rollBack();
                throw $e;
            }
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * note:抓取备案序号
     * Auther:Yao
     * Date:2022/7/14 10:48
     */
    public function fetchBillAction(){
        $return = [
            'state' => 0,
            'message' => '',
            'data' => [],
            'error' => [],
        ];
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try {
            if(!$this->_request->isPost()){
               throw new \Exception("请求错误");
            }
            $headId = $this->_request->getParam('head_id');
            if(empty($headId)){
                throw new \Exception("参数错误");
            }
            $headInfo = Service_BgPriEntryDataDetailBodyHead::getByField($headId);
            if(empty($headInfo)){
                throw new \Exception("参数错误");
            }
            $detailList = Service_BgPriEntryDataDetailBodyDetail::getByCondition([
                'bpedbh_id'=>$headId
            ]);
            foreach ($detailList as $detail){
                if($detail['product_type']!=2){
                    throw new \Exception("不是一日游数据，不能抓取");
                }
                if(empty($detail['contr_item'])) {
                    $condition = [];
                    if ($detail['goods_id']) {
                        $condition['goods_id'] = $detail['goods_id'];
                    } else {
                        $condition['gmodel'] = $detail['gmodel'];
                        $condition['gname'] = $detail['gname'];
                        $condition['hs_code'] = $detail['code_ts'];
                        $condition['origin_country'] = $detail['origin_country'];
                        $condition['trade_co']=$headInfo['trade_co'];
                    }
                    $gProduct = Service_BgProduct::getByCondition($condition, '*', 1, 1);
                    $contrItem ='';
                    if ($gProduct) {
                        $gProduct = $gProduct[0];
                        $contrItem = $gProduct['contr_item'];
                    }
                    if($contrItem){
                        Service_BgPriEntryDataDetailBodyDetail::update([
                            'contr_item'=>$contrItem
                        ],$detail['bpedbdd_id']);
                    }
                }
            }
            $db->commit();
            $return['state'] = 1;
            $return['message'] ='抓取成功：匹配成功的已经填上备案序号，未匹配的还是原始数据';
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }

    /**
     * @date 2022/7/14
     * @todo 导出表体信息
     * @auther 46935
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     * @throws PHPExcel_Writer_Exception
     */
    public function exportAction(){
        $id = $this->_request->getParam('head-id');
        require_once "PHPExcel1.8/PHPExcel.php";
        require_once "PHPExcel1.8/PHPExcel/Reader/Excel2007.php";
        require_once "PHPExcel1.8/PHPExcel/Reader/Excel5.php";
        $detailInfo = Service_BgPriEntryDataDetailBodyDetail::getByCondition([
            'bpedbh_id'=>$id
        ]);
        $headInfo = Service_BgPriEntryDataDetailBodyHead::getByField($id);

        $excel = new PHPExcel();
        $sheet = $excel->getActiveSheet();
        $title = [
             '商品序号'=>'g_no',
            '主键'=>'bpedbdd_id',
            '商品SKu'=>'sku',
            '商品名称'=>'gname',
            '归类标志'=>'class_mark',
            '商品编号'=>'code_ts',
            '备案序号'=>'contr_item',
            '申报单价'=>'decl_price',
            '征减免税方式'=>'duty_mode',
            '申报计量单位与法定单位比例因子'=>'factor',
            '商品规格、型号'=>'gmodel',
            '原产国(地区)'=>'origin_country',
            '成交币制'=>'trade_curr',
            '申报总价'=>'decl_total',
            '申报数量（成交计量单位'=>'gqty',
            '第一法定数量'=>'first_qty',
            '第二法定数量'=>'second_qty',
            '申报计量单位'=>'gunit',
            '第一计量单位'=>'first_unit',
            '第二计量单位'=>'second_unit',
            '用途/生产厂家'=>'use_to',
            '工缴费'=>'work_usd',
            '货号'=>'exg_no',
            '版本号'=>'exg_version',
            '最终目的国（地区）'=>'destination_country',
            '检验检疫编码'=>'ciq_code',
            '申报货物名称'=>'decl_goods_ename',
            '原产地区代码'=>'orig_place_code',
            '用途代码'=>'purpose',
            '产品有效期'=>'prod_valid_dt',
            '产品保质期'=>'prod_qgp',
            '货物属性代码'=>'goods_attr',
            '成份/原料/组份'=>'stuff',
            '编码'=>'uncode',
            '危险货物名称'=>'dang_name',
            '危包类别'=>'dang_pack_type',
            '危包规格'=>'dang_pack_spec',
            '境外生产企业名称'=>'eng_man_ent_cnm',
            '非危险化学品'=>'no_dang_flag',
            '目的地代码'=>'dest_code',
            '货物规格'=>'goods_spec',
            '货物型号'=>'goods_model',
            '货物品牌'=>'goods_brand',
            '生产日期'=>'produce_date',
            '生产批号'=>'prod_batch_no',
            '境内目的地/境内货源地'=>'district_code',
            '检验检疫名称'=>'ciq_name',
            '生产单位注册号'=>'mnufctr_reg_no',
            '生产单位名称'=>'mnufctr_reg_name',
//            '添加时间'=>'add_time',
//            '更新时间'=>'update_time',
            '优惠贸易协定项下原产地'=>'rcep_orig_place_code',
        ];
        $sheet->fromArray(array_keys($title));
        $index = 2;
        foreach ($detailInfo as $detail){
            $columnStart =   PHPExcel_Cell::columnIndexFromString("A");
            if($detail['product_type'] == 0){
                $productInfo = Service_Product::getByField($detail['product_id']);
                $detail['sku'] = $productInfo['product_sku'];
            }
            foreach ($title as $column){
                $columnChar = PHPExcel_Cell::stringFromColumnIndex($columnStart-1);
                $sheet->setCellValueExplicit($columnChar.$index,$detail[$column],PHPExcel_Cell_DataType::TYPE_STRING);
                $columnStart++;
            }
            $index++;
        }
        header('Pragma:public');
        $filename = $headInfo['bpd_ref_no'].date("mdhis").".xls";
        header('Content-Type:application/x-msexecl;name="' . $filename . '"');
        header("Content-Disposition:inline;filename=" . $filename);
        $writer = PHPExcel_IOFactory::createWriter($excel,"Excel5");
        $writer->save("php://output");
    }
    /**
     * @date 2022/7/14
     * @todo 导入表体修改
     * @auther 46935
     */
    public function importDetailAction(){
        $return = [
            'state' => 0,
            'message' => '',
            'data' => [],
            'error' => [],
        ];
        try {
            if(!$this->_request->isPost()){
                throw new \Exception("请求错误");
            }
            $upload = new Process_Upload();
            $savePath = APPLICATION_PATH . '/../data/pre-data-detail/';
            $uploadInfo = $upload->uploadXls($savePath, 'data_file');
            if ($uploadInfo['state'] != 1) {
                throw new Exception($uploadInfo['message']);
            }
            $filePath = $uploadInfo['path'];
            $title = [
                '商品序号'=>'g_no',
                '主键'=>'bpedbdd_id',
                '商品SKu'=>'sku',
                '归类标志'=>'class_mark',
                '商品编号'=>'code_ts',
                '备案序号'=>'contr_item',
                '申报单价'=>'decl_price',
                '征减免税方式'=>'duty_mode',
                '申报计量单位与法定单位比例因子'=>'factor',
                '商品规格、型号'=>'gmodel',
                '商品名称'=>'gname',
                '原产国(地区)'=>'origin_country',
                '成交币制'=>'trade_curr',
                '申报总价'=>'decl_total',
                '申报数量（成交计量单位'=>'gqty',
                '第一法定数量'=>'first_qty',
                '第二法定数量'=>'second_qty',
                '申报计量单位'=>'gunit',
                '第一计量单位'=>'first_unit',
                '第二计量单位'=>'second_unit',
                '用途/生产厂家'=>'use_to',
                '工缴费'=>'work_usd',
                '货号'=>'exg_no',
                '版本号'=>'exg_version',
                '最终目的国（地区）'=>'destination_country',
                '检验检疫编码'=>'ciq_code',
                '申报货物名称'=>'decl_goods_ename',
                '原产地区代码'=>'orig_place_code',
                '用途代码'=>'purpose',
                '产品有效期'=>'prod_valid_dt',
                '产品保质期'=>'prod_qgp',
                '货物属性代码'=>'goods_attr',
                '成份/原料/组份'=>'stuff',
                '编码'=>'uncode',
                '危险货物名称'=>'dang_name',
                '危包类别'=>'dang_pack_type',
                '危包规格'=>'dang_pack_spec',
                '境外生产企业名称'=>'eng_man_ent_cnm',
                '非危险化学品'=>'no_dang_flag',
                '目的地代码'=>'dest_code',
                '货物规格'=>'goods_spec',
                '货物型号'=>'goods_model',
                '货物品牌'=>'goods_brand',
                '生产日期'=>'produce_date',
                '生产批号'=>'prod_batch_no',
                '境内目的地/境内货源地'=>'district_code',
                '检验检疫名称'=>'ciq_name',
                '生产单位注册号'=>'mnufctr_reg_no',
                '生产单位名称'=>'mnufctr_reg_name',
//            '添加时间'=>'add_time',
//            '更新时间'=>'update_time',
                '优惠贸易协定项下原产地'=>'rcep_orig_place_code',
            ];
            $bodyInfo = Common_Upload::readXlsFromTitle($filePath,$title);
            if (empty($bodyInfo)) {
                throw new Exception('上传文件错误，');
            }
            $db = Common_Common::getAdapter();
            $db->beginTransaction();
            try{
                $id = $this->_request->getPost('head_id');
                $headInfo = Service_BgPriEntryDataDetailBodyHead::getByField($id);
                if(empty($headInfo)){
                    throw new Exception("预录入数据不存在,参数错误");
                }
                foreach ($bodyInfo as $body){
                    if(empty($body['bpedbdd_id'])){
                        throw new \Exception("主键不能为空");
                    }
                    $oldData = Service_BgPriEntryDataDetailBodyDetail::getByField($body['bpedbdd_id']);
                    if(empty($oldData)){
                        throw new \Exception("主键：".$body['bpedbdd_id'].'数据不存在');
                    }
                    $update = $body;
                    $update['update_time']=date("Y-m-d H:i:s");
                    unset($update['sku']);
                    Service_BgPriEntryDataDetailBodyDetail::update($update,$body['bpedbdd_id']);
                }
                $db->commit();
                $return['state'] =1 ;
                $return['message'] ='导入成功';
            }catch (\Exception $e){
                $db->rollBack();
                throw $e;
            }
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }
    /**
     * @date 2022/7/14
     * @todo 复制入区申报数据
     * @auther 46935
     */
    public function copyPreAction(){
        $return =[
            'state'=>0,
            'message'=>'fail',
            'data'=>[]
        ];
        $db = Common_Common::getAdapter();
        $db->beginTransaction();
        try{
            if($this->_request->isPost()){
                $id = $this->_request->getParam('bped_id');
                $preData = Service_BgPriEntryData::getByField($id);
                if(empty($preData)){
                    throw new \Exception("预录入数据不存在");
                }
                if($preData['ie_flag']!='I'){
                    throw new \Exception("预录入数据不是进口类型，只能从一日游进口类型复制到出口类型");
                }
                $formType='EN1D';
                $bpdNumber = Common_GetNumbers::getOnlyCode('QG',$formType);
                $newData = $preData;
                $newData['ref_no'] = $bpdNumber;
                $newData['add_time'] = date("Y-m-d H:i:s");
                $newData['ie_flag']='E';
                unset($newData['bped_id'],$newData['update_time']);
                $newId = Service_BgPriEntryData::add($newData);
                $preDataHead = Service_BgPriEntryDataDetailBodyHead::getByCondition([
                    'bped_id'=>$id
                ]);
                foreach ($preDataHead as $head){
                    $newHead = $head;
//                    $headRefNO = Common_GetNumbers::getOnlyCode('detail_body_head',"");
                    $newHead['bpd_ref_no'] =$bpdNumber;
                    $newHead['add_time']=date("Y-m-d H:i:s");
                    $newHead['bped_id']=$newId;
                    unset($newHead['bpedbh_id'],$newHead['update_time']);
                    unset($newHead['hz_status']);
                    unset($newHead['invt_no']);
                    unset($newHead['inv_no']);
                    unset($newHead['bg_status']);
                    unset($newHead['baoguan_code']);
                    $newHeadId = Service_BgPriEntryDataDetailBodyHead::add($newHead);
                    $headDetail = Service_BgPriEntryDataDetailBodyDetail::getByCondition([
                        'bpedbh_id'=>$head['bpedbh_id']
                    ]);
                    foreach ($headDetail as $hdeail){
                        $newHeadDetail = $hdeail;
                        $newHeadDetail['bpedbh_id'] =$newHeadId;
                        unset($newHeadDetail['update_time'],$newHeadDetail['bpedbdd_id']);
                        Service_BgPriEntryDataDetailBodyDetail::add($newHeadDetail);
                    }
                    $containerList = Service_BgPriEntryDataDetailBodyContainers::getByCondition([
                        'bpedbh_id'=>$head['bpedbh_id']
                    ]);
                    if(!empty($containerList)){
                        foreach ($containerList as $container){
                            $newContainer = $container;
                            $newContainer['bpedbh_id']= $newHeadId;
                            unset($newContainer['bpeddbc_id']);
                            Service_BgPriEntryDataDetailBodyContainers::add($newContainer);
                        }
                    }
                    $licenDou = Service_BgPriEntryDataDetailBodyLicensedocu::getByCondition([
                        'bpedbh_id'=>$head['bpedbh_id']
                    ]);
                    if(!empty($licenDou)){
                        foreach ($licenDou as $licens){
                            $newLicens = $licens;
                            $newLicens['bpedbh_id']= $newHeadId;
                            unset($newLicens['bpedbl_id']);
                            Service_BgPriEntryDataDetailBodyLicensedocu::add($newLicens);
                        }
                    }
                    $log=[
                        'bped_id'=>$newId,
                        'bpedbh_id'=>$newHeadId,
                        'change_status'=>'predata',
                        'ip'=>Common_Common::getRealIp(),
                        'add_time'=>date("Y-m-d H:i:s"),
                        'content'=>'复制预录入数据：'.$id.'->'.$newId
                    ];
                    Service_BgPriEntryDataDetailLog::add($log);
                }
                $db->commit();
                //$db->rollBack();
                $return['state'] = 1;
                $return['message'] ="复制预录入数据成功：".$bpdNumber;
            }
        }catch (\Exception $e){
            $return['message'] = $e->getMessage();
        }
        die(Zend_Json::encode($return));
    }


}
