<?php
namespace model\pro;
!defined('BR') && define('BR',"\r\n"); //回车换行符
!defined('XLSBR') && define('XLSBR'," &#10;"); //Excel换行符
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Psr16Cache;
class export extends \model\pro\pro
{
    public $paramsDb;
    public $basename;
    public $captions;
    public $data = [];
    public $pids = [];
    public $cids = [];
    public $dir = '';
	public function __construct(array $options,array $proRows)
    {
        $tag = ((date('H')*1) % 2 == 1) ? '1' : '2';
        $this->paramsDb = new \lib\db(\mvc::$cfg['db']['params_read'][$tag]);
		parent::__construct();
		$this->image = make(\lib\image::class,100);
		$this->dir = \mvc::$cfg['dir']['cache'].'/'.date('Y-m');
		mkdirs($this->dir);
	    $this->basename = $_SESSION['user']['au_name'].'_'.lg('产品目录').'_'.date('Y_m_d').'_'.ucfirst(getOpuser()).''.date('His');
	    $this->tempname = getOpuser().'_'.date('Ymd_His').rand(0,99);
	    $this->sheets = [];
	    $this->paramsData = [];
		$this->captions = [
		                    //列头，列宽
		    'pid'=>         ['ID',50],
		    'state'=>       [lg('状态'),50],
		    'outnum'=>      [lg('GSP型号'),80],
		    'innum'=>       [lg('内部编码'),100],
		    'bigcate'=>     [lg('产品线'),120],
		    'cate'=>        [lg('品名'),120],
		    'sales'=>       [lg('销量'),50],
		    'vio'=>         [lg('保有量'),50],
		    'time'=>        [lg('更新时间'),70],
		    'pic'=>         [lg('图片'),200],
		    'tags'=>        [lg('版本'),200],
		    
		    'g'=>           [lg('G品牌'),100],
		    'ncv'=>         [lg('NCV'),100],
		    'enertek'=>     ['ENERTEK',100],
		    'barcode'=>     ['GSP'.lg('条码'),100],
		    'barcode_g'=>   [lg('G品牌').lg('条码'),100],
		    'barcode_enertek'=>   ['ENERTEK'.lg('条码'),100],

		    'allfacnum'=>     [lg('交叉索引'),360],

		    'pf_name'=>     [lg('搜索号品牌'),360],
		    'pn_number'=>     [lg('搜索号码'),360],
		    'ckresult2'=>     [lg('复核结论'),360],
		    
		    'pml_pos0'=>  [lg('变速箱'),100],
		    'pml_pos1'=>  [lg('前/后轴'),100],
		    'pml_pos6'=>  [lg('前/后'),100],
		    'pml_pos2'=>  [lg('左/右'),100],
		    'pml_pos3'=>  [lg('外/中/内'),100],
		    'pml_pos4'=>  [lg('上/中/下'),100],
		    'pml_pos5'=>  [lg('Complex'),100],
		    'pml_node1'=> [lg('其他车型备注'),100],
		    
		    'pack'=>            [lg('包装方式'),100],
		    'miniqty_sales'=>   [lg('最小起订量'),100],
		    'miniqty_packing'=> [lg('最小装箱只数'),100],
		    'miniqty_trays'=>   [lg('最小托盘只数'),100],
		    'nilongsize'=>      [lg('尼龙袋尺寸'),100],
		    'zhihesize'=>       [lg('纸盒尺寸'),100],
		    'waixiangsize'=>    [lg('外箱尺寸'),100],
		    'zhixiangsize'=>    [lg('托盘尺寸'),100],
		    'danzhong'=>        [lg('单重'),100],
		];
		$this->gspBrandName = [
		    'gsp'=>         2,
		    'innum'=>       3,
		    'g'=>           4,
		    'ncv'=>         5,
		    'enertek'=>     6
		];
		$this->gspBrandKey = array_flip($this->gspBrandName);
		$this->factorys = $this->db->select('pro_factory',['pf_id'=>['pf_name(name)',cateName().'(as)']]);
		$this->areas = $this->db->select('m_area',['ma_id'=>[cateName().'(name)']]);
		foreach ($this->factorys as $k=>$v){
		    $this->factorys[$k]['name'] = htmlentities($v['name']);
		    if($v['as']) $this->factorys[$k]['name'] = $v['as'];
		}
		
		$lgtag = (cateName()=='en_name') ? 'en' : 'cn';
		
        $mcols=[];
	    $this->groupPidByNumidx = ($proRows && $proRows[0] && $proRows[0]['pn_id']);
	    $this->groupPidByModel = (
	        $this->groupPidByNumidx==false 
	        && $options['model'] && $options['model']['hasmodel'] && $options['model']['modelCel']!='rows'
	    );
	    
	    $this->hasModelPos = ($options['model'] && $options['model']['hasmodel'] && $options['model']['modelCel']=='rows' && $options['model']['haspos']);
	    if($options['model']['mcols']){
	        foreach($options['model']['mcols'] as $v){
	            $mcols[$v[0]] = $v[1];
	        }
	    }
        foreach ($proRows as $pk=>$row){
            $pid = $row['p_id'];
            if($this->groupPidByNumidx){
                $pid = $row['p_id'].'-'.$row['pn_id'];
            }
            if($this->groupPidByModel){
                //将车型信息合并成一条
                $pid = explode('-',$pid)[0];
                $modelText = '';
                foreach($mcols as $field=>$caption){
                    if(array_key_exists($field,$row)){
                        if($row[$field]!=''){
                            if(!in_array($field,['mk_name','ms_name','mm_name']) &&count($mcols)>1){
                                if($modelText!='') $modelText .= ', ';
                                $modelText .= $caption.":".$row[$field];
                            }else{
                                $modelText .= $row[$field].' ';
                            }
                        }
                    }
                }
                if($modelText!=''){
                    if($options['model']['modelCel']=='one' && isset($this->data[$pid]['model'])){
                        ;
                    }else{
                        if(isset($this->data[$pid]['model'])){
                            $this->data[$pid]['model'] .= XLSBR;
                        }
                        $this->data[$pid]['model'] .= $modelText;
                    }
                }
            }else{
                $pid = $row['p_id'].'-'.$row['mm_id'];
                foreach($row as $k=>$v){
                    if(substr($k,0,3)=='mm_' || in_array($k,['mk_name','ms_name','mm_name','year'])){
                        $this->data[$pid][$k] = $v; 
                    }
                }
                if($this->hasModelPos){
                    foreach($row as $k=>$v){
                        if(substr($k,0,4)=='pml_'){
                            $this->data[$pid][$k] = $v; 
                        }
                    }
                }
            }
            if(!isset($this->data[$pid])) $this->data[$pid] = [];
            $newRow = [
                'pid'=> $pid,
                'cid'=> $row['p_cate'],
                'state'=> $row['p_state_main'],
                'outnum'=> $row['p_outnum'],
                'innum'=> $row['p_innum'],
                'bigcate'=> $row['langs']['p_bigcate'][$lgtag],
                'cate'=> $row['langs']['p_cate'][$lgtag],
                'sales'=> $row['p_sales_qty'],
                'vio'=> $row['p_vio'],
                'time'=> $row['update_time'],
                'pic'=> $row['p_pic'],
                'tags'=> $row['link_tags']
            ]; 
            if($this->groupPidByNumidx){
                $newRow['pf_name'] = ($row['pf_alias']) ?: $row['pf_name'];
                $newRow['pn_number'] = $row['pn_number'];
                $newRow['ckresult2'] = $row['ckresult2'];
            }
            $this->data[$pid] = array_merge($newRow,$this->data[$pid]);
            
            $this->pids[$pid] = true;
            $this->cids[$row['p_cate']] = true;
            unset($proRows[$k]); //节省内存
        }
        //dd($this->data);
        //号码维度
        if($options['numbers']){
            $numbers = preg_split('/[\n|,]/',$options['numbers']);
            $data = array_merge([],$this->data);
            $this->data = [];
            $this->pids = [];
            $this->cids = [];
            foreach($numbers as $i=>$number){
                $format = formatNum($number);
                $has = false;
                foreach($data as $pid => $row){
                    //dump($number.'=>'.$pid);
                    if($options['model']['modelCel']=='more'){
                        //如果 不是车型合并一行
                        $pid = explode('-',$pid)[0];
                    }
                    
                    if($format == formatNum($row['pn_number']) || $format == formatNum($row['outnum']) || $format == formatNum($row['innum'])){
                        //将车型信息合并成一条
                        $modelText = '';
                        if($options['model']['hasmodel']){
                            foreach($mcols as $field=>$caption){
                                if(array_key_exists($field,$row)){
                                    if($row[$field]!=''){
                                        if(!in_array($field,['mk_name','ms_name','mm_name']) &&count($mcols)>1){
                                            if($modelText!='') $modelText .= ', ';
                                            $modelText .= $caption.":".$row[$field];
                                        }else{
                                            $modelText .= $row[$field].' ';
                                        }
                                    }
                                }
                            }
                        }
                        if($options['model']['modelCel']=='more'){
                            if(isset($this->data[$pid]) && isset($this->data[$pid]['model'])){
                               $row['model'] =  $this->data[$pid]['model'] . XLSBR .$modelText;
                            }else{
                                $row['model'] = $modelText;
                            }
                        }else if($options['model']['modelCel']=='one'){
                             $row['model'] = $modelText;
                        }
                        
                        $this->data[$pid] = $row;
                        $this->pids[$pid] = true;
                        $this->cids[$row['cid']] = true;
                        $has = true;
                        if(false==$options['model']['hasmodel'] || $options['model']['modelCel']=='one'){
                            //没有车型 或者  只取一条车型
                            break;
                        }
                        
                    }
                }
                if(!$has){
                    $pid = '-'.$i.'-0';
                    $this->pids[$pid] = true;
                    $this->data[$pid] = ['pid'=>$pid,'pn_number'=>trim($number)];
                }
            }
            unset($data);
        }
        //dd($this->data);
        $this->pids = array_keys($this->pids);
        $this->cids = array_keys($this->cids);
        $this->paramids = [];
        $this->cateParams = [];
        //品名与参数权限
        $pwCates = \p::cates('1100');
        if(!\p::isAdmin() && $pwCates!=''){
            $pwCates = explode(',',$pwCates);
            $this->cids = array_intersect($this->cids,$pwCates);
            foreach($this->cids as $cid){
                $t = \p::params('1100',$cid);
                if($t){
                    $this->paramids[$cid] = explode(',',$t);
                }
            }
            
        }
	}
	
