<?php
/**
 * @todo 根据预录入数据生成报关单数据
 */
class Api_Pre_PreDataToBaoguanProcess{
    protected $bg_pri_entry_data;
    protected $bg_pri_entry_data_detail_body_head;
    protected $bg_pri_entry_data_detail_body_containers;
    protected $bg_pri_entry_data_detail_body_detail;
    protected $bg_pri_entry_data_detail_body_licensedocu;
    protected $id; //业务主键id 根据bg_pri_entry_data_detail_body_head表的主键bpedbh_id
    protected $error;
    protected $dmhId;

    protected $countRow; //计算的属性

    protected $baseinfo; //基本信息
    protected $containerList;//集装箱信息
    protected $limitType; //报关单许可证
    protected $cert; //申请单证
    protected $goodsLimitVin; //报关单许可证Vin
    protected $licensedo; //随附单证
    protected $messageDecfreetxt; //报关单自有文本

    public function __construct($id){
        $this->id = $id;
    }
    /**
     * @todo 获取基础信息
     */
    protected function getBaseInfo(){
        $id = $this->id;
        try{
            $bg_pri_entry_data_detail_body_head =  Service_BgPriEntryDataDetailBodyHead::getByField($id,'bpedbh_id');
            $note = "";
            $amount = 0;
            if(!empty($bg_pri_entry_data_detail_body_head)){
                $this->bg_pri_entry_data_detail_body_head=$bg_pri_entry_data_detail_body_head;
                $bg_pri_entry_data = Service_BgPriEntryData::getByField($this->bg_pri_entry_data_detail_body_head['bped_id'],'bped_id');
                $this->bg_pri_entry_data = $bg_pri_entry_data;
                $condition = array(
                    'bpedbh_id'=>$id,
                );
                $bg_pri_entry_data_detail_body_detail = Service_BgPriEntryDataDetailBodyDetail::getByCondition($condition,'*');
                $this->bg_pri_entry_data_detail_body_detail = $bg_pri_entry_data_detail_body_detail;
                $bg_pri_entry_data_detail_body_containers = Service_BgPriEntryDataDetailBodyContainers::getByCondition($condition,'*');
                $this->bg_pri_entry_data_detail_body_containers = $bg_pri_entry_data_detail_body_containers;
                $bg_pri_entry_data_detail_body_licensedocu = Service_BgPriEntryDataDetailBodyLicensedocu::getByCondition($condition,'*');
                $this->bg_pri_entry_data_detail_body_licensedocu = $bg_pri_entry_data_detail_body_licensedocu;
                $note.="子单号：".$bg_pri_entry_data_detail_body_head['bpd_ref_no'].",";
                $note.="拼数：".$bg_pri_entry_data_detail_body_head['num'].",";

                $this->getCountRow();
                $countRow = $this->countRow;
                //print_r($countRow);
                $type = "";
                if(isset($countRow['bg_type'])){
                    $type = $countRow['bg_type'];
                }
                /**
                 * 前两位：一般报关单填空值；
                ML：保税区进出境备案清单
                SD: “属地申报，口岸验放”报关单
                LY：两单一审备案清单
                CL：汇总征税报关单
                SS:“属地申报，属地验放”报关单
                ZB：自主报税
                SW：税单无纸化
                SZ：水运中转普通报关单
                SM：水运中转保税区进出境备案清单
                SL：水运中转两单一审备案清单
                Z：自报自缴
                MF：公路舱单跨境快速通关报关单
                MK: 公路舱单跨境快速通关备案清单
                ZY：自报自缴，两单一审备案清单
                ZC：自报自缴，汇总征税报关单
                ZW：自报自缴，税单无纸化
                ZF：自报自缴，公路舱单跨境快速通关
                ZX：自报自缴，多项式联运
                MT：多项式联运
                TT：纳税期限报关单
                IT：分期纳税报关单
                ZT：自报自缴，纳税期限报关单
                ZI：自报自缴，分期纳税报关单
                EX：低值快速货物报关单
                EC：低值快速货物汇总征税报关单
                EZ：低值快速货物自报自缴报关单；
                ES：低值快速货物汇总征税、自报自缴报关单
                第三位：
                0/空：整合申报一次录入
                1：概要申报
                2：完整申报
                3：两步申报一次录入，人工提交。如之前进行过辅助提交，该值表示取消辅助提交且调整为人工提交
                4：两步申报一次录入，辅助提交
                第四位：涉证标记0-否，1-是，概要申报必传
                第五位：涉检标记0-否，1-是，概要申报必传
                第六位：涉税标记0-否，1-是，概要申报必传
                 */



                $baseinfohead = array(
                    'ieflag'=>$bg_pri_entry_data_detail_body_head['ie_flag'],
                    'type'=>$type, //报关单类型
                    'iedate'=>date("Ymd",time()), //进出日期为生成的日期
                    'overseas_consignor_code'=>'',
                    'owner_code'=>$bg_pri_entry_data_detail_body_head['owner_code'],//消费使用/生产销售单位代码
                    'traf_mode'=>$bg_pri_entry_data_detail_body_head['traf_mode'], //运输方式代码
                    'bill_no'=>$bg_pri_entry_data_detail_body_head['bill_no'],//提单号
                    'license_no'=>'', //许可证编号--预录入数据没有
                    //'fee_mark'=>'', //运费标记
                    //'insur_mark'=>'', //保险费标记
                    //'other_mark'=>'', //杂费标志
                    'pack_no'=>$bg_pri_entry_data_detail_body_head['pack_no'], //件数
                    'trade_area_code'=>$bg_pri_entry_data_detail_body_head['trade_area_code'], //贸易国别
                    'entry_type'=>$countRow['entry_type'], //0普通报关单，L为带报关单清单的报关单，W无纸报关类型，D既是清单又是无纸报关的情况，M：无纸化通关
                    'org_code'=>'', //检验检疫受理机关---
                    'purp_org_code'=>'', //目的地检验检疫机关---
                    'spec_decl_flag_gjss'=>'0', //特种业务标识---
                    'spec_decl_flag_wj'=>'0', //1选中。第一位：“国际赛事”；第二位：“特殊进出军工物资”；第三位:“国际援助物资”；第四位：“国际会议”；第五位：“直通放行”；第六位：“外交礼遇”；第七位：“转关
                    'custom_master'=>$bg_pri_entry_data_detail_body_head['declare_port'], //申报地海关
                    //'declare_port'=>$bg_pri_entry_data_detail_body_head['declare_port'], //申报口岸
                    'trade_code'=>$bg_pri_entry_data_detail_body_head['trade_co'], //境内收发货人编号
                    'overseas_consignor_ename'=>$bg_pri_entry_data_detail_body_head['overseas_consignor_ename']?$bg_pri_entry_data_detail_body_head['overseas_consignor_ename']:'', //
                    'owner_name'=>$bg_pri_entry_data_detail_body_head['owner_name'], //消费使用/生产销售单位单位名称
                    'traf_name'=>$bg_pri_entry_data_detail_body_head['traf_name'], //运输工具
                    'trade_mode'=>$bg_pri_entry_data_detail_body_head['trade_mode'], //贸易方式
                    'trade_country'=>$bg_pri_entry_data_detail_body_head['trade_country'], //启运国/运抵国
                    'fee_rate'=>'', //运费／率 ---
                    'insur_rate'=>'', //保险费／率 ---
                    'other_rate'=>'', //杂费／率 ---
                    'wrap_type'=>$bg_pri_entry_data_detail_body_head['wrap_type'], //包装种类
                    'goods_place'=>$countRow['goods_place'], //货物存放地点【报检时货物的存放地点】
                    //'trade_mode'=>$bg_pri_entry_data_detail_body_head['trade_mode'],
                    'mark_no'=>$countRow['mark_no'], //标记及号码
                    'vsa_org_code'=>'', //领证机关---
                    'correlation_no'=>'', //关联号码---
                    'spec_decl_flag_jg'=>'0', //特种业务标识 军工---
                    'spec_decl_flag_zg'=>'0', //特种业务标识 转关---
                    'spec_decl_flag_gjyz'=>'0',//特种业务标识 国际援助物资
                    'spec_decl_flag_gjhy'=>'0', //特种业务标识 国际会议
                    'spec_decl_flag_ztfx'=>'0', //特殊通过模式
                    'manual_no'=>$bg_pri_entry_data_detail_body_head['ems_no'], //备案号
                    'ieport'=>$bg_pri_entry_data_detail_body_head['ie_port'], //进出口岸
                    'trade_name'=>$bg_pri_entry_data_detail_body_head['trade_name'], //境内收发货人名称
                    'overseas_consignor_addr'=>'', //境外收发货人地址 ---
                    'owner_ciq_code'=>'', //消费使用/生产销售单位检验检疫编码---这个可能要有，预录入数据可能要加上待定
                    'cut_mode'=>$bg_pri_entry_data_detail_body_head['duty_mode'], //征免性质
                    'distinate_port'=>$bg_pri_entry_data_detail_body_head['destination_port'], //经停港/抵运港
                    'fee_curr'=>'', //运费币制 ---
                    'insur_curr'=>'', //保险费币制 ---
                    'other_curr'=>'', //杂费币制 ---
                    'gross_wet'=>$bg_pri_entry_data_detail_body_head['gross_wt'], //毛重
                    'desp_port_code'=>'', //启运港代码---这个系统没有
                    'note_s'=>$bg_pri_entry_data_detail_body_head['remark']?$bg_pri_entry_data_detail_body_head['remark']:'',
                    'insp_org_code'=>'', //口岸检验检疫机关 ---这个系统没有
                    'correlation_reason_flag'=>'', //关联理由【关联报检号的关联理由】 ---这个系统没有
                    'PromiseItmes1' =>'0', //承诺事项 ---
                    'domestic_consignee_ename'=>'', //境内收发货人名称（外文）---这个系统没有留空
                    'overseas_consignor_cname'=>$bg_pri_entry_data_detail_body_head['rlt_entry_bizop_etps_nm'], //境外收发货人名称 ---这个系统没有留空
                    'agent_code'=>$bg_pri_entry_data_detail_body_head['agent_code'],//申报单位代码
                    'agent_name'=>$bg_pri_entry_data_detail_body_head['agent_name'],//申报单位名称
                    'trans_mode'=>$bg_pri_entry_data_detail_body_head['trans_mode'], //成交方式
                    'net_wt'=>$bg_pri_entry_data_detail_body_head['net_wt'], //净重
                    'desp_date'=>'', //启运日期 ---这个系统没有
                    'bill_type'=>'1', //备案清单类型,1：普通备案清单   2：先进区后报关 3：分送集报备案清单 4；分送集报报关单
                    'enty_port_code'=>$bg_pri_entry_data_detail_body_head['enty_port_code'], //入境口岸代码
                    'promise_itmes_jgyxqr'=>'0',
                    'promise_itmes_txsyq'=>'0', //承诺事项
                    //'contr_no'=>'', //合同协议号 ---这个系统没有
                    'trade_ciq_code'=>'', //境内收发货人检验检疫编码 ---这个系统没有
                    'BLNo'=>'', //B/L号,提货单号【本批货物的提货单或出库单号码】 ---这个系统没有
                    'cmpl_dschrg_dt'=>'', //卸毕日期 ---这个系统没有
                    //'decl_ciq_code'=>'', //申报单位检验检疫编码 ---这个系统没有
                );
                $bodyInfos = [];
                foreach ($bg_pri_entry_data_detail_body_detail as $kb=>$vb){
                    $bodyInfo  = array(
                        'g_no'=>$vb['g_no'],
                        'contr_item'=>$vb['contr_item'],
                        'code_ts'=>$vb['code_ts'],
                        'gname'=>$vb['gname'],
                        'gmodel'=>$vb['gmodel'],
                        'gqty'=>$vb['gqty'],
                        'gunit'=>$vb['gunit'],
                        'decl_price'=>$vb['decl_price'],
                        'decl_total'=>$vb['decl_total'],
                        'trade_curr'=>$vb['trade_curr'],
                        'first_qty'=>$vb['first_qty'],
                        'first_unit'=>$vb['first_unit'],
                        'exg_version'=>'',
                        'exg_no'=>'',
                        'destination_country'=>$vb['destination_country'],
                        'second_qty'=>$vb['second_qty'],
                        'second_unit'=>$vb['second_unit'],
                        'rcep_orig_place_code'=>'',
                        'origin_country'=>$vb['origin_country']
                    );
                    $bodyInfos[] = $bodyInfo;
                    //Service_Currency::converByHscode();
                    $amount+=$vb['decl_total'];
                }
                $currency = Service_Currency::getByField($vb['trade_curr'],'currency_hs_code');
                $note.="总金额：".$amount.$currency['currency_code'];
                $baseinfohead['note_s'] = $note;


                $baseinfo['head'] = $baseinfohead;
                $baseinfo['bodyInfo'] = $bodyInfos;
                $this->baseinfo = $baseinfo;

                //查找集装箱号
                if(!empty($bg_pri_entry_data_detail_body_containers)){
                    $cRows = [];
                    foreach ($bg_pri_entry_data_detail_body_containers as $k=>$p){
                        $cRow = array(
                            'container_id'=>$p['container_id'],
                            'container_md'=>$p['container_md'],
                            'container_wt'=>$p['container_wt'],
                            'lcl_flag'=>$p['lcl_flag'],
                            'goods_no'=>$p['goods_no']
                        );
                        $cRows = $cRow;
                    }
                    $this->bg_pri_entry_data_detail_body_containers = $cRows;
                }
                //获取所需单证信息
                $this->getMessageDecfreetxt();
                if(!empty($bg_pri_entry_data_detail_body_licensedocu)){
                    $licensedocus = [];
                    foreach ($bg_pri_entry_data_detail_body_licensedocu as $k=>$vl){
                        $licensedocu = array(
                            'docu_code'=>$vl['docu_code'],
                            'cert_code'=>$vl['cert_code']
                        );
                        $licensedocus[] = $licensedocu;
                    }
                    $this->licensedo = $licensedocus;
                }
            }
        }catch (Exception $e){
            $this->error[] = "获取基本信息错误".$e->getMessage();
        }
    }
    /**
     * @todo 获取head
     */
    public function getCountRow(){

        $pt_code = $this->bg_pri_entry_data_detail_body_head['pt_code'];
        $entry_type = "M";
        switch ($pt_code){
            case "I0110":
                break;
            case "E1234":
                break;
            default:
                $this->error[] = "业务代码未配置报关单类型:".$pt_code;
        }
        //设置一些配置的业务类型
        $formType = Service_FormType::getByField($pt_code,'form_type');
        if(empty($formType)){
            $this->error[] = "业务类型:{$pt_code}不存在";
        }else{
            //业务类型存在的情况下
            if($formType['default_value']!=''){
                $defaultArr = json_decode($formType['default_value'],true);
                if(empty($defaultArr)){
                    $this->error[] = "默认配置参数无法初始化";
                }
                if(!empty($defaultArr)){
                    $countRow = $defaultArr;
                }
            }
        }

        $countRow['entry_type'] = $entry_type;
        $countRow['goods_place'] = '前海湾保税港区';
        $countRow['mark_no'] = 'N/M';
        $this->countRow = $countRow;
    }
    /**
     * @todo 用于获取自有文本
     */
    public function getMessageDecfreetxt(){
        $messageDecfreetxtData = $messageDecfreetxt = [];
        $messageDecfreetxtData['dec_bp_no'] = "";
        $messageDecfreetxtData['dec_no'] = "";
        if(isset($this->baseinfo['head'])){
            $headinfo = $this->baseinfo['head'];
            if($headinfo['BonNo']&&$headinfo['BonNo']!=''){
                $messageDecfreetxtData['bon_no'] = $messageDecfreetxt['bon_no'] = $headinfo['BonNo'];
            }else{
                $messageDecfreetxtData['bon_no'] = "";
            }
            if($headinfo['CusFie']&&$headinfo['CusFie']!=''){
                $messageDecfreetxtData['cus_fie'] = $messageDecfreetxt['cus_fie'] = $headinfo['CusFie'];
            }else{
                $messageDecfreetxtData['cus_fie'] = "";
            }
            if($headinfo['rel_id']&&$headinfo['rel_id']!=''){
                $messageDecfreetxtData['rel_id'] = $messageDecfreetxt['rel_id'] = $headinfo['rel_id'];
            }else{
                $messageDecfreetxtData['rel_id'] = "";
            }
            if($headinfo['manual_no']&&$headinfo['manual_no']!=''){
                $messageDecfreetxtData['rel_man_no'] = $messageDecfreetxt['manual_no'] = $headinfo['manual_no'];
            }else{
                $messageDecfreetxtData['rel_man_no']  = "";
            }
            if($headinfo['VoyNo']&&$headinfo['VoyNo']!=''){
                $messageDecfreetxtData['voy_no'] = $messageDecfreetxt['voy_no'] = $headinfo['VoyNo'];
            }else{
                $messageDecfreetxtData['voy_no'] = '';
            }
        }
        if(!empty($messageDecfreetxt)){
            $this->messageDecfreetxt = $messageDecfreetxt;
            return $messageDecfreetxtData;
        }
        return $messageDecfreetxt;
    }
    /**
     * @todo 根据预录入数据生成报关单
     * 根据bg_pri_entry_data_detail_body_head表的主键bpedbh_id生成
     */
    public function makebaoguan(){
        $return =[
            'state'=>0,
            'message'=>'fail',
            'code'=>'',
            'error'=>[]
        ];
        try {
            $this->getBaseInfo();
            $baseInfo = $this->baseinfo;
            //print_r($baseInfo);
            $invProcess = new Process_Baoguan();
            if(empty($baseInfo['head']) ||empty($baseInfo['bodyInfo'])){
                throw new Exception('基本信息或者商品信息为空');
            }
            $messageDecfreetxt = $this->getMessageDecfreetxt();
            $invProcess->setBaseinfo($baseInfo);
            if(!empty($this->bg_pri_entry_data_detail_body_containers)){
                $invProcess->setContainer($this->bg_pri_entry_data_detail_body_containers);
            }
            //$invProcess->setGoodsLimitVin($goodsLimitVin);
            //$invProcess->setDecrequestRert($requestcert);
            //$invProcess->setGoodsLimitType($goodsLimitType);
            $invProcess->setLicensedocu($this->licensedo);
            $invProcess->setMessageDecfreetxt($messageDecfreetxt);
            $error = $invProcess->validInfo();
            $baseInfo = $invProcess->getBaseinfo();


            //var_dump($error);
            //exit;
            if(!empty($error)){
                throw new Exception(implode("|",$error));
            }

            //经过校验和处理之后的数据
            $baseInfo = $invProcess->getBaseinfo();
            $goodsLimitVin = $invProcess->getGoodsLimitVin();
            //print_r($baseInfo);
            //exit;
            $invProcess->add($baseInfo['head'],$baseInfo['bodyInfo']);
            if(!empty($container)){
                $invProcess->addContainer($container);
            }
            if(!empty($goodsLimitVin)){
                $invProcess->addGoodsLimitVin($goodsLimitVin);
            }
            if(!empty($goodsLimitType)){
                $invProcess->addGoodsLimitType($goodsLimitType);
            }
            if(!empty($messageDecfreetxt)){
                $invProcess->addMessageDecfreetxt($messageDecfreetxt);
            }
            if(!empty($this->licensedo)){
                $invProcess->addLicensedocu($this->licensedo);
            }
            $this->dmhId = $invProcess->getDmhId();
            $this->AddPriDataLivtSbDecCd();
            $return['state'] = 1;
            $return['code'] = $invProcess->getDmhNoRel();
        }catch (Exception $e){
            $return['message'] = $e->getMessage();
        }
        return $return;
    }
    /**
     * @todo 获取bg_pri_data_livt_sb_dec_cd信息
     */
    public function AddPriDataLivtSbDecCd(){
        $row = [];
        $row['bped_id'] = $this->bg_pri_entry_data_detail_body_head['bped_id'];
        $row['bpedbh_id'] = $this->bg_pri_entry_data_detail_body_head['bpedbh_id'];
        $row['ref_table'] = 'des_message_list';
        $row['ref_id'] = 'dml_id';
        $row['ref_value'] = $this->dmhId;
        $row['op_ip'] = Common_Common::getIP();
        $row['op_id'] = Service_User::getUserId();
        $row['add_time'] = date('Y-m-d H:i:s',time());
        $row['remark'] = '';
        Service_BgPriDataLivtSbDecCd::add($row);
        return $row;
    }

}