<?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_ProductUpload
{
    protected  $phpExcel;
    protected $filePath;
    protected $baseinfo;
    protected $uomList;
    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.");
            }
        }
        $PHPReader->setReadDataOnly(true);
        $this->phpExcel = $PHPReader->load($this->filePath);
    }

    public function getData()
    {
         $phpExcel = $this->phpExcel;
        $title = [
            '客户代码' => 'customer_code',
            '产品SKU' => 'product_sku',
            '条码类型' => 'product_barcode_type',
            '产品代码' => 'product_barcode',
            '产品名称' => 'product_title',
            '英文名' => 'product_title_en',
            '状态' => 'product_status',
            '单位' => 'pu_code',
            '申报币种' => 'currency_code',
            '申报价值' => 'product_declared_value',
            '产品净重（KG）' => 'product_net_weight',
            '海关编码' => 'hs_code',
            '料件号' => 'goods_id',
            '产品品类' => 'pc_id',
//            '供应商代码' => '',
            '长（CM）' => 'product_length',
            '宽（CM）' => 'product_width',
            '高（CM）' => 'product_height',
            '产品接收类型' => 'product_receive_status',
            '质检类型' => 'product_is_qc',
            '产品分类' => 'product_type',//?
            '产品添加时间' => 'product_add_time',
            '是否属于零件类' => 'is_accessories',
            '有无发票' => 'has_invoice',
            '产品型号' => 'model_serial',
            '海关品名' => 'hs_goods_name',
            '是否带电池' => 'with_battery',
            '电池类型' => 'battery_type',
            '法定单位' => 'pu_code_law',
            '法定数量' => 'hum_quantity_law',
            '第二法定单位' => 'pu_code_second',
            '第二法定数量' => 'hum_quantity_second',
            '要素名称'=>'he_name',
            '产品重量（KG）'=>'product_weight',
            '申报要素内容'=>'he_detail'
        ];
        $currentSheet = $phpExcel->getActiveSheet();
        $maxColumn = $currentSheet->getHighestColumn();
        /**取得一共有多少行*/
        $rowCount = $currentSheet->getHighestRow();
        $maxColumn=PHPExcel_Cell::columnIndexFromString($maxColumn);
        $sheetTitle=array();
        for ($column =0; $column < $maxColumn; $column++) {
            $value = $currentSheet->getCellByColumnAndRow($column,1)->getValue();
            if (is_object($value)) {
                $value = $value->__toString();
            }
            $value = trim($value);
            $sheetTitle[$column] = trim($value);
        }
        foreach($sheetTitle as $col=>$value){
            foreach($title as $t=>$index){
                if($value==$t){
                    $readCol[$col]=$index;
                }
            }
        }
        $result = array();
        if(empty($readCol)){
            return $result;
        }
        for ($row = 2; $row <=$rowCount; $row++) {
            $totalLen = 0; //记录行总长度
            $heName =[];
            $heDetail =[];
            foreach($readCol as $column=>$index){
                $value = $currentSheet->getCellByColumnAndRow($column,$row)->getValue();
                if (is_object($value)) {
                    $value = $value->__toString();
                }
                if($index == 'he_name'){
                    $heName[] = trim($value);
                }elseif ($index == 'he_detail'){
                    $heDetail[] = trim($value);
                }else{
                    $result[$row][$index] = trim($value);
                }
                $totalLen += strlen(trim($value));
            }
            if ($totalLen == 0) unset($result[$row]); //去掉空行
            $result[$row]['he_detail'] = array_map(function($he,$heDtail){
                return ['he_name'=>$he,'he_detail'=>$heDtail];
            },$heName,$heDetail);
        }
        return $result;
    }
    protected function getUomList(){
        $uomList = Service_ProductUom::getKeyVal();
        $this->uomList = $uomList;
        return $this->uomList;
    }

    /**
     * @date 2022/7/16
     * @todo 检测上传单个商品是否有错误信息
     * @auther 46935
     * @param $product
     * @return mixed
     */
    public function validateProduct(&$product){
        if(!$this->uomList){
            $this->getUomList();
        }
        $error =[];
        try {
            $customerCode = $product['customer_code'];
            if(empty($customerCode)){
                throw new Exception("客户代码为空");
            }
            $customerInfo = Service_Customer::getByField($customerCode,'customer_code');
            if(empty($customerInfo)){
                throw new Exception("客户信息不存在");
            }
            $product['customer_id'] = $customerInfo['customer_id'];
            if($product['goods_id']) {
                $productInfo = Service_Product::getByField($product['goods_id'], 'goods_id');
                if (!empty($productInfo)) {
                    $error[] = $product['goods_id'] . '料件号已存在';
                }
            }else{
//                $product['goods_id'] = Service_CustomerProcess::generateGoodsId($customerInfo['customer_id']);
            }
            if(empty($product['product_sku'])){
                $error[]="sku为空";
            }else{
                $checkExit = Service_Product::getByCondition([
                    'product_sku'=>$product['product_sku'],
                    'customer_code'=>$customerInfo['customer_code']
                ]);
                if($checkExit){
                    $error[]="sku已经存在";
                }
            }

            if($product['product_barcode_type'] == '默认条码'){
                $product['product_barcode_type'] = 0;
            }else{
                $product['product_barcode_type'] = 1;
            }
            if($product['product_barcode_type'] == 1) {
                if (empty($product['product_barcode'])) {
                    $error[] = "条码为空";
                } else {
                    $checkExit = Service_Product::getByCondition([
                        'product_sku' => $product['product_barcode'],
                        'customer_code' => $customerInfo['customer_code']
                    ]);
                    if ($checkExit) {
                        $error[] = "产品条码已经存在";
                    }
                }
            }
            if($product['product_status'] == '已备案'){
                $product['product_status'] =1 ;
            }else{
                $product['product_status'] =2 ;
            }
            $uomCode = array_search($product['pu_code'],$this->uomList);
            if(!$uomCode){
                $error[]='产品单位错误';
            }else{
                $product['pu_code'] = $uomCode;
            }
            if($product['product_status'] == 1){
                if(empty($product['hs_code'])){
                    $error[]="海关编码为空";
                }
            }
            if($product['hs_code']){
                $hsUom = Service_HsUom::getByField($product['hs_code'],'hs_code');
                if($product['pu_code_law']){
                    $puCode = array_search($product['pu_code_law'],$this->uomList);
                    if(empty($puCode)){
                        $error[]="法定单位 错误";
                    }else{
                        if($puCode!=$hsUom['pu_code_law']){
                            $error[]="法定单位与系统对应海关编码的法定单位不一致";
                        }else{
                            $product['pu_code_law'] = $puCode;
                        }
                    }
                    if(empty($product['hum_quantity_law'])){
                        $error[]='法定数量为空';
                    }
                }
                if($product['pu_code_second']){
                    $puCode = array_search($product['pu_code_second'],$this->uomList);
                    if(empty($puCode)){
                        $error[]="法二单位 错误";
                    }else{
                        if($puCode!=$hsUom['pu_code_second']){
                            $error[]="法二单位与系统对应海关编码的法二单位不一致";
                        }else{
                            $product['pu_code_second'] = $puCode;
                        }
                    }
                    if(empty($product['hum_quantity_second'])){
                        $error[]='法二数量为空';
                    }
                }
                if($hsUom['pu_code_law']){
                    if(empty($product['pu_code_law'])){
                        $error[]="法定单位 为空";
                    }
                }
                if($hsUom['pu_code_second']){
                    if(empty($product['pu_code_second'])){
                        $error[]="法二单位 为空";
                    }
                }
                $hsElement = Service_HsElement::getByCondition([
                    'hs_code'=>$product['hs_code']
                ]);
                $hsElementMap =[];
                foreach ($hsElement as $he){
                    $hsElementMap[$he['he_id']] = $he['he_name'];
                }
                $newHsElement =[];
                foreach ($product['he_detail'] as $heDetail){
                    $heId =array_search($heDetail['he_name'],$hsElementMap);
                    if($heId){
                        $newHsElement[] =[
                            'he_id'=>$heId,
                            'he_name'=>$heDetail['he_name'],
                            'he_detail'=>$heDetail['he_detail']
                        ];
                    }
                }
                if(count($newHsElement)!=count($hsElementMap)){
                    $error[] ="海关编码".$product['hs_code']."与系统海关申报要素不一致";
                }
                if($product['product_status'] ==1 && empty($newHsElement)){
                    $error[]='已备案商品必须有申报信息';
                }
                $product['he_detail'] = $newHsElement;
            }
            if(in_array($product['with_battery'] ,['否','是'])){
                $product['with_battery'] = array_search($product['with_battery'],['否','是']);
            }else{
                $error[]=“是否带电池错误”;
            }
            if(in_array($product['product_is_qc'] ,['不质检','质检'])){
                $product['product_is_qc'] = array_search($product['product_is_qc'],['不质检','质检']);
            }else{
                $error[]=“质检类型错误”;
            }
            $batteryType =[
                '1'=>'配置电池',
                '2'=>'内置电池',
                '3'=>'纽扣电池',
                '4'=>'锂金属电池',
                '5'=>'离子电池',
                '6'=>'其他',
                '0'=>'不带'
            ];
            if($product['battery_type']){
                if(in_array($product['battery_type'] ,$batteryType)){
                    $product['battery_type'] = array_search($product['battery_type'],$batteryType);
                }else{
                    $error[]=“电池类型错误“;
                }
            }

            $receivingType =[
                '0'=>'新品',
                '1'=>'已收过货产品',
            ];
            if(!in_array($product['product_receive_status'],$receivingType)){
                $error[]="产品接收类型错误";
            }else{
                $product['product_receive_status'] = array_search($product['product_receive_status'],$receivingType);
            }
            if(!empty($product['currency_code'])){
                $check = Service_Currency::getByField($product['currency_code'],'currency_code');
                if(!$check){
                    $error[]='申报币种不存在';
                }
            }
            if(!empty($product['pc_id'])){
                $check = Service_ProductCategory::getByField($product['pc_id'],'pc_name');
                if(!$check){
                    $error[]='产品品类错误';
                }else{
                    $product['pc_id'] = $check['pc_id'];
                }
            }
        }catch (Exception $e){
            $error[]=$e->getMessage();
        }

        $product['error'] = $error;
        return $product;

    }


}