	function setDataByPid($pid,$field,$var,$type='',$joinstr=', '){
	    $keys = explode('.',$field);
	    $k1 = $keys[0];
	    $k2 = (isset($keys[1]) && $keys[1]!='') ? $keys[1] : '';
	    if($k2!=''){
    	    if(isset($this->data[$pid])){
    	        if($type=='push'){
    	            $this->data[$pid][$k1][$k2][] = $var;
    	        }else if($type=='join'){
    	            if(isset($this->data[$pid][$k1][$k2])){
    	                $this->data[$pid][$k1][$k2] .= $joinstr . $var;
    	            }else{
    	                $this->data[$pid][$k1][$k2] = $var;
    	            }
    	        }else{
    	            $this->data[$pid][$k1][$k2] = $var;
    	        }
    	    }else{
        	    foreach($this->data as $key => $v){
        	        $_pid = explode('-',$key)[0];
        	        if($_pid == $pid){
            	        if($type=='push'){
            	            $this->data[$key][$k1][$k2][] = $var;
            	        }else if($type=='join'){
            	            if(isset($this->data[$key][$k1][$k2])){
            	                $this->data[$key][$k1][$k2] .= $joinstr . $var;
            	            }else{
            	                $this->data[$key][$k1][$k2] = $var;
            	            }
            	        }else{
            	            $this->data[$key][$k1][$k2] = $var;
            	        }
        	        }
        	    }
    	    }
	    }else{
    	    if(isset($this->data[$pid])){
    	        if($type=='push'){
    	            $this->data[$pid][$k1][] = $var;
    	        }else if($type=='join'){
    	            if(isset($this->data[$pid][$k1])){
    	                $this->data[$pid][$k1] .= $joinstr . $var;
    	            }else{
    	                $this->data[$pid][$k1] = $var;
    	            }
    	        }else{
    	            $this->data[$pid][$k1] = $var;
    	        }
    	    }else{
        	    foreach($this->data as $key => $v){
        	        $_pid = explode('-',$key)[0];
        	        if($_pid == $pid){
            	        if($type=='push'){
            	            $this->data[$key][$k1][] = $var;
            	        }else if($type=='join'){
            	            if(isset($this->data[$key][$k1])){
            	                $this->data[$key][$k1] .= $joinstr . $var;
            	            }else{
            	                $this->data[$key][$k1] = $var;
            	            }
            	        }else{
            	            $this->data[$key][$k1] = $var;
            	        }
        	        }
        	    }
    	    }
	    }
	    
	}
	
