<?php
/**
 * note:海关入库清单报文
 * Created by PhpStorm.
 * User: boyer
 * Date: 2019/12/21
 * Time: 16:57
 */

use Jobs\ClientRequest\Customs;
use Pheanstalk\Job;
use Pheanstalk\Pheanstalk;
use App\models\Logistic\Api\SendXml\Baoguandan;

class Api_Des_Receiving
{
    protected $file;
    protected $desHead;
    protected $result;

    public function getSendConfig()
    {
        //暂时写死后面做成可以配置的
        $sendStr = '{"sendType":"beanstalkd","config":{"host":"132.232.48.179","port":"11300","tube":"baoguandanSend"}}';
        return json_decode($sendStr, true);
    }

    public function getFentchConfig()
    {
        //暂时写死后面做成可以配置的
//        $fetchStr = '{"sendType":"beanstalkd","config":{"host":"132.232.48.179","port":"11300","tube":"baoguandanfetch"}}';
        $fetchStr = Service_BgCompany::getDefault();
        return json_decode($fetchStr['config_value'], true);
    }

    public function getXmlById($id)
    {
        $data = $this->makeData($id);
        return $this->toXml($data);
    }

    protected function makeData($id)
    {
        $countrys = Service_Country::getByCondition([],"*");
        $countryTradeRows = [];
        if(!empty($countrys)){
            foreach ($countrys as $k=>$v){
                if($v['trade_country']!=''&&$v['country_code_single']!=''){
                    $countryTradeRows[$v['trade_country']] = $v;
                }
            }
        }
        $desHead = Service_DesMessageHead::getByField($id);
        $this->desHead = $desHead;
        $desList = Service_DesMessageList::getByCondition(array(
            'dmh_id' => $id
        ));
        //print_r($desHead);
        $listData = array();
        $gno = 1;
        foreach ($desList as $list) {
            $ProdValidDt = "";
            if ($list['prod_valid_dt'] != '0000-00-00') {
                $ProdValidDt = $list['prod_valid_dt'];
            }
            $ProduceDate = "";
            if ($list['produce_date'] != '0000-00-00') {
                $ProduceDate = $list['produce_date'];
            }
            $ProdQgp = "";
            if ($list['prod_qgp'] != '0000-00-00') {
                $ProdQgp = $list['prod_qgp'];
            }
            $DestinationCountry = $list['destination_country'];
            if(isset($countryTradeRows[$DestinationCountry])){
                $DestinationCountry = $countryTradeRows[$DestinationCountry]['country_code_single'];
            }
            $OriginCountry=$list['origin_country'];
            if(isset($countryTradeRows[$OriginCountry])){
                $OriginCountry = $countryTradeRows[$OriginCountry]['country_code_single'];
            }

            $TradeCurr = $list['trade_curr'];
            if(!empty($TradeCurr)){
                $currency = Service_Currency::getByField($TradeCurr,'currency_hs_code');
                if(!empty($currency)){
                    $TradeCurr = $currency['currency_code'];
                }
            }

            $listRow = array(
                'CodeTS' => $list['code_ts'],
                'ContrItem' => '',//$list['contr_item'],报关单不要序号
                'DeclPrice' => sprintf("%.4f", $list['decl_price']),
                'DutyMode' => $list['duty_mode'],
                'ClassMark' => '', //归类标志留空
                'Factor' => $list['factor'],
                'GModel' => $list['gmodel'],
                'GName' => $list['gname'],
                'GNo' => $gno,
                'OriginCountry' => $OriginCountry,
                'TradeCurr' => $TradeCurr,
                'DeclTotal' => sprintf("%.2f", $list['decl_total']),
                'GQty' => $list['gqty'],
                'FirstQty' => $list['first_qty'],
                'SecondQty' => $list['second_qty'],
                'GUnit' => $list['gunit'],
                'FirstUnit' => $list['first_unit'],
                'SecondUnit' => $list['second_unit'],
                'UseTo' => $list['use_to'],
                'WorkUsd' => sprintf("%.2f", $list['work_usd']),
                'ExgNo' => $list['exg_no'],
                'ExgVersion' => $list['exg_version'],
                'DestinationCountry' => $DestinationCountry,
                'CiqCode' => $list['ciq_code'],
                'DeclGoodsEname' => $list['decl_goods_ename'],
                'OrigPlaceCode' => $list['orig_place_code'],
                'Purpose' => $list['purpose'],
                'ProdValidDt' => $ProdValidDt,
                'ProdQgp' => $ProdQgp,
                'GoodsAttr' => $list['goods_attr'],
                'Stuff' => $list['stuff'],
                'Uncode' => $list['uncode'],
                'DangName' => $list['dang_name'],
                'DangPackType' => $list['dang_pack_type'],
                'DangPackSpec' => $list['dang_pack_spec'],
                'EngManEntCnm' => $list['eng_man_ent_cnm'],
                'NoDangFlag' => $list['no_dang_flag'],
                'DestCode' => $list['dest_code'],
                'GoodsSpec' => $list['goods_spec'],
                'GoodsModel' => $list['goods_model'],
                'GoodsBrand' => $list['goods_brand'],
                'ProduceDate' => $ProduceDate,
                'ProdBatchNo' => $list['prod_batch_no'],
                'DistrictCode' => $list['district_code'],
                'CiqName' => $list['ciq_name'],
                'MnufctrRegNo' => $list['mnufctr_reg_no'],
                'MnufctrRegName' => $list['mnufctr_reg_name'],
            );
            ksort($listRow);
            $listData[] = $listRow;
            $gno++;
        }
        $cmpl_dschrg_dt = "";
        if ($desHead['cmpl_dschrg_dt'] != '0000-00-00') {
            $cmpl_dschrg_dt = date("Ymd", strtotime($desHead['cmpl_dschrg_dt']));
        }
        $pdate = "";
        if ($desHead['pdate'] != '0000-00-00 00:00:00') {
            $pdate = date("Ymd", strtotime($desHead['pdate']));
        }
        //做下企业信息转发
        $agentEnt = [];
        if ($desHead['agent_code'] != '') {
            $agentEnt = Service_EntInfo::getEntBycustomerOrscc($desHead['agent_code']);
        }
        $ownerCode = [];
        if ($desHead['owner_code'] != '') {
            $ownerCode = Service_EntInfo::getEntBycustomerOrscc($desHead['owner_code']);
        }
        $trade_code = [];
        if ($desHead['trade_code'] != '') {
            $trade_code = Service_EntInfo::getEntBycustomerOrscc($desHead['trade_code']);
        }


        $TradeCountry = $desHead['trade_country'];
        if(isset($countryTradeRows[$TradeCountry])){
            $TradeCountry = $countryTradeRows[$TradeCountry]['country_code_single'];
        }
        $TradeAreaCode = $desHead['trade_area_code'];
        if(isset($countryTradeRows[$TradeAreaCode])){
            $TradeAreaCode = $countryTradeRows[$TradeAreaCode]['country_code_single'];
        }
        $OtherRate = "";
        if($desHead['other_rate']>0){
            $OtherRate=sprintf("%.4f", $desHead['other_rate']);
        }

        $DecHead = array(
            'SeqNo' => $desHead['seq_no'],
            'IEFlag' => $desHead['ieflag'],
            'Type' => $desHead['type'],
            'AgentCode' => !empty($agentEnt) ? $agentEnt['ent_customs_code'] : $desHead['agent_code'],
            'AgentName' => !empty($agentEnt) ? $agentEnt['ent_name'] : $desHead['agent_name'],
            'ApprNo' => $desHead['appr_no'],
            'BillNo' => $desHead['bill_no'],
            'ContrNo' => $desHead['contr_no'],
            'CustomMaster' => $desHead['custom_master'],
            'CutMode' => $desHead['cut_mode'],
            'DistinatePort' => $desHead['distinate_port'],
            'FeeCurr' => $desHead['fee_curr'],
            'FeeMark' => $desHead['fee_mark'],
            'FeeRate' => sprintf("%.4f", $desHead['fee_rate']),
            'GrossWet' => $desHead['gross_wet'],
            'IEDate' => date("Ymd", strtotime($desHead['iedate'])),
            'IEPort' => $desHead['ieport'],
            'InsurCurr' => $desHead['insur_curr'],
            'InsurMark' => $desHead['insur_mark'],
            'InsurRate' => sprintf("%.4f", $desHead['insur_rate']),
            'LicenseNo' => $desHead['license_no'],
            'ManualNo' => $desHead['manual_no'],
            'NetWt' => $desHead['net_wt'],
            'NoteS' => $desHead['note_s'],
            'OtherCurr' => $desHead['other_curr'],
            'OtherMark' => $desHead['other_mark'],
            'OtherRate' => $OtherRate,
            'OwnerCode' => !empty($ownerCode) ? $ownerCode['ent_customs_code'] : $desHead['owner_code'],
            'OwnerName' => !empty($ownerCode) ? $ownerCode['ent_name'] : $desHead['owner_name'],
            'PackNo' => $desHead['pack_no'],
            'TradeCode' => !empty($trade_code) ? $trade_code['ent_customs_code'] : $desHead['trade_code'],
            'TradeCountry' => $TradeCountry,
            'TradeMode' => $desHead['trade_mode'],
            'TradeName' => !empty($trade_code) ? $trade_code['ent_name'] : $desHead['trade_name'],
            'TrafMode' => $desHead['traf_mode'],
            'TrafName' => $desHead['traf_name'],
            'TransMode' => $desHead['trans_mode'],
            'WrapType' => $desHead['wrap_type'],
            'EntryId' => $desHead['entry_id'],
            'PreEntryId' => $desHead['pre_entry_id'],
            'EdiId' => $desHead['edi_id'],
            'Risk' => $desHead['risk'],
            'CopName' => $desHead['cop_name'],
            'CopCode' => $desHead['cop_code'],
            'EntryType' => $desHead['entry_type'],
            'PDate' => $pdate,
            'TypistNo' => $desHead['typist_no'],
            'InputerName' => $desHead['inputer_name'],
            'PartenerID' => $desHead['partener_id'],
            'TgdNo' => $desHead['tgd_no'],//可以不要
            'DataSource' => $desHead['data_source'],
            'DeclTrnRel' => $desHead['decl_trn_rel'],
            'ChkSurety' => $desHead['chk_surety'],
            'BillType' => $desHead['bill_type'],
            'CopCodeScc' => $desHead['cop_code_scc'],//可以不要
            'OwnerCodeScc' => !empty($ownerCode) ? $ownerCode['ent_code_scc'] : $desHead['owner_code_scc'],
            'AgentCodeScc' => !empty($agentEnt) ? $agentEnt['ent_code_scc'] : $desHead['agent_code_scc'],
            'TradeCoScc' => !empty($trade_code) ? $trade_code['ent_code_scc'] : $desHead['trade_co_scc'],
            'PromiseItmes' => $desHead['promise_itmes'],
            'TradeAreaCode' => $TradeAreaCode,
            'CheckFlow' => $desHead['check_flow'],//不是必须
            'TaxAaminMark' => $desHead['tax_aamin_mark'],//不是必须
            'MarkNo' => $desHead['mark_no'],
            'DespPortCode' => $desHead['desp_port_code'],
            'EntyPortCode' => $desHead['enty_port_code'],
            'GoodsPlace' => $desHead['goods_place'],
            'BLNo' => $desHead['blno'],
            'InspOrgCode' => $desHead['insp_org_code'],
            'SpecDeclFlag' => $desHead['spec_decl_flag'],
            'PurpOrgCode' => $desHead['purp_org_code'],
            'DespDate' => date("Ymd", strtotime($desHead['desp_date'])),
            'CmplDschrgDt' => $cmpl_dschrg_dt,
            'CorrelationReasonFlag' => $desHead['correlation_reason_flag'],
            'VsaOrgCode' => $desHead['vsa_org_code'],
            'OrigBoxFlag' => $desHead['orig_box_flag'],
            'DeclareName' => $desHead['declare_name'],
            'NoOtherPack' => $desHead['no_other_pack'],
            'OrgCode' => $desHead['org_code'],
            'OverseasConsignorCode' => $desHead['overseas_consignor_code'],
            'OverseasConsignorCname' => $desHead['overseas_consignor_cname'],
            'OverseasConsignorEname' => $desHead['overseas_consignor_ename'],
            'OverseasConsignorAddr' => $desHead['overseas_consignor_addr'],
            'OverseasConsigneeCode' => $desHead['overseas_consignee_code'],
            'OverseasConsigneeEname' => $desHead['overseas_consignee_ename']!=''?$desHead['overseas_consignee_ename']:$desHead['overseas_consignor_ename'],
            'DomesticConsigneeEname' => $desHead['domestic_consignee_ename'],
            'CorrelationNo' => $desHead['correlation_no'],
            'EdiRemark2' => $desHead['edi_remark2'],
            'EdiRemark' => $desHead['edi_remark'],
            'TradeCiqCode' => $desHead['trade_ciq_code'],
            'OwnerCiqCode' => $desHead['owner_ciq_code'],
            'DeclCiqCode' => $desHead['decl_ciq_code'], //申报单位检验检疫机构代码
        );
        ksort($DecHead);

        //查集装箱信息
        $condition = array(
            'dmh_id' => $id
        );
        $containers = Service_DesMessageContainers::getByCondition($condition);
        $containersRows = [];
        if (!empty($containers)) {
            foreach ($containers as $k => $container) {
                $containersRow = array(
                    'ContainerId' => $container['container_id'],//集装箱号
                    'ContainerMd' => $container['container_md'],//集装箱规格
                    'GoodsNo' => $container['goods_no'],//商品项号，用半角逗号分隔，如“1,3”
                    // 'LclFlag'=>'',//拼箱标识
                    'GoodsContaWt' => $container['goods_conta_wt'],//箱货重量
                    'ContainerWt' => $container['container_wt'],//自重
                );
                ksort($containersRow);
                $containersRows[] = $containersRow;
            }
        }

        //查找随附单证
        $decLicenseDocus = [];
        $decLicenseRows = Service_DesMessageLicensedocu::getByCondition($condition);
        /*array(
            'DocuCode'=>$decRequestCert['docu_code'],
            'CertCode'=>$decRequestCert['cert_code']
        );*/

        //查找申请单证
        $decRequestCerts = [];
        $decRequestCertsRows = Service_DesMessageDecrequestcert::getByCondition($condition);
        if (!empty($decRequestCertsRows)) {
            foreach ($decRequestCertsRows as $k => $decRequestCert) {
                $decRequestCertRow = array(
                    'AppCertCode' => $decRequestCert['docu_code'],
                    'ApplOri' => $decRequestCert['cert_code'],
                    'ApplCopyQuan' => '',
                );
                ksort($decRequestCertRow);
                $decRequestCerts[] = $decRequestCertRow;
            }
        }

        //DecRequestCerts

        //其它包装信息(模板没有暂时留空)
        $decOtherPacks = [];
        /*array(
            'PackQty'=>'1',
            'PackType'=>'99'
        ),*/
        //企业资质信息表(模板没有暂时留空)
        $decCopLimits = [];
        /*array(
            'EntQualifNo'=>'',//企业资质编号
            'EntQualifTypeCode'=>'',//企业资质类别代码
        )*/
        //使用人信息表(模板没有暂时留空)
        $decUsers = [];
        /*'DecUsers'=>array(
            'DecUser'=>array(
                array(
                    'UseOrgPersonCode'=>'水电费',//使用单位联系人
                    'UseOrgPersonTel'=>'15602947243',//使用单位联系电话
                ),
            )
        ),*/
        //标记号码附件表(模板没有暂时留空)
        $decMarkLobs = [];
        //标记号码附件表
        /*'DecMarkLobs'=>array(//标记号码附件表
            'DecMarkLob'=>array(
                array(
                    'AttachName'=>'附件名称',
                    'AttachType'=>'c',
                    'Attachment'=>'AAECAwQFBgcICQoLDA0ODw==',
                )
            )
        ),*/
        //报关单自由文本信息
        //$decFreeTxt = [];
        $decFreeTxt = array(
            array(
                'RelId' => '',
                'RelManNo' => '',
                'BonNo' => '',
                'VoyNo' => '',
                'DecBpNo' => '',
                'CusFie' => '',
                'DecNo' => '',
            )
        );
        list($usec, $sec) = explode(' ', microtime());
        $str = date("YmdHis", $sec);
        $sindata = $str . str_pad(floor($usec * 100), '2', '0', STR_PAD_LEFT);


        $data = array(
            'DecHead' => $DecHead,
            'DecLists' => array(
                'DecList' => $listData,
            ),
            'DecSign' => array(
                'ICCode' => '',
                'CopCode' => '',
                'OperName' => '',
                'OperType' => 'G',
                'ClientSeqNo' => $desHead['dmh_no'],
                'SignDate' => $sindata,
                'Sign' => '',
                'Certificate' => '',
                'HostId' => '',
                'BillSeqNo' => '',
                'DomainId' => '',
                'Note' => '',
            ),
            /*'EdocRealation'=>array(//电子随附单据信息
                array(
                    'EdocID'=>'测试5220保税核注清单IM123456789123456789',
                    'EdocCode'=>'1',
                    'EdocFomatType'=>'',
                    'OpNote'=>'',
                    'EdocCopId'=>'',
                    'EdocOwnerCode'=>'',
                    'SignUnit'=>'',
                    'SignTime'=>date("YmdHis"),
                    'EdocOwnerName'=>'',
                    'EdocSize'=>'',
                    ),

            )*/
        );
        if (!empty($containersRows)) {
            $data['DecContainers']['Container'] = $containersRows;
        }
        //随附单证
        if (!empty($decLicenseDocus)) {
            $data['DecLicenseDocus']['LicenseDocu'] = $decLicenseDocus;
        }
        //申请单证
        if (!empty($decRequestCerts)) {
            $data['DecRequestCerts']['DecRequestCert'] = $decRequestCerts;
        }
        //其它包装信息
        if (!empty($decOtherPacks)) {
            $data['DecOtherPacks']['DecOtherPack'] = $decOtherPacks;
        }
        //企业资质信息表
        if (!empty($decCopLimits)) {
            $data['DecCopLimits']['DecCopLimit'] = $decCopLimits;
        }
        //使用人信息表
        if (!empty($decUsers)) {
            $data['DecUsers']['DecUser'] = $decUsers;
        }
        //标记号码附件表
        if (!empty($decMarkLobs)) {
            $data['DecMarkLobs']['DecMarkLob'] = $decMarkLobs;
        }
        //报关单自由文本信息
        if (!empty($decFreeTxt)) {
            $data['DecFreeTxt'] = $decFreeTxt;
        }
        /*echo "<pre>";
        print_r($data);
        exit;*/
        return $data;
    }

