<?php

/**
 * Created by PhpStorm.
 * User: boyer
 * Date: 2021/10/28
 * Time: 13:57
 */
class Process_Baoguan
{
    protected $dmhId = '';
    protected $dmh_no = '';

    protected $baseinfo; //基本信息
    protected $containerList;//集装箱信息
    protected $limitType; //报关单许可证
    protected $cert; //申请单证
    protected $goodsLimitVin; //报关单许可证Vin
    protected $licensedo; //随附单证
    protected $messageDecfreetxt; //报关单自有文本

    protected $entry_types = array(
        '0',
        'L',
        'W',
        'D',
        'M'
    );

    protected $error;
    /**
     * @todo 设置基本信息
    **/
    public function setBaseinfo($baseinfo){
        $this->baseinfo = $baseinfo;
    }
    /**
     * @todo 获取基本信息
     */
    public function getBaseinfo(){
        return $this->baseinfo;
    }
    /**
     * @todo 设置集装箱信息
     */
    public function setContainer($containerList) {
        $this->containerList = $containerList;
    }
    /**
     * @todo 设置报关单许可证
     */
    public function setGoodsLimitType($limitType) {
        $this->limitType = $limitType;
    }
    /**
     * @todo 设置申请单证
     */
    public function setDecrequestRert($cert){
        $this->cert = $cert;
    }
    /**
     * @todo 设置报关单许可证Vin
     */
    public function setGoodsLimitVin($goodsLimitVin){
        $this->goodsLimitVin = $goodsLimitVin;
    }
    /**
     * @todo 获取报关单许可证Vin
     */
    public function getGoodsLimitVin(){
        return $this->goodsLimitVin;
    }
    /**
     * @todo 设置随附单证
     */
    public function setLicensedocu($licensedo){
        $this->licensedo = $licensedo;
    }
    /**
     * @todo 设置报关单自有文本
     */
    public function setMessageDecfreetxt($messageDecfreetxt){
        $this->messageDecfreetxt = $messageDecfreetxt;
    }
    /**
     * @todo 校验报关单表头
     */
    public function validateHead(){
        $header = $this->baseinfo['head'];
        if(empty($header)){
            $this->error[] = "报关单无表头信息";
        }else{
            if(!(isset($header['ieflag']) && in_array($header['ieflag'],array("I","E")))){
                $this->error[] = "报关单进出标志只能是I/E";
            }
            /*if($header['iedate']!=''){
                if((date("Ymd",strtotime($header['iedate']))!=$header['iedate'])){
                    $this->error[] = "进/出口日期无效";
                }
            }else{
                $this->error[] = "进/出口日期不能为空";
            }*/
            if($header['traf_mode']!=''){
                $trafModel = Service_TrafMode::getByField($header['traf_mode'],'traf_mode');
                if(empty($trafModel)){
                    $this->error[] = "运输方式{$trafModel}不对";
                }
            }else{
                $this->error[] = "运输方式必须填写";
            }
            if($header['bill_no']==''){
                //$this->error[] = "提单必须填写";
            }
            if($header['pack_no']==''){
                $this->error[] = "件数不能为空";
            }
            if($header['trade_area_code']==''){
                $this->error[] = "贸易国别不能为空";
            }
            if($header['entry_type']!=''){
                if(!in_array($header['entry_type'],$this->entry_types)){
                    $this->error[] = "报关单类型错误{$header['entry_type']}";
                }
            }else{
                //报关单类型
                $this->error[] = "报关单类型为空";
            }
            if($header['org_code']==''){
                //$this->error[] = "检验检疫受理机关必填";
            }
            if($header['spec_decl_flag_gjss']!=''){
                if(!(isset($header['spec_decl_flag_gjss']) && in_array($header['spec_decl_flag_gjss'],array("0","1")))){
                    $this->error[] = "特殊业务标识-国际赛事只能填0/1";
                }
            }else{
                $this->error[] = "特殊业务标识-国际赛事必填";
            }
            if($header['spec_decl_flag_wj']!=''){
                if(!(isset($header['spec_decl_flag_wj']) && in_array($header['spec_decl_flag_wj'],array("0","1")))){
                    $this->error[] = "特殊通过模式-外交礼遇只能填0/1";
                }
            }else{
                $this->error[] = "特殊通过模式-外交礼遇必填";
            }
            if($header['custom_master']==''){
                $this->error[] = "申报地海关必填";
            }
            if($header['trade_code']==''){
                $this->error[] = "境内收发货认代码必填";
            }else{
                //校验有效性
                $ebpinfo = Service_EntInfo::getEntBycustomerOrscc($header['trade_code']);
                if(empty($ebpinfo)){
                    $this->error[] = "境内收发货人{$header['trade_code']}无效";
                }else{
                    $this->baseinfo['head']['trade_code'] = $ebpinfo['ent_customs_code'];
                    $this->baseinfo['head']['trade_co_scc'] = $ebpinfo['ent_code_scc'];
                }
            }
            if($header['owner_code']==''){
                $this->error[] = "消费使用单位代码必填";
            }else{
                //校验有效性
                $ebpinfo = Service_EntInfo::getEntBycustomerOrscc($header['owner_code']);
                if(empty($ebpinfo)){
                    $this->error[] = "消费使用单位{$header['trade_code']}无效或者未配置企业信息,请联系管理员配置";
                }else{
                    $this->baseinfo['head']['owner_code'] = $ebpinfo['ent_customs_code'];
                    $this->baseinfo['head']['owner_code_scc'] = $ebpinfo['ent_code_scc'];
                }
            }
            if($header['owner_name']==''){
                $this->error[] = "消费使用单位必填";
            }
            if($header['trade_mode']==''){
                $this->error[] = "监管方式必填";
            }
            if($header['trade_country']==''){
                $this->error[] = "启运国/抵运国必填";
            }
            if($header['wrap_type']!=''){
                /*$wrap = Service_WrapType::getByField($header['wrap_type'],'wrap_type');
                if(empty($wrap)){
                    $this->error[] = "包装种类错误-->".$header['wrap_type'];
                }*/
            }else{
                $this->error[] = "包装种类必填";
            }
            if($header['mark_no']==''){
                $this->error[] = "标记唛码必填";
            }
            if($header['vsa_org_code']==''){
                //$this->error[] = "领证机关必填";
            }
            if($header['spec_decl_flag_jg']!=''){
                if(!(isset($header['spec_decl_flag_jg']) && in_array($header['spec_decl_flag_jg'],array("0","1")))){
                    $this->error[] = "特殊业务标识-特殊进出军工物资只能填0/1";
                }
            }else{
                $this->error[] = "特殊业务标识-特殊进出军工物资必填";
            }
            if($header['spec_decl_flag_zg']!=''){
                if(!(isset($header['spec_decl_flag_zg']) && in_array($header['spec_decl_flag_zg'],array("0","1")))){
                    $this->error[] = "特殊通过模式-转关只能填0/1";
                }
            }else{
                $this->error[] = "特殊通过模式-转关必填";
            }
            if($header['ieport']==''){
                $this->error[] = "进/出境关别必填";
            }
            if($header['trade_name']==''){
                $this->error[] = "境外收发货人地址必填";
            }
            //消费使用单位检验检疫代码
            if($header['gross_wet']==''){
                $this->error[] = "毛重必填";
            }else{
                if(!is_numeric($header['gross_wet'])){
                    $this->error[] = "毛重必须是数字";
                }
            }
            if($header['gross_wet']==''){
                $this->error[] = "毛重必填";
            }
            //特殊业务标识-国际援助物资
            if($header['spec_decl_flag_gjyz']!=''){
                if(!(isset($header['spec_decl_flag_gjyz']) && in_array($header['spec_decl_flag_gjyz'],array("0","1")))){
                    $this->error[] = "特殊业务标识-国际援助物资只能填0/1";
                }
            }else{
                $this->error[] = "特殊业务标识-国际援助物资必填";
            }
            //特殊关系确认
            if($header['PromiseItmes1']!=''){
                if(!(isset($header['PromiseItmes1']) && in_array($header['PromiseItmes1'],array("0","1","9")))){
                    $this->error[] = "特殊关系确认只能填0/1/9";
                }
            }else{
                $this->error[] = "特殊关系确认必填";
            }
            if($header['agent_code']==''){
                $this->error[] = "申报单位代码必填";
            }else{
                //校验有效性
                $ebpinfo = Service_EntInfo::getEntBycustomerOrscc($header['agent_code']);
                if(empty($ebpinfo)){
                    $this->error[] = "境内收发货人{$header['agent_code']}无效";
                }else{
                    $this->baseinfo['head']['agent_code'] = $ebpinfo['ent_customs_code'];
                    $this->baseinfo['head']['agent_code_scc'] = $ebpinfo['ent_code_scc'];
                }
            }
            if($header['trans_mode']!=''){
                $transModel = Service_TransMode::getByField($header['trans_mode'],'trans_mode');
                if(empty($transModel)){
                    $this->error[] = "成交方式错误";
                }
            }else{
                $this->error[] = "成交方式必填";
            }
            if($header['net_wt']==''){
                $this->error[] = "净重必填";
            }else{
                if(!is_numeric($header['net_wt'])){
                    $this->error[] = "毛重必须是数字";
                }
            }
            if($header['desp_date']==''){
                //$this->error[] = "启运日期必填";
            }
            if($header['bill_type']!=''){
                if(!(isset($header['bill_type']) && in_array($header['bill_type'],array("1","2","3","4")))){
                    $this->error[] = "清单类型只能填1/2/3/4";
                }
            }else{
                //$this->error[] = "清单类型必填";(可以不填)
            }
            //特殊业务标识-国际会议
            if($header['spec_decl_flag_gjhy']!=''){
                if(!(isset($header['spec_decl_flag_gjhy']) && in_array($header['spec_decl_flag_gjhy'],array("0","1")))){
                    $this->error[] = "特殊业务标识-国际会议只能填0/1";
                }
            }else{
                $this->error[] = "特殊业务标识-国际会议必填";
            }
            if($header['promise_itmes_jgyxqr']!=''){
                if(!(isset($header['promise_itmes_jgyxqr']) && in_array($header['promise_itmes_jgyxqr'],array("0","1")))){
                    $this->error[] = "价格影响确认只能填0/1";
                }
            }else{
                $this->error[] = "价格影响确认必填";
            }
            if($header['spec_decl_flag_ztfx']!=''){
                if(!(isset($header['spec_decl_flag_ztfx']) && in_array($header['spec_decl_flag_ztfx'],array("0","1")))){
                    $this->error[] = "特殊通过模式-直通放行只能填0/1";
                }
            }else{
                $this->error[] = "特殊通过模式-直通放行必填";
            }
            if($header['promise_itmes_txsyq']!=''){
                if(!(isset($header['promise_itmes_txsyq']) && in_array($header['promise_itmes_txsyq'],array("0","1")))){
                    $this->error[] = "与货物有关的特许权使用费支付确认只能填0/1";
                }
            }else{
                $this->error[] = "与货物有关的特许权使用费支付确认必填";
            }
            //处理 价格说明，
            //1勾选 0-未选 9-空
            //第一位特殊关系确认
            //第二位价格影响确认
            //第三位支付特许权使用费确认
            //第四位公式定价确认
            //第五位暂定价格确认
            $promise_itmes = "";
            if(isset($header['PromiseItmes1'])){
                $promise_itmes.=$header['PromiseItmes1'];
                unset($this->baseinfo['head']['PromiseItmes1']);
                unset($header['PromiseItmes1']);
            }
            if(isset($header['promise_itmes_jgyxqr'])){
                $promise_itmes.=$header['promise_itmes_jgyxqr'];
                unset($this->baseinfo['head']['promise_itmes_jgyxqr']);
                unset($header['promise_itmes_jgyxqr']);
            }
            if(isset($header['promise_itmes_txsyq'])){
                $promise_itmes.=$header['promise_itmes_txsyq'];
                unset($this->baseinfo['head']['promise_itmes_txsyq']);
                unset($header['promise_itmes_txsyq']);
            }
            $this->baseinfo['head']['promise_itmes'] = $promise_itmes; //生成价格说明字段
            //处理 特种业务标识
            //特种业务标识：0未勾选，1选中。
            //第一位：“国际赛事”；
            //第二位：“特殊进出军工物资”；
            //第三位:“国际援助物资”；
            //第四位：“国际会议”；
            //第五位：“直通放行”；
            //第六位：“外交礼遇”；
            //第七位：“转关
            $spec_decl_flag = "";
            if(isset($header['spec_decl_flag_gjss'])){
                $spec_decl_flag.=$header['spec_decl_flag_gjss'];
                unset($this->baseinfo['head']['spec_decl_flag_gjss']);
                unset($header['spec_decl_flag_gjss']);
            }
            if(isset($header['spec_decl_flag_jg'])){
                $spec_decl_flag.=$header['spec_decl_flag_jg'];
                unset($this->baseinfo['head']['spec_decl_flag_jg']);
                unset($header['spec_decl_flag_jg']);
            }
            if(isset($header['spec_decl_flag_gjyz'])){
                $spec_decl_flag.=$header['spec_decl_flag_gjyz'];
                unset($this->baseinfo['head']['spec_decl_flag_gjyz']);
                unset($header['spec_decl_flag_gjyz']);
            }
            if(isset($header['spec_decl_flag_gjhy'])){
                $spec_decl_flag.=$header['spec_decl_flag_gjhy'];
                unset($this->baseinfo['head']['spec_decl_flag_gjhy']);
                unset($header['spec_decl_flag_gjhy']);
            }
            if(isset($header['spec_decl_flag_ztfx'])){
                $spec_decl_flag.=$header['spec_decl_flag_ztfx'];
                unset($this->baseinfo['head']['spec_decl_flag_ztfx']);
                unset($header['spec_decl_flag_ztfx']);
            }
            if(isset($header['spec_decl_flag_wj'])){
                $spec_decl_flag.=$header['spec_decl_flag_wj'];
                unset($this->baseinfo['head']['spec_decl_flag_wj']);
                unset($header['spec_decl_flag_wj']);
            }
            if(isset($header['spec_decl_flag_zg'])){
                $spec_decl_flag.=$header['spec_decl_flag_zg'];
                unset($this->baseinfo['head']['spec_decl_flag_zg']);
                unset($header['spec_decl_flag_zg']);
            }
            $this->baseinfo['head']['spec_decl_flag'] = $spec_decl_flag;


        }
    }
    /**
     * @todo 校验报关单表体
     */
    public function validateBody(){
        $body = $this->baseinfo['bodyInfo'];
        //print_r($body);
        if(!empty($body)){
            foreach ($body as $k=>$b){
                if(empty(array_filter($b))){
                    unset($this->baseinfo['bodyInfo'][$k]);
                }else{
                    //校验表体数据
                    $g_no = (int)$b['g_no'];
                    if(!(is_int($g_no) && $g_no>0)){
                        $this->error[] = "商品表体第".($k+1)."的项号必须大于0的整数";
                    }
                    if($b['code_ts']!=''){
                        //$this->error[] = "商品表体第".($k+1)."的项号必须大于0的整数";
                        $hsRow = Service_Hscodes::getByField($b['code_ts'],'hs_code');
                        if(empty($hsRow)){
                            //$this->error[] = "商品表体第".($k+1)."的商品编码必须填写正确:".$b['code_ts'];
                        }
                    }else{
                        $this->error[] = "商品表体第".($k+1)."的商品编码必须填写";
                    }
                    //计量单位
                    if($b['gunit']!=''){
                        $puRow = Service_ProductUom::getByField($b['gunit'],'pu_code');
                        if(empty($puRow)){
                            $this->error[] = "商品表体第".($k+1)."的计量单位{$b['gunit']}不存在";
                        }
                    }else{
                        $this->error[] = "商品表体第".($k+1)."的计量单位必须填写";
                    }
                }
            }
        }else{
            $this->error[] = "报关单无商品表体信息";
        }
    }
    /**
     * 校验报关单基本信息
     */
    public function validateBaseInfo() {
        $this->validateHead();
        $this->validateBody();
    }
    /**
     * @todo 校验集装箱信息
     */
    public function validatecontainerList(){

    }
    /**
     * @todo 校验报关单许可证
     */
    public function validatelimitType(){

    }
    /**
     * @todo 校验申请单证
     */
    public function validatecert(){

    }
    /**
     * @todo 校验报关单许可证Vin
     */
    public function validategoodsLimitVin(){
        $goodsLimitVin = $this->goodsLimitVin;
        if(!empty($goodsLimitVin)){
            foreach ($goodsLimitVin as $k=>$v){
                if(empty(array_filter($v))){
                    unset($this->goodsLimitVin[$k]);
                }
            }
        }
    }
    /**
     * @todo 校验随附单证
     */
    public function valivatelicensedo(){

    }
    /**
     * @todo 校验报关单自有文本
     */
    public function validatemessageDecfreetxt(){

    }
    /**
     * @todo 报关单校验
     */
    public function validInfo(){
        $this->validateBaseInfo();
        $this->validatecontainerList();
        $this->validatelimitType();
        $this->validatecert();
        $this->validategoodsLimitVin();
        $this->valivatelicensedo();
        $this->validatemessageDecfreetxt();
        return $this->error;
    }
    public function setDmhId($dmhId) {
        $this->dmhId = $dmhId;
    }