	/**
	 * 补充数据
	 */
	function addData($options){
	    $pidsChunk = array_chunk($this->pids,500); //分隔成500条一次处理
	    
	    //所有交叉号
	    if($options['allfacnum']){
            foreach($pidsChunk as $pids){
               $this->allfacnum($pids);
            }
	    }
	    //GSP集团品牌号码, OE, 条码  和 竞品号
	    if($options['gspnum'] || $options['barcode'] || $options['barcode_g'] || $options['barcode_enertek'] || $options['fac'] || $options['oe']['qty']>0){
	        $bands = [];
	        if($options['oe']['qty']>0){
	            $bands[] = 1; //加入OE
	        }
	        if($options['barcode']){
	            $bands[] = 2; //加入gsp
	        }
	        if($options['barcode_g']){
	            $bands[] = 4; //加入g
	        }
	        if($options['barcode_enertek']){
	            $bands[] = 6; //加入enerte
	        }
	        foreach($options['gspnum'] as $name){ //集团品牌
	           if($name!='innum'){ //不需要找内部编码
	               $bands[] = $this->gspBrandName[$name];
	           }
	        }
	        if($options['fac']){ //竞品号
	            $bands = array_merge($bands,$options['fac']);
	        }
	        if($bands){
	            $bands = array_unique($bands);
                foreach($pidsChunk as $pids){
                   $this->getGspNum($pids,$bands,$options);
                }
	        }
	    }
	    //包装
	    if($options['pack']){
            foreach($pidsChunk as $pids){
               $this->getPack($pids);
            }
	    }
	    //参数
	    if($options['param']){
	        $this->getParam($pidsChunk);
	    }
	    
	    //车型
	    if($options['model'] && $options['model']['hasmodel']){
	        $this->getModel($pidsChunk);
	    }
	}
	
