<?php
namespace model\pro;
class image extends \model
{
    public $options;
	public function __construct()
    {
		parent::__construct();
		$this->fileroot = \mvc::$cfg['dir']['files'];
		$this->image = make(\lib\image::class,100);
		$this->pro = make(\model\pro\pro::class);
		$this->files = make(\model\files::class);
		
		$oy = 465;
        $oj = 28;
        $this->captions = [
            'init_add' => lg('上传原始照片'),
            'init_check' => lg('原始图审核'),
            'init_back' => lg('退回-原始图'),
            'init_replay' => lg('重拍-原始图'),
            'beautify_add' => lg('上传精修图'),
            'beautify_check' => lg('精修图审核'),
            'beautify_back' => lg('退回-精修图'),
            'beautify_replay' => lg('重拍-精修图'),
        ];
		$this->options = [
            'types'=> [
                ['key'=>'init_add','caption'=>lg('上传原始照片'), 'uploadType'=>'init_add', 'pwcode'=>'D311'
                    , 'op'=>['add','remove','import'],'offset'=>[25,200],'class'=>''],
                ['key'=>'init_check','caption'=>lg('原始图审核'), 'uploadType'=>'init_add', 'pwcode'=>'D320'
                    , 'op'=>['check'],'offset'=>[192,200],'class'=>''],
                ['key'=>'init_back','caption'=>lg('退回-原始图'), 'uploadType'=>'init_add','short'=>lg('退回'), 'pwcode'=>'D341'
                    , 'op'=>['remove','delete'],'offset'=>[210,65],'class'=>'xytow'],
                //['key'=>'init_del','caption'=>lg('删除-原始图'), 'uploadType'=>'init_add','short'=>'删除', 'pwcode'=>'D311|D320'
                    //, 'op'=>['delete'],'offset'=>[210,84],'class'=>'xytow'],
                ['key'=>'init','caption'=>lg('原始照片库'), 'uploadType'=>'init', 'pwcode'=>'D301'
                    , 'op'=>['add','remove','delete','readd','import','export'],'offset'=>[376,163],'class'=>''],
                ['key'=>'designer','caption'=>lg('设计师'), 'uploadType'=>'init', 'pwcode'=>'D303'
                    , 'op'=>['export'],'offset'=>[386,237],'class'=>''],
                
                ['key'=>'beautify_add','caption'=>lg('上传精修图'), 'uploadType'=>'beautify_add', 'pwcode'=>'D330'
                    , 'op'=>['add','remove','import'],'offset'=>[375,375],'class'=>''],
                ['key'=>'beautify_check','caption'=>lg('精修图审核'), 'uploadType'=>'beautify_add', 'pwcode'=>'D360'
                    , 'op'=>['export'],'offset'=>[192,375],'class'=>''],
                ['key'=>'beautify_back','caption'=>lg('退回-精修图'),'short'=>lg('退回'), 'uploadType'=>'beautify_add', 'pwcode'=>'D342'
                    , 'op'=>['export'],'offset'=>[210,507],'class'=>'xytow'],
                ['key'=>'beautify','caption'=>lg('精修照片库'), 'uploadType'=>'beautify', 'pwcode'=>'D302'
                    , 'op'=>['export'],'offset'=>[29,375],'class'=>''],
                
                ['key'=>'catalog_gsp','caption'=>lg('GSP'), 'uploadType'=>'', 'pwcode'=>'D312'
                    , 'op'=>['export'],'offset'=>[25,$oy + $oj * 0],'class'=>''],
                ['key'=>'catalog_g','caption'=>lg('G品牌'), 'uploadType'=>'', 'pwcode'=>'D313'
                    , 'op'=>['export'],'offset'=>[25,$oy + $oj * 1],'class'=>''],
                ['key'=>'tecdoc','caption'=>lg('TECDOC'), 'uploadType'=>'', 'pwcode'=>'D314'
                    , 'op'=>['export'],'offset'=>[25,$oy + $oj * 2],'class'=>''],
                ['key'=>'usa','caption'=>lg('北美'), 'uploadType'=>'', 'pwcode'=>'D315'
                    , 'op'=>['export'],'offset'=>[25,$oy + $oj * 3],'class'=>''],
                    
                ['key'=>'attach','caption'=>lg('附件'), 'uploadType'=>'', 'pwcode'=>'D316'
                    , 'op'=>['add','remove','export'],'offset'=>[25,$oy + $oj * 4],'class'=>''],
                ['key'=>'notcattle','caption'=>lg('不带牛油包'), 'uploadType'=>'', 'pwcode'=>'D317'
                    , 'op'=>['add','remove','export'],'offset'=>[25,$oy + $oj * 5],'class'=>''],
                ['key'=>'360','caption'=>lg('360'), 'uploadType'=>'', 'pwcode'=>'D318'
                    , 'op'=>['add','remove','export'],'offset'=>[25,$oy + $oj * 6],'class'=>''],
                ['key'=>'other','caption'=>lg('其他'), 'uploadType'=>'', 'pwcode'=>'D319'
                    , 'op'=>['add','remove','export'],'offset'=>[25,$oy + $oj * 7],'class'=>''],
                
                
           ],
           'upload'=>\mvc::$cfg['upload']['category']['proimage']['items'],
        ];
    }//
    

    /**检测上传
     * @param 
     * @return array
     */
	public function getCfg($pictype)
	{
	   return $this->options['types'][array_search($pictype,array_column($this->options['types'],'key'))];
	}

    /**检测上传
     * @param 
     * @return
     */
	public function uploadCheck($filecount,$reqfilename,$reqfilesize,$uploadID,$extname,$category,$item,$params)
	{
		$pid = $params['pid'];
		if(empty($pid)) {
			throw new \Exception ( '上传产品图片时，产品ID丢失' );
		}
		$cfg = \mvc::$cfg['upload']['category'][$category]['items'][$item];
		$count = $this->db->count('pro_pic',['ppic_p_id'=>$pid,'ppic_type'=>$item]);
		if( ($count+1) > $cfg['maxfile']){
			return lg('超出此项的最大允许的文件数量') .','. lg('最大允许').' '.$cfg['maxfile'].' '.lg('个文件');
		}else{
			return true;
		}
	}


