<?php

/**
 * Created by PhpStorm.
 * User: boyer
 * Date: 2020/8/24
 * Time: 11:51
 */
class Api_Inv_Send
{
    // public $invUrl = 'https://zbq.dgeport.cn/REST/INV101';
    public $invUrl = '';
    protected $companyHsCode = '';
    protected $wsdlUrl = '';
    protected $responseToken = '';
    public function send($xml) {
        $return = [
            'state' => 0,
            'message' => 'fail'
        ];
        try {
            $data = [
                'userId' => '',
                'userPwd' => '',
                'platId' => '',
                'companyId' => $this->companyHsCode,
                'messageID' => $this->getMessageId(),
                'msgType' => 'INV101',
                'format' => 'xml',
                'compress' => '0',
                'signature' => '',
                'data' => $xml
            ];
            $result = Common_Common::http_requestPost($this->invUrl,'60',[
                'Content-type:application/json'
            ],json_encode($data));
            // $adpter = new Zend_Http_Client_Adapter_Curl();
            // $adpter->setCurlOption([
            //      CURLOPT_SSL_VERIFYPEER => false,
            //      CURLOPT_SSL_VERIFYHOST => false,
            // ]);
            // $client = new Zend_Http_Client();
            // $client->setAdapter($adpter);
            // $client->setUri($this->invUrl);
            // $client->setMethod(Zend_Http_Client::POST);
            // $client->setConfig([
            //     'maxredirects' => 9,
            //     'timeout' => 60,
            // ]);
            // $client->setRawData(json_encode($data));
            // $response = $client->request();
            // $result = $response->getBody();
            $resJosn = json_decode($result, true);
            $return['message'] = $resJosn['retData'];
            if ($resJosn['resultFlag'] == 1) {
                $return['state'] = 1;
            } else {
                throw new Exception($result);
            }
        } catch (Exception $e) {
            $return['message'] = $e->getMessage();
        }
        return $return;
    }

    protected function getMessageId() {
        $cpCode = preg_replace("/[A-Z]/", '0', $this->companyHsCode);
        $cpCode .= date("YmdHis");
        $timeList = explode(" ", microtime());
        $cpCode .= mt_rand(1, 9) . substr($timeList[1], 4) . substr($timeList[0], 3, 5);
        return $cpCode;
    }

    /**
     * Note:获取综保系统回执
     * User: Yao
     * Date: 2020/11/30
     * Time: 20:59
     * @return array|mixed
     */
    public function getResponse() {
        $soapClient = new SoapClient($this->wsdlUrl, [
            'trace' => true,
            'cache' => true
        ]);
        try {
            $postParams = [
                'token' => $this->responseToken,
            ];
            $res = $soapClient->list($postParams);
            return $res;
        } catch (SoapFault $e) {
            echo $e;
        }
        return [];
    }