	/**
	 * 字段组装
	 */
	function impField($options){
	    $fields = [];
	    //号码维度
	    if($this->groupPidByNumidx){
	        array_push($fields,'pn_number');
	        array_push($fields,'pf_name');
	        array_push($fields,'ckresult2');
	    }
	    $fields = array_merge($fields,['bigcate','cate','state','outnum']);
	    //所有交叉号
	    if($options['allfacnum']){
	        array_push($fields,'allfacnum');
	    }
	    //集团品牌
	    if($options['gspnum']){
    	    $fields = array_merge($fields,$options['gspnum']);
	    }
	    //竞品号
	    if($options['fac']){
	        foreach($options['fac'] as $v){
	            array_push($fields,$this->factorys[$v]['name']);
	        }
	    }
	    
	    //OE
	    if($options['oe']['qty']>0){
	        if($options['oe']['iscols']){
    	        for($i=1;$i<=$options['oe']['qty'];$i++){
    	            array_push($fields,'OE'.$i);
    	        }
	        }else{
	            array_push($fields,'OE');
	        }
	    }
	    //车型
	    if($options['model'] && $options['model']['hasmodel']){
	        if($options['model']['modelCel']=='rows'){
    	        foreach($options['model']['mcols'] as $v){
    	            array_push($fields,$v[0]);
    	            $this->captions[$v[0]] = [$v[1],100];
    	        }
	        }else{
	            array_push($fields,'model');
	        }
	    }
	    //车型位置
        if($this->hasModelPos){
            $fields = array_merge($fields,['pml_pos0','pml_pos1','pml_pos6','pml_pos2','pml_pos3','pml_pos4','pml_pos5','pml_node1']);
        }
	    //条码
	    if($options['barcode']){
            array_push($fields,'barcode');
	    }
	    if($options['barcode_g']){
            array_push($fields,'barcode_g');
	    }
	    if($options['barcode_enertek']){
            array_push($fields,'barcode_enertek');
	    }
	    //销量
	    if($options['sales']){
            array_push($fields,'sales');
	    }
	    //保有量
	    if($options['vio']){
            array_push($fields,'vio');
	    }
	    //包装
	    if($options['pack']){
            $fields = array_merge($fields,[
                'pack','miniqty_sales','miniqty_packing','miniqty_trays','nilongsize','zhihesize','waixiangsize','zhixiangsize','danzhong'
            ]);
	    }
	    $this->sheets['base'] = ['caption'=>lg('目录'),'fields'=>$fields];
	    //找出相同参数的品类
	    $this->uniq = [];
	    $this->uniqCates = [];
	    foreach($this->cateParams as $cid=>$arr){
	        $key = md5(serialize($arr));
	        $this->uniq[$cid] = $key;
	        $this->uniqCates[$key][] = $cid; 
	    }
	    
	    foreach($this->data as $pid=>$row){
	        //竞品号
	        if(isset($row['numidx'])){
	            foreach($row['numidx'] as $k=>$v){
	                $this->data[$pid][$k] = $v;
	            }
	            unset($this->data[$pid]['numidx']);
	        }
	        //OE
	        if($options['oe']['qty']>0 && isset($row['OE'])){
	            //OE分列
	            if($options['oe']['iscols']){
	                for($i=1;$i<=$options['oe']['qty'];$i++){
	                    if(isset($row['OE'][$i-1])){
	                        $this->data[$pid]['OE'.$i] = $row['OE'][$i-1];
	                    }else{
	                        break;
	                    }
	                }
                    unset($this->data[$pid]['OE']);
	            }else{
	                //OE合并
	                $oe = '';
	                for($i=1;$i<=$options['oe']['qty'];$i++){
	                    if(isset($row['OE'][$i-1])){
	                        if($oe!='') $oe .= ','.XLSBR;
	                        $oe .= $row['OE'][$i-1];
	                    }else{
	                        break;
	                    }
	                }
	                $this->data[$pid]['OE'] = $oe;
	            }
	        }
	        //参数
	        if(isset($row['params'])){
	            $param = $row['params'];
	            unset($this->data[$pid]['params']);
	            $param = array_merge($this->data[$pid],$row['params']);
	            $this->paramsData[$this->uniq[$row['cid']]][] = $param;
	        }
	    }
	}
	