    /**接收上传的图片处理
     * @param 
     * @return
     */
	public function uploadGet($fileid,$filename,$dir,$filebase,$extname,$category,$item,$params)
	{
		$pid = $params['pid'];
		if(empty($pid)) {
			throw new \Exception ( '上传产品图片时，产品ID丢失' );
		}
		$proRow = $this->pro->getRowByKey($pid);
		$tmpA = explode('_',basenameFirst($params['reqfilename']));
		$reqfilename = $tmpA[0];
		if(strtoupper($reqfilename) != strtoupper($proRow['p_innum'])){
		    //文件名和内部编码必须完全一至
		    throw new \Exception ( '文件名和内部编码必须完全一至,文件名:'.$params['reqfilename'] . ' , 内部编码:'.$proRow['p_innum'] );
		    return;
		}
		$oldfilename = basename($params['reqfilename']);
		$oldfilename = substr($oldfilename,0,strrpos($oldfilename,'.'));
		if($item=='init_add' || $item=='beautify_add'){
			$state = 0;
		}else{
			$state = 1;
		}
        //如果原始图中有北美标记得精修也默认加上
        $ppic_isusa = 0;
        if($item=='beautify_add' || $item=='beautify'){
            if($this->db->get('pro_pic','*',['ppic_p_id'=> $pid,'ppic_filebase'=> $oldfilename,'ppic_isusa'=>1])){
                $ppic_isusa=1;
            }
            
            //pdm 能找到 
            $join['[>]pro_numidx'] = ['ppic_p_id'=>'pn_p_id'];
            $numRows = $this->db->select('pro_pic',$join,['pn_number'],['pn_pf_id'=> [3,4,5,6],'pn_p_id'=> $pid]); //gsp no 与 区域码
            $numArr = [];
            $numArr[] = $proRow['p_outnum'];
            foreach($numRows as $numRow){
                $numArr[] = $numRow['pn_number'];
            }
            /*if($this->db->get('copy_smt_api_pdm_items','*',['brand'=> 'DRJN','part_number'=> $numArr])){
                $ppic_isusa=1;
            }*/
            if($this->db->get('pdm_pdc_itemlink','*',['ppi_brand'=> 'DRJN','ppi_pdc_gsp'=> $numArr])){
                $ppic_isusa=1;
            }
                        
        }
        
        if($item=='usa'){
            $item = 'beautify';
            $ppic_isusa = 1;
        }
        
        if($ppic_isusa==1){
    	    //北美图待更新状态
            $data = [
                'ps_p_id'=>$pid,
                'ps_usa_state'=>1,
                'ps_opuser'=>getOpuser(),
            ];
            $this->db->replace('pro_state',$data,['ps_p_id']);
        }
        
        
        
        //如果图片名存在则删除老图片
        if($picRow = $this->db->get('pro_pic','*',['ppic_p_id'=> $pid,'ppic_type'=>$item,'ppic_filebase'=> $oldfilename])){
            $this->files->delete($pidRow['ppic_fileid']);
        }

		$data = [
			'ppic_p_id'=> $pid,
			'ppic_fileid'=> $fileid,
			'ppic_outnum'=> $proRow['p_outnum_format'],
			'ppic_innum'=> $proRow['p_innum'],
			'ppic_type'=> $item,
			'ppic_state'=> $state,
			'ppic_filebase'=> $oldfilename,
			'ppic_isusa'=> $ppic_isusa,
			'opuser'=> getOpuser(),
			'create_time'=> getNowTime(),
			'update_time'=> getNowTime()
		];
		$this->db->replace('pro_pic',$data,['ppic_p_id','ppic_fileid'],['create_time']);
		
		
		//if($item=='init' || $item=='beautify' && $proRow['p_innum']==$oldfilename){
		if($item=='beautify' && $proRow['p_innum']==$oldfilename){
		    $this->setMain($pid,$fileid);
		}
		if($item=='beautify'){
		    $this->setProState($pid,1,['beautify','tecdoc']);
		}
        $this->submitPicTask($pid); //完成上传原始图任务
        
        $this->addHistory('upload',$pid,$fileid);
        
        if($item=='init'){
            (new \model\iocrm())->crmAddProApi($pid, 'U'); 
        }
	}

    /**
     * 任务 - 完成上传原始图
     * @param string $p_id
     * @return mixed
     */
    public function submitPicTask($p_id)
    {
        $date = getNowDate();
        $now = getNowTime();
        $data = [
            'ppt_submit_user'=>getOpuser(),
            'ppt_submit_time'=>$date,
            'update_time'=>$now,
        ];
        $this->db->update('pro_pic_task',$data,['ppt_p_id'=>$p_id]);
    }
    

    /**
     * 设置 一些类型的更新状态
     * @param int $state  0 或 1
     * @param array $types  ['beautify','tecdoc']
     * @return mixed
     */
    public function setProState($pid,$state,$types)
    {
        if(empty($pid)) return false;
        foreach($types as $type){
            $data = [
                'ps_p_id'=>$pid,
                'ps_'.$type.'_state'=>$state,
                'ps_opuser'=>getOpuser(),
            ];
            $this->db->replace('pro_state',$data,['ps_p_id']);
        }
        return true;
    }
    

    /**
     * 任务 - 退回
     * @param string $p_id
     * @return mixed
     */
    public function backPicTask($p_id)
    {
        $date = getNowDate();
        $now = getNowTime();
        $data = [
            'ppt_check_user'=>getOpuser(),
            'ppt_back_time'=>$date,
            'update_time'=>$now,
        ];
        $this->db->update('pro_pic_task',$data,['ppt_p_id'=>$p_id]);
    }
    
    /**
     * 更新设计师导出时间
     * @param int $pid
     * @param int $fileid
     * @return array
     */
	function updateDesexportTime($pid,$fileid){
		$table = 'pro_pic';
        $where['ppic_p_id'] = $pid;
        $where['ppic_fileid'] = $fileid;
        $update=[
            'desexport_time'=> getNowTime()
        ];
		$this->db->update($table,$update,$where);
		$this->addHistory('download',$pid,$fileid);
	}
    
    /**
     * 通过文件ID取品图片
     * @param int $pid
     * @param int $fileid
     * @return array
     */
	function getFileByFileId($pid,$fileid){
		$table = 'pro_pic';
		$join['[>]files'] = ['ppic_fileid'=>'fileid'];
		$fields = '*';
        $where['ppic_p_id'] = $pid;
        $where['ppic_fileid'] = $fileid;
		return $this->db->get($table,$join,$fields,$where);
	}
    