    /**
     * Note:解析核注清单报文回执，
     * User: Yao
     * Date: 2020/11/30
     * Time: 20:59
     */
    public function parseInv201($data, $filePath) {
        $bussinessData = $data['DataInfo']['BussinessData'];
        $hdeApprResult = $bussinessData['INV201']['HdeApprResult'];
        $seqNo = $hdeApprResult['etpsPreentNo'];
        $invNo = $bussinessData['INV201']['BondInvtBsc']['etpsInnerInvtNo'];
        if (empty($seqNo)) {
            throw new Exception('报文格式错误，统一编号为空');
        }
        $invtList = Service_InvtList::getByField($seqNo, 'SeqNo');
        if (empty($invtList)) {
            if($invNo){
                $invtList = Service_InvtList::getByField($invNo, 'EtpsInnerInvtNo');
            }
        }
        if(empty($invtList)){
            throw new Exception('找不到对应的核注清单');
        }
        $zbStatus = Service_InvtList::getZbStatus();
        $typeCd = $hdeApprResult['typecd'];
        //typecd INV201: 1.清单审批 2.清单修改 3. 清单删除 4. 清单同步
        //manageResult INV201: 1-通过（已核扣）2-转人工3-退单4-预核扣5-通过（未核扣）Y-入库成功Z-入库失败,只有当业务类型为[1.清单审批]时，该字段有效，其他业务类型时该字段为空
        if($typeCd ==1) {
            $hdeApprResultStatus = $hdeApprResult['manageResult'];
            $log = [
                'il_id' => $invtList['il_id'],
                'note' => '综保回执：' . $zbStatus[$hdeApprResultStatus],
                'add_time' => date("Y-m-d H:i:s"),
                'status_from' => $invtList['status'],
                'status_to' => $invtList['status'],
                'file_path' => $filePath,
            ];
        }elseif($typeCd ==3){//清单删除
            $log = [
                'il_id' => $invtList['il_id'],
                'note' => '综保回执：' .$bussinessData['INV201']['CheckInfo']['note'],
                'add_time' => date("Y-m-d H:i:s"),
                'status_from' => $invtList['status'],
                'status_to' => $invtList['status'],
                'file_path' => $filePath,
            ];
            Service_InvtListLog::add($log);
            $invProcess = new Process_Inv();
            return $invProcess->concel($invtList);
        }else{
            $hdeApprResultStatus=0;
            $log = [
                'il_id' => $invtList['il_id'],
                'note' => '综保回执：未知类型' ,
                'add_time' => date("Y-m-d H:i:s"),
                'status_from' => $invtList['status'],
                'status_to' => $invtList['status'],
                'file_path' => $filePath,
            ];
        }
        Service_InvtListLog::add($log);
        if ($invtList['zb_status'] != 1) {
            if($invtList['zb_status'] !=4 &&$invtList['zb_status'] !=5){
                Service_InvtList::update([
                    'zb_status' => $hdeApprResultStatus
                ], $invtList['il_id']);
            }elseif($hdeApprResultStatus ==1){
                Service_InvtList::update([
                    'zb_status' => $hdeApprResultStatus
                ], $invtList['il_id']);
            }
        }
        $zongbaoHead = $bussinessData['INV201']['BondInvtBsc'];
        if (isset($zongbaoHead['bondInvtNo']) || isset($zongbaoHead['rltInvtNo'])) {
            Service_InvtList::update([
                'BondInvtNo' => $zongbaoHead['bondInvtNo'],
                'RltInvtNo' => empty($zongbaoHead['rltInvtNo']) ? '' : $zongbaoHead['rltInvtNo']
            ], $invtList['il_id']);
            $editInfo['header'] = [
                'BondInvtNo_pre' => $invtList['BondInvtNo'],
                'RltInvtNo_pre' => $invtList['RltInvtNo'],
                'BondInvtNo' => $zongbaoHead['bondInvtNo'],
                'RltInvtNo' => empty($zongbaoHead['rltInvtNo']) ? '' : $zongbaoHead['rltInvtNo']
            ];
            $log = [
                'il_id' => $invtList['il_id'],
                'note' => '回执解析：更新核注清单海关编号',
                'add_time' => date("Y-m-d H:i:s"),
                'status_from' => $invtList['status'],
                'status_to' => $invtList['status'],
                'edite_info' => json_encode($editInfo),
            ];
            Service_InvtListLog::add($log);
        }
        if ($hdeApprResultStatus == '1') {
            if($invtList['status'] == 4){
                return true;
            }
            $invProcess = new Process_Inv();
            //出口BBC

            if ($invtList['ImpexpMarkcd'] == 'E' && $invtList['InvtType'] == '8') {

                $invProcess->complete($invtList);
            } else {
                $invtListBody = Service_InvtListBody::getByCondition([
                    'il_id' => $invtList['il_id'],
                    'PutrecSeqnoEmpty' => true
                ]);
                if (!empty($invtListBody)) {
                    // $editInfo =[];
                    $zongbaoHead = $bussinessData['INV201']['BondInvtBsc'];
                    // Service_InvtList::update([
                    //     'BondInvtNo'=>$zongbaoHead['bondInvtNo'],
                    //     'RltInvtNo'=>$zongbaoHead['rltInvtNo']
                    // ],$invtList['il_id']);
                    // $editInfo['header'] = [
                    //     'BondInvtNo_pre'=>$invtList['BondInvtNo'],
                    //     'RltInvtNo_pre'=>$invtList['RltInvtNo'],
                    //     'BondInvtNo'=>$zongbaoHead['bondInvtNo'],
                    //     'RltInvtNo'=>$zongbaoHead['rltInvtNo']
                    // ];
                    // $log = [
                    //     'il_id' => $invtList['il_id'],
                    //     'note' => '核注清单完成，反填序号',
                    //     'add_time' => date("Y-m-d H:i:s"),
                    //     'status_from' => $invtList['status'],
                    //     'status_to' => $invtList['status'],
                    //     'edite_info'=>json_encode($editInfo),
                    // ];
                    // Service_InvtListLog::add($log);
                    $headInfo = [
                        'il_id' => $invtList['il_id'],
                        'bound_invt_no' => $zongbaoHead['bondInvtNo'],
                        'dcl_typecd' => $invtList['DclTypecd'],
                        'bizop_etps_no' => $invtList['BizopEtpsno'],//经营企业编号
                        'bizop_etps_nm' => $invtList['BizopEtpsNm'],//经营企业名称
                        'bizop_etps_sccd' => $invtList['BizopEtpsSccd'],//经营企业社会信用代码
                        // 'DclEtpsSccd'=>$invtList['dcl_etps_sccd'],//申报企业社会信用代码
                        'supv_modecd' => $invtList['SupvModecd'],//监管方式代码
                        'trsp_modecd' => $invtList['TrspModecd'],
                        'dclcus_flag' => $invtList['DclcusFlag'],
                        'stship_trsarv_natcd' => $invtList['StshipTrsarvNatcd'],//起运抵运国
                        'mtpck_endprd_markcd' => $invtList['MtpckEndprdMarkcd'],
                        'impexp_markcd' => $invtList['ImpexpMarkcd'],
                        'impexp_portcd' => $invtList['ImpexpPortcd'],
                        'gen_dec_flag' => $invtList['GenDecFlag'],
                        'bwl_type' => $invtList['bwl_type'],
                        'invt_type' => $invtList['InvtType'],
                        'bwl_no' => $invtList['bwl_no'],
                        'remark' => $invtList['Rmk'],
                        'rcvgd_etps_no' => $invtList['RcvgdEtpsno'],//固定 企业海关代码 收发货企业信息
                        'rvsngd_etps_sccd' => $invtList['RvsngdEtpsSccd'],//固定企业信用代码
                        'rcvgd_etps_nm' => $invtList['RcvgdEtpsNm'],//企业中文名称
                        'rlt_invt_no' => $zongbaoHead['rltInvtNo'] ?: '',//关联清单编号
                        'rlt_putrec_no' => $invtList['RltPutrecNo'],//关联账册备案编号
                        'rlt_entry_no' => $invtList['RltEntryNo'] ?: '',//关联报关单编号
                    ];
                    $bodyResult = $bussinessData['INV201']['BondInvtDt'];
                    if (!isset($bodyResult[0])) {
                        $bodyResult = [$bodyResult];
                    }
                    $invRefillBody = [];
                    foreach ($bodyResult as $rbody) {
                        $invRefillBody[] = [
                            'gds_seqno' => $rbody['gdsSeqno'],
                            'putrec_seqno' => empty($rbody['putrecSeqno']) ? '' : $rbody['putrecSeqno'],
                            'gds_mtno' => $rbody['gdsMtno'],
                            'gdecd' => $rbody['gdecd'],
                            'gds_nm' => $rbody['gdsNm'],
                            'gds_spcf_model_desc' => $rbody['gdsSpcfModelDesc'],
                            'dcl_unitcd' => $rbody['dclUnitcd'],
                            'lawf_unitcd' => $rbody['lawfUnitcd'],
                            'secd_lawf_unitcd' => $rbody['secdLawfUnitcd'],
                            'natcd' => $rbody['natcd'],
                            'dcl_uprc_amt' => $rbody['dclUprcAmt'],
                            'dcl_total_amt' => $rbody['dclTotalAmt'],
                            'usd_stat_total_amt' => $rbody['usdStatTotalAmt'],
                            'dcl_currcd' => $rbody['dclCurrcd'],
                            'lawf_qty' => $rbody['lawfQty'],
                            'secd_lawf_qty' => $rbody['secdLawfQty']?:'',
                            'wt_sf_val' => $rbody['wtSfVal']?:'',
                            'fst_sf_val' => $rbody['fstSfVal']?:'',
                            'secd_sf_val' => $rbody['secdSfVal']?:'',
                            'dcl_qty' => $rbody['dclQty'],
                            'gross_wt' => $rbody['grossWt']?:'',
                            'net_wt' => $rbody['netWt']?:'',
                            // 'use_cd' => $rbody['use_cd'],
                            'lvyrlf_modecd' => $rbody['lvyrlfModecd'],
                            'ucns_verno' => $rbody['ucnsVerno']?:'',
                            'entry_gds_seqno' => $rbody['entryGdsSeqno'],
                            // 'ClyMarkcd'=>$rbody['cly_markcd'],
                            'apply_tb_seqno' => $rbody['applyTbSeqno']?:'',
                            'destination_natcd' => $rbody['destinationNatcd'],
                            'ModfMarkcd' => $rbody['modfMarkcd'],
                            'Rmk' => $rbody['rmk']?:'',
                        ];
                    }
                    $invProcess->reFillRecodeNo($headInfo, $invRefillBody);
                }
                $invProcess->complete($invtList);
            }
        }
    }