	//参数
	function getParam_beta(array &$pidsChunk){
	    if(empty($this->getParam_set)){
            $this->getParam_set = $this->db->select('gsp_part_param',
                ['ptpa_id'=>['ptpa_id','ptpa_pc_id',cateName().'(name)','ptpa_type','ptpa_decimal']],
                ['ptpa_pc_id'=>$this->cids]
            );
            foreach($this->getParam_set as $k=>$row){
                $cid = $row['ptpa_pc_id'];
                $ptpaid = $row['ptpa_id'];
                if(!isset($this->paramids[$cid]) || in_array($ptpaid,$this->paramids[$cid])){
                    $this->getParam_set[$k]['vfield'] = 'ppv_val_'.$this->paramType[$row['ptpa_type']];
                    $this->cateParams[$cid][] = htmlentities($row['name']);
                }
            }
	    }
	    foreach($this->pids as $pid){
	        $cateLinkPids[$this->data[$pid]['cid']][] = trim($pid,'-');
	    }
	    foreach($cateLinkPids as $cate_id=>$pids){
	        $chunks = array_chunk($pids,500); //分隔成500条一次处理
	        foreach($chunks as $chunkpids){
	            $paramRows = $this->paramsDb->select('cate_'.$cate_id,'*',['pro_id'=>$chunkpids]);
	            $HasNames=[];
	            $hasPids = [];
	            foreach($paramRows as $paramRow){
	                $pid = $paramRow['pro_id'];
	                foreach($paramRow as $field=>$value){
	                    $arr = explode('_',$field);
	                    $ptpaid = (isset($arr[1]) && is_numeric($arr[1])) ? $arr[1]: '';
	                    if($ptpaid){
	                        $name = htmlentities($this->getParam_set[$ptpaid]['name']);
	                        $this->setDataByPid($pid,'params.'.$name,$value);
	                        $HasNames[] = $name;
	                        $hasPids[] = $pid;
	                    }
	                }
	            }
	            /*
	            $diff=array_diff($chunkpids,$hasPids);
                if($HasNames){
                    foreach($diff as $pid){
                        foreach($HasNames as $name){
                            $this->setDataByPid($pid,'params.'.$name,'');
                        }
                    }
                }*/
	        }
	    }
	}
	function getParam(array &$pidsChunk){
        $sets = $this->db->select('gsp_part_param',
            ['ptpa_id'=>['ptpa_id','ptpa_pc_id',cateName().'(name)','ptpa_type','ptpa_decimal']],
            ['ptpa_pc_id'=>$this->cids]
        );
        foreach($sets as $k=>$row){
            $cid = $row['ptpa_pc_id'];
            $ptpaid = $row['ptpa_id'];
            if(!isset($this->paramids[$cid]) || in_array($ptpaid,$this->paramids[$cid])){
                $sets[$k]['vfield'] = 'ppv_val_'.$this->paramType[$row['ptpa_type']];
                $this->cateParams[$cid][] = htmlentities($row['name']);
            }
        }
        foreach($pidsChunk as $pids){
            foreach($pids as $k=>$v) $pids[$k] = trim($v,'-');
            $hasPids = [];
            $HasNames=[];
            $paramRows = $this->db->select('gsp_pro_param_val','*',['ppv_p_id'=>$pids]);
            foreach($paramRows as $paramRow){
                $pid = $paramRow['ppv_p_id'];
                $cid = $paramRow['ppv_pc_id'];
                $ptpaid = $paramRow['ppv_ptpa_id'];
                if(!isset($this->paramids[$cid]) || in_array($ptpaid,$this->paramids[$cid])){
                    $vfield = $sets[$ptpaid]['vfield'];
                    $name = htmlentities($sets[$ptpaid]['name']);
                    $value = $paramRow[$vfield];
                    if($vfield=='ppv_val_double'){
                        $value = round($value,$sets[$ptpaid]['ptpa_decimal']);
                    }
                    $this->setDataByPid($pid,'params.'.$name,$value);
                    if(!in_array($pid,$hasPids)) $hasPids[] = $pid;
                    $HasNames[] = $name;
                }
            }
            /*
            $diff=array_diff($pids,$hasPids);
            if($HasNames){
                foreach($diff as $pid){
                    foreach($HasNames as $name){
                        $this->setDataByPid($pid,'params.'.$name,'');
                    }
                }
            }*/
        }
	}
	
	//所有交叉号
	function allfacnum(array $pids){
	    $join['[>]pro_factory'] = ['pn_pf_id'=>'pf_id'];
        $rows = $this->db->select('pro_numidx',$join,'*',['pn_p_id'=>$pids,'pn_is_gsp'=>0,'ckresult2'=>NUMIDX_CKRESULT2_OK,'ORDER'=>['pf_name']]);
        $data = [];
        foreach($rows as $row){
            if(isset($data[$row['pn_p_id']])) 
                $data[$row['pn_p_id']] .= XLSBR;
            else
                $data[$row['pn_p_id']] = '';
            $data[$row['pn_p_id']] .= $row['pf_name'].': '. $row['pn_number'];
        }
        foreach($data as $pid=>$allfacnum){
            $this->setDataByPid($pid,'allfacnum',$allfacnum);
        }
	}
	
	//车型
	function getModel(array $pids){
        ;
	}
	
	//包装
	function getPack(array $pids){
        $rows = $this->db->select('pro_pack','*',['pp_id'=>$pids]);
        foreach($rows as $row){
            foreach($row as $k=>$v){
                $pid = $row['pp_id'];
                if(!in_array($k,['pp_id','update_time','create_time'])){
                    $this->setDataByPid($pid,$k,$v);
                }
            }
        }
	}
	