    /**
     * 通过类型取产品图片
     * @param int $pid
     * @param string $type 类型
     * @return array
     */
	function getFiles($pid,$propictype='',$rules=null){
		$table = 'pro_pic';
		$join['[>]files'] = ['ppic_fileid'=>'fileid'];
		$fields = '*';
        $where['ppic_p_id'] = $pid;
        $tsql = '';
		switch ($propictype) {
		    case 'init_add':
		        $where['ppic_type'] = ['init_add','init_back','init_replay'];
		        break;
		    case 'init_back':
		        $where['ppic_type'] = ['init_back','init_replay'];
		        break;
		    case 'init_del':
		        $where['ppic_type'] = 'init_del';
		        break;
		    case 'init_check':
		        $where['ppic_type'] = ['init_add','init'];
		        break;
		    case 'designer':
		        $where['ppic_type'] = 'init';
		        if($rules){
    			    if($rules['checkOption']=='1'){
        			    $where['desexport_time[!]'] = null; //已导出
    			    }else if($rules['checkOption']=='-1'){
        			    $where['desexport_time'] = null; //未导出
    			    }else if($rules['checkOption']=='2'){
        			    $where['ppic_isusa'] = 1; //北美
    			    }else if($rules['checkOption']=='3'){
        			    $where['ppic_isusa'] = 1; //北美
        			    $where['desexport_time'] = null; //未导出
    			    }
		        }
		    case 'init':
		        $where['ppic_type'] = 'init';
		        break;
		    case 'beautify_add':
		        $where['ppic_type'] = ['beautify_add','beautify_back','beautify_replay'];
		        break;
		    case 'beautify_check':
		        $where['ppic_type'] = ['beautify_add','beautify'];
		        break;
		    case 'beautify_back':
		        $where['ppic_type'] = ['beautify_back','beautify_replay'];
		        break;
		    case 'beautify':
		        $where['ppic_type'] = ['beautify'];
		        break;
		        
		    case 'usa':
		        $where['ppic_type'] = ['beautify'];
		        $where['ppic_isusa'] = 1;
		        break;
		    case 'attach':
		    case 'notcattle':
		    case '360':
		    case 'catalog':
		    case 'other':
		        $where['ppic_type'] = $propictype;
		        break;
		}
	    if($tsql!=''){ 
	        $where['RAW'] = raw($tsql);
	    }
		$where['ORDER'] = ['ppic_sort'=>'ASC','ppic_filebase'=>'ASC'];
		$rows = $this->db->select($table,$join,$fields,$where);
		foreach($rows as &$row){
		    $row['back'] = null;
		    $row['replay'] = null;
		    if($row['ppic_state']=='0'){
		        //退回的图片
    			if(in_array($propictype,['init_add','init_check'])){
    			    $backFileid = $this->db->get('pro_pic','ppic_fileid',[
    			        'ppic_p_id'=>$row['ppic_p_id'],
    			        'ppic_type'=>'beautify_back',
    			        'ppic_filebase'=>$row['ppic_filebase'],
    			    ]);
    			    if(empty($backFileid)){
        			    $backFileid = $this->db->get('pro_pic','ppic_fileid',[
        			        'ppic_p_id'=>$row['ppic_p_id'],
        			        'ppic_type'=>'init_back',
        			        'ppic_filebase'=>$row['ppic_filebase'],
        			    ]);
    			    }
    			    $row['back'] = $this->getFileMoreById($backFileid);
    			}else if(in_array($propictype,['beautify_add','beautify_check'])){
    			    $backFileid = $this->db->get('pro_pic','ppic_fileid',[
    			        'ppic_p_id'=>$row['ppic_p_id'],
    			        'ppic_type'=>'beautify_back',
    			        'ppic_filebase'=>$row['ppic_filebase'],
    			    ]);
    			    $row['back'] = $this->getFileMoreById($backFileid);
    			}
    			//重拍的图片
    			if(in_array($propictype,['init_add','init_check'])){
    			    $backFileid = $this->db->get('pro_pic','ppic_fileid',[
    			        'ppic_p_id'=>$row['ppic_p_id'],
    			        'ppic_type'=>'beautify_replay',
    			        'ppic_filebase'=>$row['ppic_filebase'],
    			    ]);
    			    if(empty($backFileid)){
        			    $backFileid = $this->db->get('pro_pic','ppic_fileid',[
        			        'ppic_p_id'=>$row['ppic_p_id'],
        			        'ppic_type'=>'init_replay',
        			        'ppic_filebase'=>$row['ppic_filebase'],
        			    ]);
    			    }
    			    $row['replay'] = $this->getFileMoreById($backFileid);
    			}else if(in_array($propictype,['beautify_add','beautify_check'])){
    			    $backFileid = $this->db->get('pro_pic','ppic_fileid',[
    			        'ppic_p_id'=>$row['ppic_p_id'],
    			        'ppic_type'=>'beautify_replay',
    			        'ppic_filebase'=>$row['ppic_filebase'],
    			    ]);
    			    $row['replay'] = $this->getFileMoreById($backFileid);
    			}
		    }
		    $row['isback'] = strpos($row['ppic_type'],'_back')>0;
		    $row['isreplay'] = strpos($row['ppic_type'],'_replay')>0;
			$this->getFileMore($row);
		}
		return $rows;
    }
    
    //取产品大小图
    public function getProImages($pid,$propictype){
		$smallfile = \mvc::$cfg['path']['files'].'/pro/'.$propictype.'/'.($pid % 100).'/'.$pid.'small.jpg?'.time();
		$bigfile = \mvc::$cfg['path']['files'].'/pro/'.$propictype.'/'.($pid % 100).'/'.$pid.'big.jpg?'.time();
		return ['smallfile'=>$smallfile,'bigfile'=>$bigfile];
    }
    
    //取多尺寸产品图
    public function getFileMoreById($fileid){
        if($fileid && $row = $this->db->get('files','*',['fileid'=>$fileid]))
            return $this->getFileMore($row);
        else
            return [];
    }
    public function getFileMore(&$row)
    {
		$row['filename'] = \mvc::$cfg['path']['files'].'/'. ltrim(str_replace('\\','/',$row['filename']),'/');
 		if($row['filetype']=='image'){
			$row['smallfile'] = filenameSize($row['filename'],'small');
			$row['bigfile'] = filenameSize($row['filename'],'big');
			//原始图片扩展名
		    $row['initfile'] = substr($row['filename'],0,strrpos($row['filename'],'.')).'.'.$row['fileextname'];
		}else{
			$row['smallfile'] = $row['filename'];
			$row['bigfile'] = $row['filename'];
		}
		return $row;
   }
    
    //重置主图
    public function resetAllMain()
	{
		return false;
		set_time_limit(0);
		/*
		$st = $this->db->query("SELECT pro.p_id,pro.p_pic,bkpic.ppic_p_id FROM `gspcatalog`.pro pro
JOIN `gspcatalog_back`.pro_pic bkpic ON pro.p_pic = bkpic.ppic_fileid
WHERE pro.p_pic>0");
		ob_flush();
		$i=0;
		$arrType = ['tecdoc','catalog_g','catalog_gsp'];
		while($row = $st->fetch()){
			$i++;
			if($i%500==0) echo $i."\r\n";
			ob_flush();
			foreach($arrType as $type){
				$bigfilename = $this->fileroot.'/pro/'.$type.'_old/'.($row['ppic_p_id'] % 100) . '/'. $row['ppic_p_id'] .'big.jpg'; 
				$smallfilename = $this->fileroot.'/pro/'.$type.'_old/'.($row['ppic_p_id'] % 100) . '/'. $row['ppic_p_id'] .'small.jpg'; 
				if(file_exists($bigfilename)){
					$tobigfilename = $this->fileroot.'/pro/'.$type.'/'.($row['p_id'] % 100) . '/'. $row['p_id'] .'big.jpg'; 
					$tosmallfilename = $this->fileroot.'/pro/'.$type.'/'.($row['p_id'] % 100) . '/'. $row['p_id'] .'small.jpg'; 
					mkdirs($this->fileroot.'/pro/'.$type.'/'.($row['p_id'] % 100));
					copy($bigfilename,$tobigfilename);
					copy($smallfilename,$tosmallfilename);
					echo $bigfilename."\r\n";
				}
			}
		}
		echo $i;
		*/
		dd('重置主图完成');
	}