    /**
     * Note:211核注,清单记账回执
     * User: Yao
     * Date: 2021/1/26
     * Time: 13:33
     * @param $data
     * @param $filePath
     * @throws Exception
     */
    public function parseInv211($data, $filePath) {
        $bussinessData = $data['DataInfo']['BussinessData'];
        $hdeApprResult = $bussinessData['INV211']['BondInvtBsc'];
        $seqNo = $hdeApprResult['invtPreentNo'];
        if (empty($seqNo)) {
            throw new Exception('报文格式错误，统一编号为空');
        }
        $invtNo = $hdeApprResult['etpsInnerInvtNo'];
        $invtList = Service_InvtList::getByField($seqNo, 'SeqNo');
        if (empty($invtList)) {
            if($invtNo){
                $invtList = Service_InvtList::getByField($invtNo,'EtpsInnerInvtNo');
            }
        }
        if(empty($invtList)){
            throw new Exception('对应核注清单信息不存在');
        }
        $log = [
            'il_id' => $invtList['il_id'],
            'note' => '综保回执：INV211',
            'add_time' => date("Y-m-d H:i:s"),
            'status_from' => $invtList['status'],
            'status_to' => $invtList['status'],
            'operater'=>Service_User::getUserId(),
            'file_path' => $filePath,
        ];
        Service_InvtListLog::add($log);
        if($invtList['status'] ==4){//手动完成的只添加个记录
            return true;
        }
        if ($invtList['status'] != '2') {
            throw new Exception("核注清单不是确认状态");
        }
        $zongbaoHead = $bussinessData['INV211']['BondInvtBsc'];
        if (isset($zongbaoHead['bondInvtNo']) && $zongbaoHead['bondInvtNo']!='' ) {
            Service_InvtList::update([
                'BondInvtNo' => $zongbaoHead['bondInvtNo'],
                //'RltInvtNo' => empty($zongbaoHead['rltInvtNo']) ? '' : $zongbaoHead['rltInvtNo']
            ], $invtList['il_id']);
            $editInfo['header'] = [
                'BondInvtNo_pre' => $invtList['BondInvtNo'],
                'RltInvtNo_pre' => $invtList['RltInvtNo'],
                'BondInvtNo' => $zongbaoHead['bondInvtNo'],
                'RltInvtNo' => empty($zongbaoHead['rltInvtNo']) ? '' : $zongbaoHead['rltInvtNo']
            ];
            $log = [
                'il_id' => $invtList['il_id'],
                'note' => '回执解析INV211：更新核注清单海关编号',
                'add_time' => date("Y-m-d H:i:s"),
                'status_from' => $invtList['status'],
                'status_to' => $invtList['status'],
                'edite_info' => json_encode($editInfo),
            ];
            Service_InvtListLog::add($log);
        }else{
            throw new Exception('核注清单号不存在或者为空');
        }
        $invtListBody = Service_InvtListBody::getByCondition([
            'il_id' => $invtList['il_id'],
            'PutrecSeqnoEmpty' => true
        ]);
        /*var_dump($invtListBody);
        exit;*/
        if (empty($invtListBody)) {
            throw new Exception('核注清单表体数据备案序号完整');
        }

        $bodyResult = $bussinessData['INV211']['BwsDt'];
        if (!isset($bodyResult[0])) {
            $bodyResult = [$bodyResult];
        }
        $invRefillBody = [];
        $editInfo = [];
        foreach ($bodyResult as $rbody) {
            //var_dump($rbody);
            $invtListBody = Service_InvtListBody::getByCondition([
                'il_id' => $invtList['il_id'],
                'GdsSeqno' => $rbody['invtGNo'],
                'GdsMtno' => $rbody['gdsMtno']
            ]);
            /*var_dump($invtListBody);
            exit;*/
            if(count($invtListBody)>1){
                throw new Exception("备案序号不唯一".$rbody['invtGNo'].'-->'.$rbody['gdsMtno']);
            }
            if ($invtListBody) {
                $invtListBody = $invtListBody[0];
                $editInfo['body'][] = [
                    'PutrecSeqno' => $rbody['gdsSeqno'],
                    'PutrecSeqno_pre' => $invtListBody['PutrecSeqno']
                ];
                $update = [
                    'PutrecSeqno' => $rbody['gdsSeqno']
                ];
                //var_dump($invtListBody['ilb_id']);
                Service_InvtListBody::update($update, $invtListBody['ilb_id']);
            }else{
                throw new Exception("核注表体数据错误".$rbody['invtGNo'].'-->'.$rbody['gdsMtno']);
            }
        }
        $log = [
            'il_id' => $invtList['il_id'],
            'note' => 'INV211反填备案序号',
            'add_time' => date("Y-m-d H:i:s"),
            'status_from' => $invtList['status'],
            'status_to' => $invtList['status'],
            'edite_info' => json_encode($editInfo),
            'operater' => Service_User::getUserId()
        ];
        Service_InvtListLog::add($log);
    }