    public function getDmhId() {
        if (!$this->dmhId) {
            throw new Exception('报关单未创建，请先创建');
        }
        return $this->dmhId;
    }
    public function getDmhNo(){
        $dmh_no = Common_GetNumber::getCode('baoguandan', '', 'BGD');
        $this->dmh_no = $dmh_no;
        return $this->dmh_no;
    }
    public function getDmhNoRel(){
        return $this->dmh_no;
    }

    //
    public function add($head, $lists) {
        $head['add_time'] = date("Y-m-d H:i:s");
        //生成dmh_no
        $dmh_no = $this->getDmhNo();
        $head['dmh_no'] = $dmh_no;
        $dmhId = Service_DesMessageHead::add($head);
        $this->setDmhId($dmhId);
        if($dmhId){
            foreach ($lists as $item) {
                $item['dmh_id'] = $dmhId;
                if(!Service_DesMessageList::add($item)){
                    throw new Exception("添加报关单表体信息错误");
                }
            }
        }else{
            throw new Exception("添加报关单表头信息错误");
        }
        return $dmhId;
    }

    /**
     * Note:添加集装箱信息
     * User: Yao
     * Date: 2021/10/28
     * Time: 14:13
     */
    public function addContainer($containerList) {
        if(!empty($containerList)){
            foreach ($containerList as $container) {
                $container['dmh_id'] = $this->getDmhId();
                Service_DesMessageContainers::add($container);
            }
        }
    }