    //设置主图
    public function setMain($pid,$fileid)
	{
        if(empty($pid) || empty($fileid))
            return false;
        $this->db->begin();    
		$this->db->update('pro',['p_pic'=>$fileid],['p_id'=>$pid]);
		if($filename = $this->files->getFilename($fileid)){
		    //图待更新状态
            $data = [
                'ps_p_id'=>$pid,
                'ps_beautify_state'=>1,
                'ps_usa_state'=>1,
                'ps_tecdoc_state'=>1,
                'ps_notcattle_state'=>1,
                'ps_opuser'=>getOpuser(),
            ];
            $this->db->replace('pro_state',$data,['ps_p_id']);
            
            //处理图片
			$filename = $this->fileroot.'/'.$filename;
			foreach(['tecdoc','catalog_g','catalog_gsp'] as $item){
				$cfg = \mvc::$cfg['upload']['category']['proimage']['items'][$item];
				$dir = $this->fileroot.'/pro/'. $item . '/' . ($pid % 100);
				mkdirs($dir);
				foreach($cfg['size'] as $key=>$size){
					$dist = $dir.'/'.$pid.$key.'.jpg';
					$watermark = \mvc::$cfg['dir']['static'].'/images/watermark/pro/'.$item.'.png';
					if(file_exists($watermark)){
						$this->image->ResizeWatermark($filename,$dist,$size[0],$size[1],$watermark);
					}else{
						$this->image->Resize($filename,$dist,$size[0],$size[1]);
					}
				}
			}
		}
		$this->db->end();
        $iocrm = new \model\iocrm();
		$iocrm->crmAddProApi($pid, 'U');		
		return $fileid;
	}
    
    //删除文件
    public function deleteFile($pid,$fileid)
    {
		$this->db->begin();
		$this->db->delete('pro_pic',['ppic_p_id'=>$pid,'ppic_fileid'=>$fileid]);
		$this->files->delete($fileid);
		$this->db->update('pro',['p_pic'=>0],['p_id'=>$pid,'p_pic'=>$fileid]);
		return $this->db->end();
    }
    
    //删除
    public function saveDeletes($pid,$items,$propicType)
    {
        if(empty($pid) || empty($items) || empty($propicType))
            return false;
        $where = [
            'ppic_p_id'=>$pid,
            'ppic_fileid'=>$items,
        ];
        //上原始图片者仅删除自己的类型
        if(in_array($propicType,['init_add','beautify_add'])){
            $where['ppic_type'] = $propicType;
        }
        //审核人不能操作已审核的
        if(in_array($propicType,['init_check','beautify_check'])){
            $where['ppic_state'] = 0;
        }
        $rows = $this->db->select('pro_pic','*',$where);
        $this->db->begin();
        foreach($rows as $row){
            //删除所有同名照片
            if(in_array($propicType,['beautify'])){
                $finds = $this->db->select('pro_pic','*',['ppic_p_id'=>$pid,'ppic_filebase'=>$row['ppic_filebase']]);
                foreach($finds as $frow){
                    $this->deleteFile($pid,$frow['ppic_fileid']);
                }
            }
            $this->deleteFile($pid,$row['ppic_fileid']);
            (new \model\iocrm())->crmAddProApi($pid, 'U');            
        }
        //上原始图片者或原始图审核者如果全删除了图片，则将任务中的提交时间置空
        if(in_array($propicType,['init_add','init_check'])){
            if(!$this->db->has('pro_pic',['ppic_p_id'=>$pid,'ppic_type'=>$propicType])){
                $data = [
                    'ppt_submit_user'=>'',
                    'ppt_submit_time'=>null,
                ];
                $this->db->update('pro_pic_task',$data,['ppt_p_id'=>$pid]);
            }
        }
        return $this->db->end();
    }
    
    //Usa
    public function saveUsas($pid,$items,$propicType)
    {
        if(empty($pid) || empty($items) || empty($propicType))
            return false;
        $this->db->begin();
        foreach($items as $item){
            if($item['value']=='1'){
                $where = [
                    'ppic_p_id'=>$pid,
                    'ppic_fileid'=>$item['fileid']
                ];
                $row = $this->db->get('pro_pic','*',$where);
                $filebase = $row['ppic_filebase'];
                $ppic_isusa = abs($row['ppic_isusa']*1-1);
                //更新同产品下所有同名图片
                $this->db->update('pro_pic',['ppic_isusa'=>$ppic_isusa],['ppic_p_id'=>$pid,'ppic_filebase'=>$filebase]);
            }
        }
        
	    //北美图待更新状态
        $data = [
            'ps_p_id'=>$pid,
            'ps_usa_state'=>1,
            'ps_opuser'=>getOpuser(),
        ];
        $this->db->replace('pro_state',$data,['ps_p_id']);
        return $this->db->end();
    }
    
    //重拍 + 批量 + 原因
    public function saveReplaysMore($list,$propicType,$remark){
        foreach($list as $pid=>$items){
            $this->saveReplays($pid,$items,$propicType,$remark);
        }
        return true;
    }
    
    //重拍
    public function saveReplays($pid,$items,$propicType,$remark='')
    {
        if(empty($pid) || empty($items) || empty($propicType))
            return false;
        $where = [
            'ppic_p_id'=>$pid,
            'ppic_fileid'=>$items,
        ];
        //审核人不能操作已审核的
        if(in_array($propicType,['init_check','beautify_check'])){
            $where['ppic_state'] = 0;
        }
        $bigType = explode('_',$propicType)[0];
        $replayType = $bigType.'_replay';
        $rows = $this->db->select('pro_pic','*',$where);
        $this->db->begin();
        foreach($rows as $row){
            //如果已经有重拍则删除前面的文件
            if($findFieldId = $this->db->get('pro_pic','ppic_fileid',['ppic_p_id'=>$pid,'ppic_type'=>$replayType,'ppic_filebase'=>$row['ppic_filebase']]))
            {
                //$this->deleteFile($pid,$findFieldId);
                $this->files->delete($findFieldId);
            }
			if(in_array($propicType,['beautify'])){
				$this->db->update('pro_pic',['ppic_type'=>'init_replay','ppic_state'=>0, 'ppic_remark'=>$remark]
					,['ppic_p_id'=>$pid,'ppic_filebase'=>$row['ppic_filebase'],'ppic_type'=>'init']);
				$this->db->update('pro_pic',['ppic_type'=>'beautify_replay','ppic_state'=>0, 'ppic_remark'=>$remark]
					,['ppic_p_id'=>$pid,'ppic_filebase'=>$row['ppic_filebase'],'ppic_type'=>'beautify']);
			}else{
				$this->db->update('pro_pic',['ppic_type'=>'init_replay','ppic_state'=>0, 'ppic_remark'=>$remark]
				    ,['ppic_p_id'=>$pid,'ppic_fileid'=>$row['ppic_fileid']]);
			}
			if(strtoupper($row['ppic_innum']) == strtoupper($row['ppic_filebase'])){
                $iocrm = new \model\iocrm();
        		$iocrm->crmAddProApi($pid, 'U');		
			}
        }
        $this->db->delete('pro_pic_task',['ppt_p_id'=>$pid]);
        $this->addPicTask($pid);

		$iocrm = new \model\iocrm();
		$iocrm->crmAddProApi($pid, 'U');

        return $this->db->end();
    }
    