    /**
     * Note:common响应
     * User: Yao
     * Date: 2020/12/2
     * Time: 17:52
     * @param $data
     * @param $filePath
     */
    public function parseCommonResponse($data, $filePath) {
        $conmmonResponse = $data;
        $invtNo = $conmmonResponse['EtpsPreentNo'];
        if (empty($invtNo)) {
            throw new Exception('报文格式错误，核注清单编号为空');
        }
        $invtList = Service_InvtList::getByField($invtNo, 'EtpsInnerInvtNo');
        if (empty($invtList)) {
            throw new Exception('核注清单编号不存在');
        }
        $seqNo = $conmmonResponse['SeqNo'];
        Service_InvtList::update([
            'SeqNo' => $seqNo
        ], $invtList['il_id']);
        $editInfo = [
            'header' => [
                'SeqNo' => $seqNo,
                'SeqNo_pre' => $invtList['SeqNo']
            ]
        ];
        $log = [
            'il_id' => $invtList['il_id'],
            'note' => '综保回执：' . $conmmonResponse['CheckInfo'],
            'add_time' => date("Y-m-d H:i:s"),
            'status_from' => $invtList['status'],
            'status_to' => $invtList['status'],
            'edite_info' => json_encode($editInfo),
            'file_path' => $filePath,
        ];
        Service_InvtListLog::add($log);
    }

    /**
     * Note:无关紧要回执记录日志
     * User: Yao
     * Date: 2020/12/3
     * Time: 9:39
     * @param $conment
     * @param $filePath
     * @param $seq
     * @throws Exception
     */
    public function invtResponseLog($conment, $filePath, $seq) {
        $invtList = Service_InvtList::getByField($seq, 'SeqNo');
        if (empty($invtList)) {
            throw new Exception('统一编号为空');
        }
        $log = [
            'il_id' => $invtList['il_id'],
            'note' => '综保回执：' . $conment,
            'add_time' => date("Y-m-d H:i:s"),
            'status_from' => $invtList['status'],
            'status_to' => $invtList['status'],
            'file_path' => $filePath,
        ];
        Service_InvtListLog::add($log);
    }


}