    /**
     * Note:生成xml
     * User: Yao
     * Date: 2019/12/24
     * Time: 13:35
     * @param $data
     */
    protected function toXml($data)
    {
        $xml = Common_ArrayToXml::convert($data, array(
            'rootElementName' => 'DecMessage',
            '_attributes' => array(
                'xmlns' => 'http://www.chinaport.gov.cn/dec',
                'Version' => '4.8'
            ),

        ),
            true,
            'UTF-8',
            '1.0',
            [
                'formatOutput' => true,
                'encoding' => 'UTF-8'
            ]
        );
        return $xml;
    }

    /**
     * @todo 获取file的名称
     */
    public function getFile()
    {
        return $this->file;
    }

    /**
     * @todo 报关单发送
     */
    public function sendbaoguandan($id)
    {
        $return = array(
            'state' => 0,
            'message' => 'faise',
        );
        try {
            $xml = $this->getXmlById($id);

            $path = APPLICATION_PATH . '/../data/baoguan/baoguandan/' . date('Ymd') . '/';
            if (!is_dir($path)) {
                mkdir($path, 0777, true);
            }
            $name = "baoguandan." . time() . "." . $id . ".xml";
            file_put_contents($path . $name, $xml);

            $company_code = "ZH-WXT"; //默认一个公司
            $res = [];
            if ($this->desHead['bpedbh_id'] > 0) {
                $bgpdh = Service_BgPriEntryDataDetailBodyHead::getByField($this->desHead['bpedbh_id'], 'bpedbh_id');
                if (!empty($bgpdh)) {
                    $bgpreData = Service_BgPriEntryData::getByField($bgpdh['bped_id'], 'bped_id');
                    if (!empty($bgpreData)) {
                        $company_code = $bgpreData['company_code'];
                    }
                }
            }
            if ($company_code != '') {
                $bgCompany = Service_BgCompany::getByField($company_code, 'company_code');
                if (!empty($bgCompany)) {
                    $resourceRow = json_decode($bgCompany['config_value'], true);
                    if (!empty($resourceRow)) {
                        $res = $resourceRow['baoguan']['send'];
                    }
                }
            }


            $aMessage['fmt_code'] = 'baoguandan';
            $aMessage['fmt_type'] = 'baoguandan';
            $aMessage['refercence_no'] = $this->desHead['dmh_no'];
            $aMessage['fml_status'] = 2;
            $aMessage['fml_add_time'] = date('Y-m-d H:i:s');
            $aMessage['company_code'] = $company_code;
            $aMessage['fml_path'] = $path. $name;
            Service_FtpMessageSendlist::add($aMessage);

            $sendApi = new Baoguandan($res);
            $result = $sendApi->send($path . $name);
            if(!$result){
                throw new Exception("发送文件到单一失败");
            }
            $return['state'] = 1;
            $return['message'] = "发送成功";
            $this->result = $return;
            return true;
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
            $this->result = $return;
            return false;
        }
//        $filename = $path."/".$id."_".date("ymdhis",time()).".xml";
//        file_put_contents($filename,$xml);
//        $sendinfo = $this->getSendConfig();
//        //var_dump($sendinfo);
//        $config = $sendinfo['config'];
//        $param['host'] = $config['host'];
//        $param['port'] = $config['port'];
//        $param['tube'] = $config['tube'];
//        $obj = new Service_Pheanstalk($param);
//        $sendName = basename($filename);
//        $message = file_get_contents($filename);
//        $this->file = $filename;
//        if ($obj->putMessage($message, $sendName)) {
//            $result = true;
//        } else {
//            $result = false;
//        }
        return $result;
    }