    //退回 + 批量 + 原因
    public function saveBacksMore($list,$propicType,$remark){
        foreach($list as $pid=>$items){
            $this->saveBacks($pid,$items,$propicType,$remark);
        }
        return true;
    }
    
    //退回
    public function saveBacks($pid,$items,$propicType,$remark='')
    {
        if(empty($pid) || empty($items) || empty($propicType))
            return false;
        $where = [
            'ppic_p_id'=>$pid,
            'ppic_fileid'=>$items,
        ];
        //审核人不能操作已审核的
        if(in_array($propicType,['init_check','beautify_check'])){
            $where['ppic_state'] = 0;
        }
        $bigType = explode('_',$propicType)[0];
        $backType = $bigType.'_back';
        $rows = $this->db->select('pro_pic','*',$where);
        $this->db->begin();
        foreach($rows as $row){
            //如果已经有退回则删除前面的
            if($findBackFieldId = $this->db->get('pro_pic','ppic_fileid',['ppic_p_id'=>$pid,'ppic_type'=>$backType,'ppic_filebase'=>$row['ppic_filebase']]))
            {
                $this->deleteFile($pid,$findBackFieldId);
            }
			if(in_array($propicType,['beautify'])){
				$this->db->update('pro_pic',['ppic_type'=>'init_back','ppic_state'=>0, 'ppic_remark'=>$remark]
					,['ppic_p_id'=>$pid,'ppic_filebase'=>$row['ppic_filebase'],'ppic_type'=>'init']);
				$this->db->update('pro_pic',['ppic_type'=>'beautify_back','ppic_state'=>0, 'ppic_remark'=>$remark]
					,['ppic_p_id'=>$pid,'ppic_filebase'=>$row['ppic_filebase'],'ppic_type'=>'beautify']);
			}else{
				$this->db->update('pro_pic',['ppic_type'=>'init_back','ppic_state'=>0, 'ppic_remark'=>$remark]
				    ,['ppic_p_id'=>$pid,'ppic_fileid'=>$row['ppic_fileid']]);
			}
            
            /*
            $updateData = ['ppic_type'=>$backType,'ppic_state'=>0];
            if($remark!=''){
                $updateData['ppic_remark'] = $remark;
            }
            $this->db->update('pro_pic',$updateData,['ppic_p_id'=>$pid,'ppic_fileid'=>$row['ppic_fileid']]);
            */
			//2022/10/19 退回清主图
			$this->db->update('pro',['p_pic'=>0],['p_id'=>$pid,'p_pic'=>$row['ppic_fileid']]);
        }
        $this->db->delete('pro_pic_task',['ppt_p_id'=>$pid]);
        $this->addPicTask($pid);

		$iocrm = new \model\iocrm();
		$iocrm->crmAddProApi($pid, 'U');

        return $this->db->end();
    }
    
    //牛油包图待更新状态
    public function saveNotcattleState($state,$pid,$items,$propicType){
        $this->db->begin();
        if($state==0){
            $data = [
                'ps_p_id'=>$pid,
                'ps_notcattle_state'=>0,
                'ps_opuser'=>getOpuser(),
            ];
        }else{
            $data = [
                'ps_p_id'=>$pid,
                'ps_notcattle_state'=>1,
                'ps_opuser'=>getOpuser(),
            ];
        }
        $this->db->replace('pro_state',$data,['ps_p_id']);
        return $this->db->end();
    }
    
    //审核
    public function saveChecks($pid,$items,$propicType)
    {
        if(empty($pid) || empty($items) || empty($propicType))
            return false;
        $bigType = explode('_',$propicType)[0];
        $where = [
            'ppic_p_id'=>$pid,
            'ppic_fileid'=>$items,
            'ppic_state'=>0,
        ];
        $rows = $this->db->select('pro_pic','*',$where);
        $this->db->begin();
        $crmAddProApi = false;
		foreach($rows as $row){
            //图片名是否等于内部编码
            if(strtolower($row['ppic_innum']) == strtolower($row['ppic_filebase'])){
                if(explode('_',$propicType)[0]=='init'){
                    //原始图审核，查询是否存在精修图主图,如果没有则创建主图
                    /*
                    if(!$this->db->has('pro_pic',['ppic_p_id'=>$pid,'ppic_type'=>'beautify','ppic_filebase'=>$row['ppic_innum']]))
                    {
                        $this->setMain($pid,$row['ppic_fileid']);
                    }*/
                }else{
                    //精修图审核，创建主图
                    $this->setMain($pid,$row['ppic_fileid']);
					$crmAddProApi = true;
                }
            }
            //删除同名退回与重拍及重复图片
            $delWhere =[
                'ppic_p_id'=>$pid,
                'ppic_fileid[!]'=>$row['ppic_fileid'],
                'ppic_type'=>[$bigType.'_back',$bigType.'_replay',$bigType],
                'ppic_filebase'=>$row['ppic_filebase']
            ] ;
            $findDelRows = $this->db->select('pro_pic','*',$delWhere);
            if($findDelRows){
                foreach ($findDelRows as $delRow){
                    $this->deleteFile($pid,$delRow['ppic_fileid']);
                }
                $this->db->delete('pro_pic',$delWhere);
            }
            if($propicType=='beautify_check'){
    		    $this->setProState($pid,1,['beautify','tecdoc']);
    		}
            //更换类型
            $this->db->update('pro_pic',['ppic_state'=>1,'ppic_type'=>$bigType],['ppic_p_id'=>$pid,'ppic_fileid'=>$row['ppic_fileid']]);
            if($row['ppic_isusa']==1){
        	    //北美图待更新状态
                $data = [
                    'ps_p_id'=>$pid,
                    'ps_usa_state'=>1,
                    'ps_opuser'=>getOpuser(),
                ];
                $this->db->replace('pro_state',$data,['ps_p_id']);
            }
        }
        //如果图片都审核过了，删除任务清单记录
        if(!$this->db->has('pro_pic',['ppic_p_id'=>$pid,'ppic_type'=>['init_add','beautify_add']]))
        {
            if($this->db->has('pro_pic',['ppic_p_id'=>$pid,'ppic_type'=>['init','beautify']])){
                $this->db->delete('pro_pic_task',['ppt_p_id'=>$pid]);
            }
        }
		
		if(!$crmAddProApi)
		{
			$iocrm = new \model\iocrm();
			$iocrm->crmAddProApi($pid, 'U');
		}
        return $this->db->end();
    }
    