    /**
     * Note:添加报关单许可证
     * User: Yao
     * Date: 2021/10/28
     * Time: 14:23
     */
    public function addGoodsLimitType($limitType) {
        foreach ($limitType as $limit) {
            $limit['dmh_id'] = $this->getDmhId();
            Service_DesMessageGoodslimittype::add($limit);
        }
    }
    /**
     * Note:申请单证
     * User: Yao
     * Date: 2021/10/28
     * Time: 14:30
     * @param $cert
     */
    public function addDecrequestRert($cert){
        foreach ($cert as $item) {
            $item['dmh_id'] = $this->getDmhId();
            Service_DesMessageDecrequestcert::add($item);
        }
    }
    /**
     * Note:报关单许可证Vin
     * User: Yao
     * Date: 2021/10/28
     * Time: 14:31
     * @param $cert
     * @throws Exception
     */
    public function addGoodsLimitVin($goodsLimitVin){
        //print_r($goodsLimitVin);
        foreach ($goodsLimitVin as $item) {
            $item['dmh_id'] = $this->getDmhId();
            Service_DesMessageGoodslimitvin::add($item);
        }
    }

    /***
     * Note:随附单证
     * User: Yao
     * Date: 2021/10/28
     * Time: 14:34
     */
    public function addLicensedocu($licensedo){
        foreach ($licensedo as $item) {
            $item['dmh_id'] = $this->getDmhId();
            Service_DesMessageLicensedocu::add($item);
        }
    }
    /**
     * @todo 报关单自有文本
     */
    public function addMessageDecfreetxt($messageDecfreetxt){
        if(!empty($messageDecfreetxt)){
            $messageDecfreetxt['dmh_id'] = $this->getDmhId();
            Service_DesMessageDecfreetxt::add($messageDecfreetxt);
        }
    }

}