	//GSP集团品牌号码, OE 和 条码
	function getGspNum(array $pids, array $bands,$options){
        $rows = $this->db->select('pro_numidx',['pn_p_id','pn_pf_id','pn_number','pn_ma_id','pn_barcode','ckresult2'],['pn_p_id'=>$pids,'pn_pf_id'=>$bands]);
        foreach($rows as $row){
            $pid = $row['pn_p_id'];
            $number = $row['pn_number'];
            if($row['pn_pf_id']==1){ //OE
                if($row['ckresult2']==NUMIDX_CKRESULT2_OK){
                    $this->setDataByPid($pid,'OE',$number,'push');
                }
            }else{
                //非OE
                $band = $this->gspBrandKey[$row['pn_pf_id']];
                if($band){
                    //区域
                    if($row['pn_ma_id']){
                        $number = $number.':'.$this->areas[$row['pn_ma_id']]['name'];
                    }
                    //多个区域号码
                    $this->setDataByPid($pid,$band,$number,'join',XLSBR);
                    if($row['pn_barcode']){
                        if($row['pn_pf_id']==2 && $options['barcode']){
                            $this->setDataByPid($pid,'barcode',$row['pn_barcode']);
                        }
                        if($row['pn_pf_id']==4 && $options['barcode_g']){
                            $this->setDataByPid($pid,'barcode_g',$row['pn_barcode']);
                        }
                        if($row['pn_pf_id']==6 && $options['barcode_enertek']){
                            $this->setDataByPid($pid,'barcode_enertek',$row['pn_barcode']);
                        }
                    }
                }else{
                    //竞品号
                    if($row['ckresult2']==NUMIDX_CKRESULT2_OK){ //复核结论为OK的记录
                        $fac = $this->factorys[$row['pn_pf_id']]['name'];
                        $this->setDataByPid($pid,$fac,$number,'join');
                    }
                }
            }
        }
    }
	function xlsx2($options){
	    $this->addData($options);
	    $this->impField($options);
	    $cateObj = makeOne(\model\pro\cate::class);
        $fp = fopen('php://output','w');
        $excel = new \lib\exportXlsx($fp,\mvc::$cfg['dir']['cache']);
        $excel->header();
        $excel->bookBegin();
        
        $eheader = [];
        foreach($this->sheets['base']['fields'] as $field){
            $eheader[] = isset($this->captions[$field]) ? $this->captions[$field][0] : strtoupper($field);
        }
        $excel->sheetBegin(lg('基本资料'),$eheader);
        foreach($this->data as $row){
            $erow = [];
            foreach($this->sheets['base']['fields'] as $field){
                $erow[] = isset($row[$field]) ? $row[$field] : '';
            }
            $excel->append($erow);
        }
        $excel->sheetEnd();
        
        if($this->paramsData){
            foreach($this->paramsData as $uniq=>$rows){
                $cid = $this->uniqCates[$uniq][0];
                $cname = ($crow = $cateObj->getRowByKey($cid)) ? $crow[cateName()] : 'sheet';
                $paramFields = $this->cateParams[$cid];
                $fields = array_merge($this->sheets['base']['fields'],$paramFields);
                $eheader = [];
                foreach($fields as $field){
                    $eheader[] = isset($this->captions[$field]) ? $this->captions[$field][0] : strtoupper($field);
                }
                $excel->sheetBegin($cname,$eheader);
                foreach($rows as $row){
                    $erow = [];
                    foreach($fields as $field){
                        $erow[] = isset($row[$field]) ? $row[$field] : '';
                    }
                    $excel->append($erow);
                }
                $excel->sheetEnd();
            }
        }
        $excel->bookEnd();
        fclose($fp);
	}
	
	function xlsx($options){
	    $this->addData($options);
	    $this->impField($options);
	    $cateObj = makeOne(\model\pro\cate::class);
        ob_end_clean();
        header('Content-Description: File Transfer');
        header("Content-type:application/vnd.ms-excel");
        header('Content-Disposition: attachment; filename='.$this->basename.'.xlsx');
        error_reporting(0);
        echo '<?xml version="1.0"?>'.BR;
        echo '<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">'.BR;
        echo '<ss:Styles>'.BR;
        echo    '<ss:Style ss:ID="1">'.BR;
        echo        '<ss:Font ss:Bold="1"/>'.BR;
        echo    '</ss:Style>'.BR;
        echo '</ss:Styles>'.BR;
        $this->outputSheet($this->sheets['base']['fields'],$this->data,$this->sheets['base']['caption']);
        if($this->paramsData){
            foreach($this->paramsData as $uniq=>$rows){
                $cid = $this->uniqCates[$uniq][0];
                $cname = ($crow = $cateObj->getRowByKey($cid)) ? $crow[cateName()] : 'sheet';
                $paramFields = $this->cateParams[$cid];
                $fields = array_merge($this->sheets['base']['fields'],$paramFields);
                $this->outputSheet($fields,$rows,$cname);
            }
        }
        echo '</ss:Workbook>'.BR;
        ob_end_flush();
        exit();
	}
    public function specialchars($value){
        return str_replace('&amp;','&',htmlspecialchars($value));
    }
	