    //加载任意备注
    public function loadAnyRemark($type,$filebase)
    {
        $remark = '';
        if($type=='init_back'){
            $row = $this->db->get('pro_pic',
                ['ppic_type','ppic_remark'],['ppic_type'=>'beautify_back','ppic_filebase'=>$filebase,'ppic_remark[!]'=>'','ppic_remark[!]'=>NULL]);
            if(empty($row)){
                $row = $this->db->get('pro_pic',
                    ['ppic_type','ppic_remark'],['ppic_type'=>'init_back','ppic_filebase'=>$filebase,'ppic_remark[!]'=>'','ppic_remark[!]'=>NULL]);
            }
        }else if($type=='init_replay'){
            $row = $this->db->get('pro_pic',
                ['ppic_type','ppic_remark'],['ppic_type'=>'beautify_replay','ppic_filebase'=>$filebase,'ppic_remark[!]'=>'','ppic_remark[!]'=>NULL]);
            if(empty($row)){
                $row = $this->db->get('pro_pic',
                    ['ppic_type','ppic_remark'],['ppic_type'=>'init_replay','ppic_filebase'=>$filebase,'ppic_remark[!]'=>'','ppic_remark[!]'=>NULL]);
            }
        }else{
            $row = $this->db->get('pro_pic',
                ['ppic_type','ppic_remark'],['ppic_type'=>'init_replay','ppic_filebase'=>$filebase,'ppic_remark[!]'=>'','ppic_remark[!]'=>NULL]);
        }  
        $remark = $row['ppic_remark'] ;
        return $remark;
    }
    
    //保存名称与备注
    public function saveNameAndRemark($pid,$items,$propicType)
    {
        if(empty($pid) || empty($items) || empty($propicType))
            return false;
        $innum = $this->db->get('pro_pic','ppic_innum',['ppic_p_id'=>$pid]);
        $this->db->begin();
        foreach($items as $item){
            $where = [
                'ppic_p_id'=>$pid,
                'ppic_fileid'=>$item['fileid'],
            ];
            $data = [
                'ppic_filebase'=>$item['filebase'],
                'ppic_remark'=>$item['remark'],
            ];
            //图片名是否等于内部编码
            if(formatNum($innum) == formatNum($item['filebase'])){
                $findRow = $this->db->get('pro_pic',['ppic_filebase','ppic_state'],$where);
                //已审核状态，图片名修改过,进入创建主图流程
                if($findRow && $findRow['ppic_state']=='1' && $findRow['ppic_filebase']!=$item['filebase'])
                {
                    if(explode('_',$propicType)[0]=='init'){
                        //原始图审核，查询是否存在精修图主图,如果没有则创建主图
                        /*
                        if(!$this->db->has('pro_pic',['ppic_p_id'=>$pid,'ppic_type'=>'beautify','ppic_filebase'=>$innum]))
                        {
                            $this->setMain($pid,$item['fileid']);
                        }
                        */
                    }else{
                        //精修图审核，创建主图
                        $this->setMain($pid,$item['fileid']);
                    }
                }
            }
            $this->db->update('pro_pic',$data,$where);
        }
        return $this->db->end();
    }

    /**
     * 添加产品到拍照清单
     * @param string $begin 开始日期
     * @param string $end 结束日期
     * @return mixed
     */
    public function addPicTask($p_id)
    {
        $pro = $this->pro;
        $proRow = $pro->getRowByKey($p_id);
        $proPicTask = new \model\proPicTask();
        $date = getNowDate();
        $now = getNowTime();
        if($proRow){
           $proRow = $pro->formatRow($proRow);
        }else{
           $proRow = [
               'p_id' => 0,
               'p_cate' => 0,
               'captions' => ['p_bigcate'=>'','p_cate'=>''],
           ];
           return ['error'=>false, 'type'=> 'notfound', 'outnum'=>$proRow['p_outnum']];
        }
        $has = $this->db->has('pro_pic_task',['ppt_outnum'=>$proRow['p_outnum']]);
        if($has){
            return ['error'=>true, 'type'=> 'has', 'outnum'=>$proRow['p_outnum']];
        }else{
            $data = [
                'ppt_p_id'=>$proRow['p_id'],
                'ppt_outnum'=>$proRow['p_outnum'],
                'ppt_innum'=>$proRow['p_innum'],
                'ppt_catebig'=>$proRow['captions']['p_bigcate'],
                'ppt_catename'=>$proRow['captions']['p_cate'],
                'ppt_cate'=>$proRow['p_cate'],
                'ppt_orderno'=>'',
                'ppt_orderid'=>0,
                'ppt_remark'=>$remark,
                'ppt_submit_user'=>null,
                'ppt_submit_time'=>null,
                'create_time'=>$now,
                'update_time'=>$now,
            ];
            $result = $proPicTask->replaceRow($data,'ppt_outnum');
            return ['error'=>false,'type'=> $result, 'outnum'=>$proRow['p_outnum']];
        }
    }

    /**
     * 生成拍照清单
     * @param string $begin 开始日期
     * @param string $end 结束日期
     * @return mixed
     */
    public function createPicTask($begin,$end)
    {
        $where = [
            'deliverydatebyitem[<>]'=>[$begin,$end],
            'orderLevel'=>['5','s-评审完毕','s-评审完毕','评审完毕'],
            'RAW1'=> raw(" exists(select 1 from pro where p_innum = productshortnumber and p_state_main not in('Y5','Y6') limit 1)"),
            //'RAW2'=> raw(" not exists(select 1 from pro_pic_task where ppt_innum = ProductShortNumber and ppt_submit_user is null limit 1)"),
            'RAW3'=> raw(" not exists(select 1 from pro_pic where ppic_type in ('init','beautify') and ppic_innum = productshortnumber limit 1)"),
            'ORDER'=>['deliverydatebyitem'=>'DESC'],
        ];
        $rows = $this->db->select('gsp_new_saledataall_bi','*',$where);
        //dd($this->db->last());
        $pro = new \model\pro\pro();
        $proPicTask = new \model\proPicTask();
        $date = getNowDate();
        $now = getNowTime();
        foreach ($rows as $row){
           if(empty($row['productshortnumber']))
                continue;
            $remark = '';
            $proRow = $pro->getRowByFieldValue('p_innum',$row['productshortnumber'],'p_id');
            if($proRow){
               $proRow = $pro->formatRow($proRow);
            }else{
                continue;
            }
            $data = [
                'ppt_p_id'=>$proRow['p_id'],
                'ppt_outnum'=>$proRow['p_outnum'],
                'ppt_innum'=>$proRow['p_innum'],
                'ppt_catebig'=>$proRow['captions']['p_bigcate'],
                'ppt_catename'=>$proRow['captions']['p_cate'],
                'ppt_cate'=>$proRow['p_cate'],
                'ppt_orderno'=>$row['orderno'],
                'ppt_senddate'=>$row['deliverydatebyitem'],
                //'ppt_orderid'=>$row['Id'],
                'ppt_remark'=>$remark,
                //'ppt_submit_user'=>getOpuser(),
                //'ppt_submit_time'=>$date,
                'create_time'=>$now,
                'update_time'=>$now,
            ];
            $proPicTask->replaceRow($data,'ppt_innum');
        }
    }

