<?php
require_once "PHPExcel1.8/PHPExcel.php";
require_once "PHPExcel1.8/PHPExcel/Reader/Excel2007.php";
require_once "PHPExcel1.8/PHPExcel/Reader/Excel5.php";

class Process_BaoguanUpload
{
    protected $phpExcel;
    protected $filePath;
    protected $baseinfo;
    public function setFilePath($path) {
        $this->filePath = $path;
        $this->getExcelReader();
        return $this;
    }
    protected function getExcelReader() {
        $PHPReader = new PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($this->filePath)) {
            $PHPReader = new PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($this->filePath)) {
                throw new Exception("Invalid File.");
            }
        }
        $this->phpExcel = $PHPReader->load($this->filePath);
    }

    public function getBaseInfo() {
        $headerTitle=[
            '进出口标识'=>['B2', 'ieflag'],
            '进/出口日期'=>['B3', 'iedate'],
            '境外发货人代码'=>['B4','overseas_consignor_code'],
            '消费使用单位代码'=>['B5','owner_code'],//有问题以前是owner_ciq_code
            '运输方式'=>['B6','traf_mode'],
            '提运单号'=>['B7','bill_no'],
            '许可证号'=>['B8','license_no'],
            '运费标识'=>['B9','fee_mark'],
            '保费标识'=>['B10','insur_mark'],
            '杂费标识'=>['B11','other_mark'],
            '件数'=>['B12','pack_no'],
            '贸易国别'=>['B13','trade_area_code'],
            '报关单类型'=>['B14','entry_type'],
            '检验检疫受理机关'=>['B15','org_code'],
            '目的地检验检疫机关'=>['B16','purp_org_code'],
            '特殊业务标识-国际赛事'=>['B17','spec_decl_flag_gjss'], //SpecDeclFlag,这个17和18是一个字段
            '特殊通过模式-外交礼遇'=>['B18','spec_decl_flag_wj'],
            '关联报关单号'=>['B19','rel_id'],//暂时不知道存哪里自由文本
            '申报地海关'=>['D2','custom_master'],
            '境内收发货人代码'=>['D3','trade_code'],//接口文档是trade_co
            '境外收发货人名称（英文）'=>['D4','overseas_consignor_ename'],
            '消费使用单位名称'=>['D5','owner_name'],
            '运输工具名称'=>['D6','traf_name'],//这个不确定
            '监管方式'=>['D7','trade_mode'],
            '启运国/抵运国'=>['D8','trade_country'],
            '运费数值'=>['D9','fee_rate'],
            '保费数值'=>['D10','insur_rate'],
            '杂费数值'=>['D11','other_rate'],
            '包装种类'=>['D12','wrap_type'],
            '存放地点'=>['D13','goods_place'],
            '标记唛码'=>['D14','mark_no'],
            '领证机关'=>['D15','vsa_org_code'],
            '关联号码'=>['D16','correlation_no'],
            '特殊业务标识-特殊进出军工物资'=>['D17','spec_decl_flag_jg'],//特种业务标识：0未勾选，1选中。第一位：“国际赛事”；第二位：“特殊进出军工物资”；第三位:“国际援助物资”；第四位：“国际会议”；第五位：“直通放行”；第六位：“外交礼遇”；第七位：“转关
            '特殊通过模式-转关'=>['D18','spec_decl_flag_zg'],
            '关联备案号'=>['D19','manual_no'],
            '进/出境关别'=>['F2','ieport'],
            '境内收发货人名称'=>['F3','trade_name'],
            '境外收发货人地址'=>['F4','overseas_consignor_addr'],
            '消费使用单位检验检疫代码'=>['F5','owner_ciq_code'],
            '航次号'=>['F6','VoyNo'], //自由文本
            '征免性质'=>['F7','cut_mode'],
            '经停港/指运港'=>['F8','distinate_port'],
            '运费币制代码'=>['F9','fee_curr'],
            '保费币制代码'=>['F10','insur_curr'],
            '杂费币制代码'=>['F11','other_curr'],
            '毛重（KG）'=>['F12','gross_wet'],
            '启运港'=>['F13','desp_port_code'],
            '备注'=>['F14','note_s'],
            '口岸检验检疫机构'=>['F15','insp_org_code'],
            '关联理由'=>['F16','correlation_reason_flag'],
            '特殊业务标识-国际援助物资'=>['F17','spec_decl_flag_gjyz'],//特种业务标识：0未勾选，1选中。第一位：“国际赛事”；第二位：“特殊进出军工物资”；第三位:“国际援助物资”；第四位：“国际会议”；第五位：“直通放行”；第六位：“外交礼遇”；第七位：“转关],
            '特殊关系确认'=>['F18','PromiseItmes1'],//1勾选 0-未选 9-空 第一位特殊关系确认;第二位价格影响确认;第三位支付特许权使用费确认;第四位公式定价确认;第五位暂定价格确认
            '保税/监管场地'=>['F19','BonNo'],
            '备案号'=>['H2','manual_no'],
            '境内收发货人名称（英文）'=>['H3','domestic_consignee_ename'],//不确定
            '境外收发货人名称（中文）'=>['H4','overseas_consignor_cname'],
            '申报单位代码'=>['H5','agent_code'],
            '成交方式'=>['H8','trans_mode'],
            '净重（KG）'=>['H12','net_wt'],
            '启运日期'=>['H13','desp_date'],
            '清单类型'=>['H14','bill_type'],//自贸区特有的类型：1：普通备案清单;2：先进区后报关;3：分送集报备案清单;4；分送集报报关单;注：当选择自贸区类型时，以下字段不可填写
            '入境/离境口岸'=>['H15','enty_port_code'],
            // '原箱运输'=>['H16'],
            '特殊业务标识-国际会议'=>['H17','spec_decl_flag_gjhy'],//特种业务标识：0未勾选，1选中。第一位：“国际赛事”；第二位：“特殊进出军工物资”；第三位:“国际援助物资”；第四位：“国际会议”；第五位：“直通放行”；第六位：“外交礼遇”；第七位：“转关],],
            '价格影响确认'=>['H18','promise_itmes_jgyxqr'],
            '货场代码'=>['H19','CusFie'],//CUSTOMS_FIELD还是customs_fie?文档不一样
            '合同号协议号'=>['J2','contr_no'],
            '境内收发货人检验检疫编码'=>['J3','trade_ciq_code'],
            '申报单位名称'=>['J5','agent_name'],
            'B/L号'=>['J15','BLNo'],//BLNo
            '卸毕日期'=>['J16','cmpl_dschrg_dt'],
            '特殊通过模式-直通放行'=>['J17','spec_decl_flag_ztfx'],//特种业务标识：0未勾选，1选中。第一位：“国际赛事”；第二位：“特殊进出军工物资”；第三位:“国际援助物资”；第四位：“国际会议”；第五位：“直通放行”；第六位：“外交礼遇”；第七位：“转关]
            '与货物有关的特许权使用费支付确认'=>['J18','promise_itmes_txsyq'],//第三位支付特许权使用费确认
            '申报单位检验检疫代码'=>['L5','decl_ciq_code']
        ];
        $currentSheet = $this->phpExcel->getSheet(0);
        $headData =[];
        foreach ($headerTitle as $colName => $cellInfo) {
           $value = $currentSheet->getCell($cellInfo[0])->getValue();
            if(is_object($value)){
                $value = $value->__toString();
            }
            if($value == NULL){
                $value='';
            }
            $headData[$cellInfo[1]] = $value;
        }
        $oldheaData = $headData;

        //报关单表头去除的文本
        $tripColumn = array(
            'rel_id',
            'VoyNo',
            //'PromiseItmes1',
            'customs_fie',
            'CusFie',
            'BonNo'
        );
        //<PromiseItmes>11199</PromiseItmes>
        foreach ($tripColumn as $k=>$trip){
            if(isset($headData[$trip])){
                unset($headData[$trip]);
            }
        }

        /*echo "<pre>";
        print_r($headData);
        exit;*/
        $bodyTitle=[
            'g_no'=>'A',
            'contr_item'=>'B',
            'code_ts'=>'C',
            'ciq_code'=>'D',
            'gname'=>'E',
            'gmodel'=>'F',
            'gqty'=>'G',
            'gunit'=>'H',
            'decl_price'=>'I',
            'decl_total'=>'J',
            'trade_curr'=>'K',
            'first_qty'=>'L',
            'first_unit'=>'M',
            'exg_version'=>'N',
            'exg_no'=>'O',
            'destination_country'=>'P',
            'second_qty'=>'Q',
            'second_unit'=>'R',
            'rcep_orig_place_code'=>'S',
            'origin_country'=>'T'
        ];
        $maxRow = $currentSheet->getHighestRow();
        $bodyInfo = [];
        for($i=23;$i<=$maxRow;$i++){
            $bodyRow =[];
            foreach ($bodyTitle as $column =>$cell){
                $value = $currentSheet->getCell($cell.$i)->getValue();
                if(is_object($value)){
                    $value = $value->__toString();
                }
                if($value!=NULL){
                    $bodyRow[$column] = $value;
                }else {
                    $bodyRow[$column] = '';
                }
            }
            if(!empty($bodyRow)){
                $bodyInfo[]=$bodyRow;
            }
        }
        $baseinfo = [
            'head'=>$headData,
            'bodyInfo'=>$bodyInfo,
        ];
        $this->baseinfo = $baseinfo;
        return $baseinfo;
    }
    /**
     * Note:获取许可证信息
     * User: Yao
     * Date: 2021/10/28
     * Time: 11:33
     */
    public function getGoodsLimit(){
        $currentSheet = $this->phpExcel->getSheet(1);
        $sheetTitle=[
            '商品序号'=>'goods_no',
            // '许可证信息序号'=>'',
            '许可证类别代码'=>'lic_type_code',
            '许可证编号'=>'licence_no',
            '核销货物序号'=>'lic_wrtof_detail_no',
            '核销数量'=>'lic_wrtof_qty',
            '核销数量单位'=>'lic_wrtof_qty_unit',
        ];
        $maxRow = $currentSheet->getHighestRow();
        $bodyInfo = [];
        for($i=3;$i<=$maxRow;$i++){
            $bodyRow =[
                'goods_no'=>$currentSheet->getCell('A'.$i)->getValue(),
                'lic_type_code'=>$currentSheet->getCell('C'.$i)->getValue(),
                'licence_no'=>$currentSheet->getCell('D'.$i)->getValue(),
                'lic_wrtof_detail_no'=>$currentSheet->getCell('E'.$i)->getValue(),
                'lic_wrtof_qty'=>$currentSheet->getCell('F'.$i)->getValue(),
                'lic_wrtof_qty_unit'=>$currentSheet->getCell('G'.$i)->getValue(),
            ];
            if(!empty($bodyRow)){
                $bodyRow = array_map(function($value){
                    if($value == NULL){
                        return '';
                    }
                    return $value;
                },$bodyRow);
                $bodyInfo[]=$bodyRow;
            }
        }
        return $bodyInfo;
    }

    /**
     * Note:许可证VIN信息
     * User: Yao
     * Date: 2021/10/28
     * Time: 13:20
     * @return array
     */
    public function getGoodslimitVin(){
        $currentSheet = $this->phpExcel->getSheet(2);
        $maxRow = $currentSheet->getHighestRow();
        $bodyInfo = [];
        for($i=3;$i<=$maxRow;$i++){
            $bodyRow =[
                //商品序号
                //许可证信息序号
                'vin_no'=>$currentSheet->getCell('C'.$i)->getValue(),//VIN序号
                'bill_lad_date'=>$currentSheet->getCell('D'.$i)->getValue(),// 提/运单日期
                'quality_qgp'=>$currentSheet->getCell('E'.$i)->getValue(),//质量保质期
                'motor_no'=>$currentSheet->getCell('F'.$i)->getValue(),//发动机号或电机号
                'vin_code'=>$currentSheet->getCell('G'.$i)->getValue(),//车俩识别代码
                'chassis_no'=>$currentSheet->getCell('H'.$i)->getValue(),//底盘号
                'invoice_num'=>$currentSheet->getCell('I'.$i)->getValue(),//发票所列数量
                'prod_cnnm'=>$currentSheet->getCell('J'.$i)->getValue(),//品名（中文）
                'prod_ennm'=>$currentSheet->getCell('K'.$i)->getValue(),//品名（英文）
                'price_per_unit'=>$currentSheet->getCell('L'.$i)->getValue(),//单价（英文）
                'invoice_no'=>$currentSheet->getCell('G'.$i)->getValue(),//单价（英文）
            ];
            if(!empty($bodyRow)){
                $bodyRow = array_map(function($value){
                    if($value == NULL){
                        return '';
                    }
                    return $value;
                },$bodyRow);
                $bodyInfo[]=$bodyRow;
            }
        }
        return $bodyInfo;
    }
    /**
     * Note:获取所需单证信息
     * User: Yao
     * Date: 2021/10/28
     * Time: 13:30
     * @return array
     */
    public function getDecrequestCert(){
        $currentSheet = $this->phpExcel->getSheet(3);
        $maxRow = $currentSheet->getHighestRow();
        $bodyInfo = [];
        for($i=3;$i<=$maxRow;$i++){
            $bodyRow =[
                'app_cert_code'=>$currentSheet->getCell('A'.$i)->getValue(),//证书代码
                'appl_ori'=>$currentSheet->getCell('B'.$i)->getValue(),//正本数量
                'appl_copy_quan'=>$currentSheet->getCell('C'.$i)->getValue(),//副本数量
            ];
            if(!empty($bodyRow)){
                $bodyInfo[]=$bodyRow;
            }
        }
        return $bodyInfo;
    }
    /**
     * Note: 获取集装箱信息
     * User: Yao
     * Date: 2021/10/28
     * Time: 13:32
     * @return array
     */
    public function getContainers(){
        $currentSheet = $this->phpExcel->getSheet(4);
        $maxRow = $currentSheet->getHighestRow();
        $bodyInfo = [];
        for($i=3;$i<=$maxRow;$i++){
            $bodyRow =[
                'container_id'=>$currentSheet->getCell('A'.$i)->getValue(),//集装箱号
                'container_md'=>$currentSheet->getCell('B'.$i)->getValue(),//集装箱规格
                'container_wt'=>$currentSheet->getCell('C'.$i)->getValue(),//集装箱自重
                'lcl_flag'=>$currentSheet->getCell('D'.$i)->getValue(),//拼箱标识
                'goods_no'=>$currentSheet->getCell('E'.$i)->getValue(),//商品项号关系
            ];
            if(!($bodyRow['container_id']!=''&&$bodyRow['container_md']!=''&&$bodyRow['container_wt']!=''&&$bodyRow['lcl_flag']!=''&&$bodyRow['goods_no']!='')){
                $bodyRow = [];
            }
            if(!empty($bodyRow)){
                $bodyRow = array_map(function($value){
                    if($value == NULL){
                        return '';
                    }
                    return $value;
                },$bodyRow);
                $bodyInfo[]=$bodyRow;
            }
        }
        return $bodyInfo;
    }
    /**
     * Note:随附单证
     * User: Yao
     * Date: 2021/10/28
     * Time: 13:40
     * @return array
     */
    public function getLicensedocu(){
        $currentSheet = $this->phpExcel->getSheet(3);
        $maxRow = $currentSheet->getHighestRow();
        $bodyInfo = [];
        for($i=3;$i<=$maxRow;$i++){
            $bodyRow =[
                'docu_code'=>$currentSheet->getCell('A'.$i)->getValue(),//单证代码
                'cert_code'=>$currentSheet->getCell('B'.$i)->getValue(),//单证编号
            ];
            if(!empty($bodyRow)){
                $bodyInfo[]=$bodyRow;
            }
        }
        return $bodyInfo;
    }
    /**
     * @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)){
            return $messageDecfreetxtData;
        }
        return $messageDecfreetxt;
    }
}