	//输出一个Sheet
	public function outputSheet($fields,$data,$sheetName){
        echo '<ss:Worksheet ss:Name="'.$sheetName.'">'.BR;
        echo '<ss:Table>'.BR;
        foreach($fields as $field){
            $width = isset($this->captions[$field]) ? $this->captions[$field][1] : 100;
            echo '<ss:Column ss:Width="'.$width.'"/>'.BR;
        }
        echo '<ss:Row ss:StyleID="1">'.BR;
        foreach($fields as $field){
            $caption = isset($this->captions[$field]) ? $this->captions[$field][0] : strtoupper($field);
            echo '<ss:Cell><ss:Data ss:Type="String">'.$caption.'</ss:Data></ss:Cell>'.BR;
        }
	    echo '</ss:Row>'.BR;
		foreach($data as $row){
            echo '<ss:Row>'.BR;
            foreach($fields as $field){
                $value = isset($row[$field]) ? $row[$field] : '';
                if($field!='pic'){
    	            echo '<ss:Cell><ss:Data ss:Type="String">'.$this->specialchars($value).'</ss:Data></ss:Cell>'.BR;
                }
		    }
    	    echo '</ss:Row>'.BR;
            flush();
            ob_flush();
		}
        echo '</ss:Table>'.BR;
        echo '</ss:Worksheet>'.BR;
	}
	
	//导出带图片 xlsx
	//$haspic 是否导出图片
	public function imgxlsx($options,$haspic=false){
	    $this->addData($options);
	    $this->impField($options);
	    $band = $options['img']['brand'];
	    $size = 'mid';//$options['img']['size'];
	    $fields = $this->sheets['base']['fields'];
	    if($haspic){
	        array_unshift($fields,'pic');
	    }
	    $excel  = new \Vtiful\Kernel\Excel(['path' => $this->dir]);
	    $header = [];
        foreach($fields as $field){
            $caption = isset($this->captions[$field]) ? $this->captions[$field][0] : strtoupper($field);
            $header[] = $caption;
        }
        $xlsfile = $excel->fileName($this->tempname.".xlsx")
            ->header($header);
            
        //头样式
        $fileHandle = $xlsfile->getHandle();
        $format    = new \Vtiful\Kernel\Format($fileHandle);
        $boldStyle = $format->bold()
                    ->background(0x002F5F)
                    ->fontColor(0xFFFFFF)
                    ->toResource();
        //自动换行           
        $format    = new \Vtiful\Kernel\Format($fileHandle);
        $wrapStyle = $format->wrap()->toResource();  
        
        //列宽
        $r = 0;
        $c=0;
        $maxColLabel = 'A';
        foreach($header as $v){
            $maxColLabel = int2Excel($c);//chr(ord('A')+$c);
            $xlsfile->setColumn($maxColLabel.$r.':'.$maxColLabel.$r,20);
            $c++;
        }
        if($haspic){
            $xlsfile->setColumn('A0:A0',22);
        }
          
        $r = 0;
        $modelColIndex = 0;
        $wrapCols = [];
        foreach($this->data as $row){
            $r++;
            foreach($fields as $c => $field){
                if($field!='pic'){
                    $value = $row[$field];
                    $value = str_replace(XLSBR," \r\n",$value);
                    $xlsfile->insertText($r, $c, $value);
                }
                if(in_array($field,['model','allfacnum'])){
                    if(!in_array($c,$wrapCols))
                        array_push($wrapCols,$c);
                }
            }
            if($haspic && $row['pic']){
                $imgfilename = $this->getProImageFile('xlsx',$row,$band,$size);
                if($imgfilename){
                    $xlsfile->insertImage($r, 0, $imgfilename,0.47,0.47);
                    $xlsfile->setRow('A'.($r+1).':'.'A'.($r+1),90);
                }
            }        
        }
        foreach($wrapCols as $c){
             $xlsfile->setColumn(int2Excel($c).':'.int2Excel($c), 360, $wrapStyle);
        }
        
        if($this->paramsData){
    	    $cateObj = makeOne(\model\pro\cate::class);
    	    $cateNames = [];
            // 添加参数工作表
            foreach($this->paramsData as $uniq=>$paramRows){
                $cid = $this->uniqCates[$uniq][0];
                $paramFields = $this->cateParams[$cid];
                $paramFields = array_merge($this->sheets['base']['fields'],$paramFields);
                if(!isset($cateNames[$cid])){
                   $cateNames[$cid] = ($crow = $cateObj->getRowByKey($cid)) ? $crow[cateName()] : 'sheet';
                }
                $sheetName = $cateNames[$cid];
                $sheetHeader = [];
                $sheetData = [];
                foreach($paramFields as $paramField){
                    $caption = isset($this->captions[$paramField]) ? $this->captions[$paramField][0] : strtoupper($paramField);
                    array_push($sheetHeader,$caption);
                }
                foreach($paramRows as $paramRow){
                    $arr = [];
                    foreach($paramFields as $paramField){
                        $value = isset($paramRow[$paramField]) ? $paramRow[$paramField] : '';
                        $value = str_replace(XLSBR," \r\n",$value);
                        array_push($arr,$value);
                    }
                    array_push($sheetData,$arr);
                }
                $excel->addSheet($sheetName)
                    ->header($sheetHeader)
                    ->data($sheetData);
                $xlsfile->setRow('A0', 16, $boldStyle);
                //$excel->autoFilter('A0:'.chr(ord('A')+count($paramFields)-1).'0');
                $excel->autoFilter('A0:'.int2Excel(count($paramFields)-1).'0');
                foreach($paramFields as $c =>$v){
                    $xlsfile->setColumn(int2Excel($c).$r.':'.int2Excel($c).$r,20);
                }
            }
        }
        
        //头样式和自动筛选
        $excel->checkoutSheet('Sheet1');
        $xlsfile->setRow('A0', 16, $boldStyle);
        $excel->autoFilter('A0:'.$maxColLabel.'0');
        
        $xlsfile->output();
        $excel->close();
        $filename = $this->dir.'/'.$this->tempname.".xlsx";
        ob_end_clean();
        header('Content-Description: File Transfer');
        header("Content-type:application/vnd.ms-excel");
        header('Content-Disposition: attachment; filename='.$this->basename.'Photo.xlsx');
        header("Content-Length:".filesize($filename));
        error_reporting(0);
        readfile($filename);
        ob_end_flush();
        unlink($filename);
        exit();
	}
	