    public function pictureSynthesis($rules,$where='',$page=0,$pagesize=0,$sidx='',$sord='asc',$orderby='')
    {
        $types = array_column($this->options['types'],'key');
        $this->join = [];
        $where = $this->filter2medoo($where,function(&$field,&$op,&$data)use($types){
            if(in_array($field,['tecdoc','catalog_gsp','catalog_g'])){
                $field = 'p_pic';
                $op = $data == 1 ? 'not' : 'eq';
                $data = 0;
            }elseif($field=='init_has'){
                $op = 'sql';
                if($data){
                    $data = " EXISTS(SELECT 1 FROM pro_pic WHERE ppic_p_id = pro.p_id AND (ppic_type='init_add' OR ppic_type='init'))";
                }else{
                    $data = " NOT EXISTS(SELECT 1 FROM pro_pic WHERE ppic_p_id = pro.p_id AND (ppic_type='init_add' OR ppic_type='init'))";
                }
            }elseif($field=='beautify_has'){
                $op = 'sql';
                if($data){
                    $data = " EXISTS(SELECT 1 FROM pro_pic WHERE ppic_p_id = pro.p_id AND (ppic_type='beautify_add' OR ppic_type='beautify'))";
                }else{
                    $data = " NOT EXISTS(SELECT 1 FROM pro_pic WHERE ppic_p_id = pro.p_id AND (ppic_type='beautify_add' OR ppic_type='beautify'))";
                }
            }elseif(in_array($field,$types)){
                $op = 'sql';
                if($data){
                    $data = " EXISTS(SELECT 1 FROM pro_pic WHERE ppic_p_id = pro.p_id AND ppic_type='".$field."')";
                }else{
                    $data = " NOT EXISTS(SELECT 1 FROM pro_pic WHERE ppic_p_id = pro.p_id AND ppic_type='".$field."')";
                }
            }else{
                switch($field){
                    case 'create_time':
                    case 'update_time':
                        $data = trim($data);
                        $field = 'pro_pic.'.$field;
                        break;
                }
            }
        });
        
        if(in_array($sidx,$types)){
            $sidx = '';
        }else{
            switch($sidx){
                case 'create_time':
                case 'update_time':
                    $sidx = 'pro_pic.'.$sidx;
                    break;
            }
        }
        
        if(!empty($rules['p_cate'])){
            $where['p_cate'] = explode(',',$rules['p_cate']);
        }
		//号码查询
		if(!empty($rules['numbers'])){
			$this->join['[><]pro_numidx(pn)'] = ['p_id'=>'pn_p_id'];
			$where['pn.pn_pf_id'] = [2,3];
			if($rules['numlike']){//模糊
				foreach($rules['numbers'] as $nk=>$number){
					$sub = sprintf("pn.pn_formart like '%%%s%%'",$number);
					$andStr[] = $sub;
				}
				$where['RAW #numlike'] = raw('('.implode(' OR ',$andStr).')');
			}else{
				$where['pn_formart'] = $rules['numbers'];
			}
		}
        $where = $this->listWhere($where,$page,$pagesize,$sidx,$sord,$orderby);
        /*
        $this->join = [
            '[>]pro_pic' => ['p_id'=>'ppic_p_id']
        ];
        */
        if($page>0 && $pagesize>0){
            if(empty($this->join)){
                $pages = $this->paging('pro',$where,$page,$pagesize);
            }else{
                $pages = $this->paging('pro',$this->join,'p_id',$where,$page,$pagesize);
            }
            $where["LIMIT"] = [$pages['limit'],$pagesize];
        }
        //dd($this->db->last());
        $where['GROUP'] = 'p_id';
        $fields = ['p_innum','p_id','p_outnum','p_cate','p_pic'];
        if(empty($this->join)){
            $rows = $this->db->select('pro',$fields,$where);
        }else{
            $rows = $this->db->select('pro',$this->join,$fields,$where);
        }
        $ids = array_column($rows,'p_id');
        $stateData = [];
        if($ids){
            $stateData = $this->db->select('pro_pic'
             ,['ppic_state','ppic_p_id','ppic_type','create_time','update_time']
             ,['ppic_p_id' => $ids,'GROUP'=>['ppic_p_id','ppic_type','ppic_state']
             ,'ORDER'=>'update_time']);
        }
        foreach ($rows as $i=>$row)
        {
            $row = $this->getProPicState($row,$stateData,$types);
            $row['tecdoc'] = $row['p_pic'] ? 1 : 0;
            $row['catalog_gsp'] = $row['tecdoc'];
            $row['catalog_g'] = $row['tecdoc'];
            $rows[$i] = $row;
        }
        //dd($stateData,$rows);
        $data = [
            'page'=> $page,
            'total'=> $pages['total'],
            'records' => $pages['records'],
            'rows' => $rows
        ];
        return $data;
    }
    
    public function getProPicState($row,$stateData,$types)
    {
        foreach($types as $type){
            $row[$type] = 0;
        }
        $row['init_has'] = 0;
        $row['beautify_has'] = 0;
        foreach($stateData as $item){
            if($row['p_id']==$item['ppic_p_id']){
                $row[$item['ppic_type']] = 1;
                $row['create_time'] = $item['create_time'];
                $row['update_time'] = $item['update_time'];
                if($item['ppic_type']=='init' or $item['ppic_type']=='init_add'){
                    $row['init_has'] = 1;
                }elseif($item['ppic_type']=='beautify' or $item['ppic_type']=='beautify_add'){
                    $row['beautify_has'] = 1;
                }
            }
        }
        return $row;
    }
    