    public function getResult()
    {
        return $this->result;
    }

    /**
     * @todo 报关单接收回执
     */
    public function receivingbaoguandan()
    {
        return true;
        $dir = $path = APPLICATION_PATH . "/../data/baoguandanreceive/";
        $path = $path . date("Y/m", time());
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
        }
        $sendinfo = $this->getFentchConfig();
        $config = $sendinfo['config'];
        $param['host'] = $config['host'];
        $param['port'] = $config['port'];
        $param['tube'] = $config['tube'];
        //print_r($param);
        //exit;
        $stalk = new Pheanstalk($param['host'], $param['port']);
        //$stalk = new Service_Pheanstalk($param);
        //var_dump($stalk);
        //exit;
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        $moveDir = APPLICATION_PATH . '/../data/baoguandanreceive-tmp/';
        if (!is_dir($moveDir)) {
            mkdir($moveDir, 0777, true);
        }
        try {
            $number = 5000;
            while ($number > 0) {
                $tube = $param['tube'];
                //$tube = 'baoguandanfetch';
                $job = $stalk->watchOnly($tube)->reserve(4);
                if (!$job) {
                    return false;
                }
                //echo "<pre>";
                $xml = $job->getData();
                //var_dump($data);
                //exit;
                //$xml = json_decode($data,true);
                //$filename = $data['name'];
                //$xml = $data['xml'];
                $filename = time() . uniqid() . rand(1000, 9999) . '.xml';

                if ($xml != '' && $filename != '') {
                    $localFile = $dir . $filename;
                    if (file_put_contents($localFile, $xml, FILE_APPEND)) {
                        rename($localFile, $moveDir . basename($localFile));
                        $stalk->delete($job);
                    };
                }
                $number--;
            }
        } catch (Exception $exception) {
            echo $exception->getMessage() . "\n";
            return false;
        }
    }

    /**
     * @todo 报关单解析回执
     */
    public function parsebaoguandan()
    {
        $fetchPath = $this->getFentchConfig();
        $root ='/home/ftp/zh';
        $receivePath = $root.$fetchPath['baoguan']['receive']['path'];
//        $receivePath = 'E:/ftp/zh_baoguan/send/';
//        $dir = APPLICATION_PATH . '/../data/baoguandanreceive-tmp/';
        $dir = $receivePath.'/';
        $moveDir = APPLICATION_PATH . '/../data/baoguandanreceive/' . date('Ymd') . '/';
        $moveErrorDir = APPLICATION_PATH . '/../data/baoguandanreceive-error/';
        if (!is_dir($moveErrorDir)) {
            mkdir($moveErrorDir, 0777, true);
        }
        if (!is_dir($moveDir)) {
            mkdir($moveDir, 0777, true);
        }
        $dirSource = opendir($dir);
        while ($baseName = readdir($dirSource)) {
            if ($baseName != '.' && $baseName != '..' && !is_dir($dir . $baseName)) {
                $db = Common_Common::getAdapter();
                $localFile = $dir . $baseName;
                $zsDirFile = $moveDir . $baseName;
//                echo $zsDirFile;
//                echo PHP_EOL;
//                die();
                $db->beginTransaction();
                try {
                    $parseObj = new Api_Des_Receiving();
                    $result = $parseObj->parsebaoguandanProcess($localFile);
                    var_dump($result);
                    if ($result !== true) {
                        throw new \Exception("报文无法解析" . var_export($result, true));
                    }
                    $db->commit();
                    rename($localFile, $zsDirFile);
                    //$db->rollBack();
                } catch (\Exception $e) {
//                    echo $e;
                    $db->rollBack();
                    $failPath = dirname($dir) . '/receivefailse/';
                    if (!file_exists($failPath)) {
                        mkdir($failPath, 0777, true);
                    }
                    $failName = pathinfo($baseName, PATHINFO_FILENAME) . '.error';
                    rename($localFile, $failPath . $baseName);
                    file_put_contents($failPath . $failName, $e->__toString());
                    //rename($zsDirFile,$moveErrorDir.$baseName);
                    echo $baseName;
                }
            }
        }
        closedir($dirSource);
    }

    /**
     * @todo 解析报关单
     */
    public function parsebaoguandanProcess($zsDirFile)
    {
        //$zsDirFile = "E:/mycode/kjqinguan/kjqinguan/trunk/data/baoguan-tmp/Failed_24_20211211003_2021121316144490707289.xml";
        $fileContent = file_get_contents($zsDirFile);
        $restArray = Common_Common::simpleXmlToArray($fileContent);
        if (!is_array($restArray)) {
            return '报文无法解析';
        }
        //exit;
        if (isset($restArray['ResponseCode']) && isset($restArray['ErrorMessage']) && isset($restArray['ClientSeqNo'])) {
            $ClientSeqNo = $restArray['ClientSeqNo'];
            if(empty($ClientSeqNo)){
                return "报关单号为空";
            }
            $dmhInfo = Service_DesMessageHead::getByField($ClientSeqNo, 'dmh_no');
            //var_dump($dmhInfo);
            //exit;
            if (empty($dmhInfo)) {
                return '找不到对应报关单信息';
            }
            $state_to = 1;
            //写日志
            if ($restArray['ResponseCode'] == '0') {
                //接收成功
                $desRow = array(
                    'seq_no' => $restArray['SeqNo'],
                    'des_status' => 2,
                    'update_time' => date("Y-m-d H:i:s", time())
                );
                Service_DesMessageHead::update($desRow, $dmhInfo['dmh_id'], 'dmh_id');
                $state_to = 2;
            }
            //写日志
            $dmhLog = array(
                'note' => "接收报关单回执:" . $fileContent,
                'add_time' => date("Y-m-d H:i:s", time()),
                'dmh_id' => $dmhInfo['dmh_id'],
                'state_from' => $dmhInfo['des_status'],
                'state_to' => $state_to,
                'user_id' => 0,
                'type' => '2',
                'file_path' => $zsDirFile
            );
            Service_DesMesssageLog::add($dmhLog);
            return true;
        }
        if(isset($restArray['CUS_CIQ_NO']) && !empty($restArray['CUS_CIQ_NO'])){
            var_dump($restArray['CUS_CIQ_NO']);
            die();
            $dmhInfo = Service_DesMessageHead::getByField($restArray['CUS_CIQ_NO'], 'seq_no');
            if (empty($dmhInfo)) {
                return '找不到对应报关单信息';
            }
            $dmhLog = array(
                'note' => "接收报关单回执:" . $fileContent,
                'add_time' => date("Y-m-d H:i:s", time()),
                'dmh_id' => $dmhInfo['dmh_id'],
                'state_from' => $dmhInfo['des_status'],
                'state_to' => $dmhInfo['des_status'],
                'user_id' => 0,
                'type' => '2',
                'file_path' => $zsDirFile
            );
            Service_DesMesssageLog::add($dmhLog);
            return true;

        }
        return false;
    }

}