	//导出图片zip
	public function imgzip($options){
	    $band = $options['img']['brand'];
	    $size = $options['img']['size'];
	    $fid = $options['img']['fid'];
        $zipfile = $this->dir.'/'.$this->tempname.".zip";
        $zip = new \ZipArchive(); //linux需开启zlib,windows需php_zip.dll
        if ($zip->open ($zipfile, \ZIPARCHIVE::CREATE ) !== true) {
           throw new \Exception ('生成压缩文件失败,请检查相关目录权限');
        }
	    $hasPic = false;
        foreach($this->data as $row){
            if($row['pic']){
                $imgfilename = $this->getProImageFile('zip',$row,$band,$size);
                if($imgfilename){
                    $showfilename = ($fid=='2') ? $row['outnum'] : $row['innum'];
                    $zip->addfile($imgfilename,$showfilename.'.jpg');
                    $hasPic = true;
                }
            }            
        }
        $zip->close();
        if(!$hasPic){
            unlink($zipfile);
            exit(lg('没有图片数据'));
        }
        ob_end_clean();
        header('Content-Description: File Transfer');
        header("Content-type:application/vnd.ms-excel");
        header('Content-Disposition: attachment; filename='.$this->basename.'Photo.zip');
        header("Content-Length:".filesize($zipfile));
        error_reporting(0);
        readfile($zipfile);
        ob_end_flush();
        unlink($zipfile);
        exit();
	}
	
	public function getImgFileByWater($band,$srcFilename,$distFilename){
		$watermark = \mvc::$cfg['dir']['static'].'/images/watermark/pro/'.$band.'.png';
		$dist = \mvc::$cfg['dir']['cache'].'/pdf_temp_jpg/'.basename($distFilename);
		if(file_exists($watermark) && file_exists($srcFilename)){
			$this->image->Watermark($srcFilename,$distFilename,$watermark);
		}
		return $distFilename;
	}
	
	public function getProImageFile($type,$row,$band,$size){
        $pid = explode('-',$row['pid'])[0];
        $dist = \mvc::$cfg['dir']['cache'].'/pdf_temp_jpg/export_'.$pid.'.jpg';
        $result = '';
        if(in_array($row['cid'],[148,149,151,153])!==false){
            //外球笼,内球笼,高速节球笼,修理包
            $join['[><]files'] = ['pro_pic.ppic_fileid'=>'fileid']; 
            $where = [
                'ppic_p_id'=>$pid,
                'ppic_type'=>'notcattle',
                'ppic_innum'=>raw('ppic_filebase'),
            ];
            $filename = $this->db->get('pro_pic',$join,'filename',$where);
            $src = \mvc::$cfg['dir']['files']. '/'.$filename;

            if($band == 'tecdoc'){ //无水印
                if(empty($filename)) return '';
                if(!file_exists($src)) return '';
                if($type=='xlsx'){
                    $this->image->Resize($src,$dist,320,240);
                    $src = $dist;
                }
                $result = $src;
            }else if($band == 'catalog_gsp'){
                if($type=='xlsx'){
                    $size = 'mid';
                }
                $result = \mvc::$cfg['dir']['files'].'/pro/'.$band.'/'.($pid % 100).'/'.$pid.$size.'.jpg';
            }else{
                if(empty($filename)) return '';
                if(!file_exists($src)) return '';
                if($type=='xlsx'){
                    $this->image->Resize($src,$dist,320,240);
                    $src = $dist;
                }
                //动态水印
                $result = $this->getImgFileByWater($band,$src,$dist);
            }
            //dd($imgfilename);
        }else{
            if($type=='xlsx'){
                $size = 'mid';
            }
            $src = \mvc::$cfg['dir']['files'].'/pro/tecdoc/'.($pid % 100).'/'.$pid.$size.'.jpg';
            if($band=='catalog_enertek'){
                //动态水印
                $result = $this->getImgFileByWater($band,$src,$dist);
            }else{
                $result = \mvc::$cfg['dir']['files'].'/pro/'.$band.'/'.($pid % 100).'/'.$pid.$size.'.jpg';
            }
        }
        return $result;
	}
}