    public function reportList($rules, $where='',$page=0,$pagesize=0,$sidx='',$sord='asc',$orderby='')
    {
        $formatRowCache = [];
        $cate = new \model\pro\cate();
        
        $table = 'pro(p)';
        $this->fields = ['p.*'];
        $this->join = [];
		$whereRegi = 0;
		$othWhere = [];
        $where = $this->filter2medoo($where,function(&$field,&$op,&$data)use($cate,&$rules,&$whereRegi,&$othWhere){
            switch($field){
                case 'pic_opuser':
                    $field = 'pic.opuser';
                    break;
                case 'p_cate_caption':
                    $data = $cate->like($data);
                    if(empty($data)) $data = [0];
                    break;
                case 'p_bigcate_caption':
					$field = 'p_cate';
                    $data = $cate->likeAndChilds($data);
                    if(empty($data)) $data = [0];
                    break;
                case 'upload_lasttime':
                    $mdop = $this->getMedooOp($op);
                    if($mdop=='>=')  $data .= ' 00:00:00';
                    if($mdop=='<=')  $data .= ' 23:59:59';
                    //$othWhere['HAVING']['upload_lasttime['.$mdop.']'] = $data;
                    $othWhere['RAW_upload_lasttime #'.$mdop] = raw("EXISTS(SELECT 1 FROM pro_pic_history WHERE pph_pid=p.p_id AND pph_type='upload' AND pph_time ".$mdop." '".$data."')");
                    $op=null;
                    break;
                case 'download_lasttime':
                    $mdop = $this->getMedooOp($op);
                    if($mdop=='>=')  $data .= ' 00:00:00';
                    if($mdop=='<=')  $data .= ' 23:59:59';
                    //$othWhere['HAVING']['download_lasttime['.$mdop.']'] = $data;
                    $othWhere['RAW_download_lasttime #'.$mdop] = raw("EXISTS(SELECT 1 FROM pro_pic_history WHERE pph_pid=p.p_id AND pph_type='download' AND pph_time ".$mdop." '".$data."')");
                    $op=null;
                    break;
            }
        });
        $where = $this->listWhere($where,$page,$pagesize,$sidx,$sord,$orderby);
		/*
		$this->fields[] = 'pic.opuser(pic_opuser)';
		$this->fields['upload_qty'] = raw('COUNT(pic.ppic_fileid)');
		$this->fields[] ="@(SELECT MAX(update_time) FROM pro_pic WHERE ppic_p_id=p.p_id AND ppic_type IN ('beautify_add','beautify')) as upload_lasttime";
		$this->fields['download_lasttime'] = raw('MAX(pic.desexport_time)');
		$this->join['[><]pro_pic(pic)'] = ['p.p_id'=>'ppic_p_id'];
		$where['pic.opuser'] = 'Chencm';
		$where['GROUP'] = ['p.p_id'];
        */
 		//$this->join['[><]pro_pic_history(h)'] = ['p.p_id'=>'pph_pid'];
		$this->fields[] = "@'Chencm' as pic_opuser";
		$this->fields['upload_qty'] = raw("(SELECT count(1) FROM pro_pic_history WHERE pph_pid=p.p_id AND pph_type='upload')");
		$this->fields['download_qty'] = raw("(SELECT count(1) FROM pro_pic_history WHERE pph_pid=p.p_id AND pph_type='download')");
		$this->fields['upload_lasttime'] = raw("(SELECT MAX(pph_time) FROM pro_pic_history WHERE pph_pid=p.p_id AND pph_type='upload')");
		$this->fields['download_lasttime'] = raw("(SELECT MAX(pph_time) FROM pro_pic_history WHERE pph_pid=p.p_id AND pph_type='download')");
 		$where['RAW #pro_pic_history'] = raw('EXISTS(SELECT 1 FROM pro_pic_history WHERE pph_pid=p.p_id LIMIT 1)');
       
        $where = array_merge($where,$othWhere);
        if(!empty($rules['p_cate'])){
            $where['p_cate'] = explode(',',$rules['p_cate']);
        }
		//号码查询
		if(!empty($rules['numbers'])){
			$this->join['[><]pro_numidx(pn)'] = ['p.p_id'=>'pn_p_id'];
			if($rules['numfac']){
				if($rules['numfac']=='2'){
					$where['pn.pn_is_gsp'] = 1;
					$where['pn.pn_pf_id[!]'] = 3;
				}else{
					$where['pn.pn_pf_id'] = $rules['numfac'];
				}
			}
			if($rules['numlike']){//模糊
				foreach($rules['numbers'] as $nk=>$number){
					$sub = sprintf("pn.pn_formart like '%%%s%%'",$number);
					$andStr[] = $sub;
				}
				$where['RAW #numlike'] = raw('('.implode(' OR ',$andStr).')');
			}else{
				$where['pn_formart'] = $rules['numbers'];
			}
		}

		
		if($page>0 && $pagesize>0){
            if(empty($this->join)){
                $pages = $this->paging($table,$where,$page,$pagesize);
            }else{
                $pages = $this->paging($table,$this->join,'p.p_id',$where,$page,$pagesize);
            }
            /*
            $records = $this->db->select($table,$this->join,array_merge(['@count(1) total'],$this->fields),$where);
            dd($records,$this->db->last());
            $records = 2;//$records[0]['total'];
            /*if(empty($this->join)){
                $records = $this->db->count($table,$this->fields,$where);
            }else{
                $records = $this->db->count($table,$this->join,$this->fields,$where);
            }*/
            /*
            $pages['page'] = $page; //当前页码
            $pages['pagesize'] = $pagesize; //一页多少条
            $pages['total'] = ceil($records / $pagesize); //总页码数
            $pages['records'] = $records; //总记录数
            $pages['limit'] = ($page-1) * $pagesize;
            */    
			$where["LIMIT"] = [$pages['limit'],$pagesize];
		}
		
        if(empty($this->join)){
            $rows = $this->db->select($table,$this->fields,$where);
        }else{
            $rows = $this->db->select($table,$this->join,$this->fields,$where);
        }
        
        //dd($this->db->last(),count($rows));
        if(!empty($rows)) foreach($rows as $k=>$row){
            //$row['download_qty'] = $this->db->count('pro_pic',['ppic_p_id'=>$row['p_id'],'opuser'=>$row['pic_opuser'],'desexport_time[!]'=>null]);
            //产品线与品名
            if(!empty($row['p_cate'])){
    			if(empty($formatRowCache['cate'][$row['p_cate']])){
    				 $cateRow = $cate->getRowByKey($row['p_cate']);
    				 $formatRowCache['cate'][$row['p_cate']] = $cateRow;
    			}else{
    				 $cateRow = $formatRowCache['cate'][$row['p_cate']];
    			}
    
    			if(empty($formatRowCache['cate'][$cateRow['parent_id']])){
    				 $bigCateRow = $cate->getRowByKey($cateRow['parent_id']);
    				 $formatRowCache['cate'][$cateRow['parent_id']] = $bigCateRow;
    			}else{
    				 $bigCateRow = $formatRowCache['cate'][$cateRow['parent_id']];
    			}
    			$row['p_bigcate_caption'] = $bigCateRow[cateName()];
    			$row['p_cate_caption'] = $cateRow[cateName()];
            }        
            $rows[$k] = $row;
        }
		$data = [
			'page'=> $page,
			'total'=> $pages['total'],
			'records' => $pages['records'],
			'rows' => $rows
		];
		return $data;
    }
    public function addHistory($type,$pid,$fileid)
    {
        $user = getOpuser();
        if($user=='Chencm'){ //Chencm
            $data = [
                'pph_pid'=> $pid,
                'pph_fileid'=> $fileid,
                'pph_type'=> $type,
                'pph_opuser'=> getOpuser()
            ];
            $this->db->insert('pro_pic_history',$data);
        }
    }
}