<?php

namespace model\pro;

use model\alioss;
use model\files;

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'=>'G311'
                    , 'op'=>['add','remove','import'],'offset'=>[25,200],'class'=>''],
                ['key'=>'init_check','caption'=>lg('原始图审核'), 'uploadType'=>'init_add', 'pwcode'=>'G320'
                    , 'op'=>['check'],'offset'=>[192,200],'class'=>''],
                ['key'=>'init_back','caption'=>lg('退回-原始图'), 'uploadType'=>'init_add','short'=>lg('退回'), 'pwcode'=>'G341'
                    , 'op'=>['remove','delete'],'offset'=>[210,65],'class'=>'xytow'],
                //['key'=>'init_del','caption'=>lg('删除-原始图'), 'uploadType'=>'init_add','short'=>'删除', 'pwcode'=>'G311|D320'
                    //, 'op'=>['delete'],'offset'=>[210,84],'class'=>'xytow'],
                ['key'=>'init','caption'=>lg('原始照片库'), 'uploadType'=>'init', 'pwcode'=>'G301'
                    , 'op'=>['add','remove','delete','readd','import','export'],'offset'=>[376,163],'class'=>''],
                ['key'=>'designer','caption'=>lg('设计师'), 'uploadType'=>'init', 'pwcode'=>'G303'
                    , 'op'=>['export'],'offset'=>[386,237],'class'=>''],
                
                ['key'=>'beautify_add','caption'=>lg('上传精修海报'), 'uploadType'=>'beautify_add', 'pwcode'=>'G330'
                    , 'op'=>['add','remove','import'],'offset'=>[375,375],'class'=>''],
                ['key'=>'beautify_check','caption'=>lg('审精修海报'), 'uploadType'=>'beautify_add', 'pwcode'=>'G360'
                    , 'op'=>['export'],'offset'=>[192,375],'class'=>''],
                ['key'=>'beautify_back','caption'=>lg('退回-精修图'),'short'=>lg('退回'), 'uploadType'=>'beautify_add', 'pwcode'=>'G342'
                    , 'op'=>['export'],'offset'=>[210,507],'class'=>'xytow'],
                ['key'=>'beautify','caption'=>lg('精修海报库'), 'uploadType'=>'beautify', 'pwcode'=>'G302'
                    , 'op'=>['export'],'offset'=>[29,375],'class'=>''],
                
                ['key'=>'video','caption'=>lg('视频'), 'uploadType'=>'', 'pwcode'=>'G312'
                    , 'op'=>['add','remove','export'],'offset'=>[25,$oy + $oj * 0],'class'=>''],
                ['key'=>'oem','caption'=>lg('原厂'), 'uploadType'=>'', 'pwcode'=>'G313'
                    , 'op'=>['add','remove','export'],'offset'=>[25,$oy + $oj * 1],'class'=>''],
                ['key'=>'competitor','caption'=>lg('竞品'), 'uploadType'=>'', 'pwcode'=>'G314'
                    , 'op'=>['add','remove','export'],'offset'=>[25,$oy + $oj * 2],'class'=>''],
                ['key'=>'other','caption'=>lg('其他'), 'uploadType'=>'', 'pwcode'=>'G319'
                    , 'op'=>['add','remove','export'],'offset'=>[25,$oy + $oj * 3],'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 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['pic_p_id'] = $pid;
        $where['pic_fileid'] = $fileid;
        $update=[
            'pic_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'] = ['pic_fileid' => 'fileid'];
        $join['[>]pro'] = ['pic_p_id' => 'p_id'];
        $fields = '*';
        $where['pic_p_id'] = $pid;
        $where['pic_fileid'] = $fileid;
		return $this->db->get($table,$join,$fields,$where);
	}

    function getProByFieId($fileid){
        $join['[><]pro'] = ['pic_p_id'=>'p_id'];
        return $this->db->get('pro_pic',$join,'*',['pic_fileid'=>$fileid]);
    }
        
    /**
     * 通过类型取产品图片
     * @param int $pid
     * @param string $type 类型
     * @return array
     */
	function getFiles($pid,$propictype='',$rules=null){
		$table = 'pro_pic';
		$join['[>]files'] = ['pic_fileid'=>'fileid'];
        if($rules['objectVer']){
            $join['[><]object_tags_link'] = ['pic_fileid'=>'otl_val_id'];
            $where['otl_o_id'] = $rules['objectVer'];
            $where['otl_table'] = 'pro';
            $where['otl_type'] = 'pic';
            $where['GROUP'] = ['pic_fileid'];
        }
        
        if(!empty($rules['langs'])){
            if($rules['langs']=='unset'){
                $where['pic_lang'] = '';
            }else{
                $where['pic_lang'] = $rules['langs'];
            }
        }
		$fields = '*';
        $where['pic_p_id'] = $pid;
        $tsql = '';
		switch ($propictype) {
		    case 'init_add':
		        $where['pic_style'] = ['init_add','init_back','init_replay'];
		        break;
		    case 'init_back':
		        $where['pic_style'] = ['init_back','init_replay'];
		        break;
		    case 'init_del':
		        $where['pic_style'] = 'init_del';
		        break;
		    case 'init_check':
		        $where['pic_style'] = ['init_add','init'];
		        break;
		    case 'designer':
		        $where['pic_style'] = 'init';
                $where['pic_isbeautify'] = 1;
		        if($rules){
    			    if($rules['checkOption']=='1'){
        			    $where['pic_desexport_time[!]'] = null; //已导出
    			    }else if($rules['checkOption']=='-1'){
        			    $where['pic_desexport_time'] = null; //未导出
    			    }
		        }
		    case 'init':
		        $where['pic_style'] = 'init';
		        break;
		    case 'beautify_add':
		        $where['pic_style'] = ['beautify_add','beautify_back','beautify_replay'];
		        break;
		    case 'beautify_check':
		        $where['pic_style'] = ['beautify_add','beautify'];
		        break;
		    case 'beautify_back':
		        $where['pic_style'] = ['beautify_back','beautify_replay'];
		        break;
		    case 'beautify':
		        $where['pic_style'] = ['beautify'];
		        break;
		    case 'oem':
		    case 'competitor':
		    case 'other':
                $where['pic_style'] = $propictype;
		        break;
            case 'video': 
		        $where['pic_type'] = $propictype;
		        break;
		}
	    if($tsql!=''){ 
	        $where['RAW'] = raw($tsql);
	    }
		$where['ORDER'] = ['pic_sort'=>'ASC','pic_filebase'=>'ASC'];
        $rows = $this->db->select($table,$join,$fields,$where);
		foreach($rows as &$row){
		    $row['back'] = null;
		    $row['replay'] = null;
		    if($row['pic_status']=='0'){
		        //退回的图片
    			if(in_array($propictype,['init_add','init_check'])){
    			    $backFileid = $this->db->get('pro_pic','pic_fileid',[
    			        'pic_p_id'=>$row['pic_p_id'],
    			        'pic_style'=>'beautify_back',
    			        'pic_filebase'=>$row['pic_filebase'],
    			    ]);
    			    if(empty($backFileid)){
        			    $backFileid = $this->db->get('pro_pic','pic_fileid',[
        			        'pic_p_id'=>$row['pic_p_id'],
        			        'pic_style'=>'init_back',
        			        'pic_filebase'=>$row['pic_filebase'],
        			    ]);
    			    }
    			    $row['back'] = $this->getFileMoreById($backFileid);
    			}else if(in_array($propictype,['beautify_add','beautify_check'])){
    			    $backFileid = $this->db->get('pro_pic','pic_fileid',[
    			        'pic_p_id'=>$row['pic_p_id'],
    			        'pic_style'=>'beautify_back',
    			        'pic_filebase'=>$row['pic_filebase'],
    			    ]);
    			    $row['back'] = $this->getFileMoreById($backFileid);
    			}
    			//重拍的图片
    			if(in_array($propictype,['init_add','init_check'])){
    			    $backFileid = $this->db->get('pro_pic','pic_fileid',[
    			        'pic_p_id'=>$row['pic_p_id'],
    			        'pic_style'=>'beautify_replay',
    			        'pic_filebase'=>$row['pic_filebase'],
    			    ]);
    			    if(empty($backFileid)){
        			    $backFileid = $this->db->get('pro_pic','pic_fileid',[
        			        'pic_p_id'=>$row['pic_p_id'],
        			        'pic_style'=>'init_replay',
        			        'pic_filebase'=>$row['pic_filebase'],
        			    ]);
    			    }
    			    $row['replay'] = $this->getFileMoreById($backFileid);
    			}else if(in_array($propictype,['beautify_add','beautify_check'])){
    			    $backFileid = $this->db->get('pro_pic','pic_fileid',[
    			        'pic_p_id'=>$row['pic_p_id'],
    			        'pic_style'=>'beautify_replay',
    			        'pic_filebase'=>$row['pic_filebase'],
    			    ]);
    			    $row['replay'] = $this->getFileMoreById($backFileid);
    			}
		    }
		    $row['isback'] = strpos($row['pic_style'],'_back')>0;
		    $row['isreplay'] = strpos($row['pic_style'],'_replay')>0;
			$this->getFileMore($row);
            // 获取图片标签
            $tagJoin = [
                '[>]object(o)' => ['otl_o_id'=>'o_id']
            ];
            $tagWhere = ['otl_table'=>'pro','otl_type'=>'pic','otl_val_id'=> $row['pic_fileid']];
            $picTagRes = $this->db->select('object_tags_link',$tagJoin,'o.'.LG_NAME,$tagWhere);
            $row['pic_tags'] = implode(',',$picTagRes);
		}
        unset($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['orgfilename'] = $row['filename'];
		$row['filename'] = \mvc::$cfg['urls']['outfiles'].'/'. ltrim(str_replace('\\','/',$row['filename']),'/');
 		if($row['filetype']=='image'){
			$row['smallfile'] = filenameSize($row['filename'],'small');
			$row['bigfile'] = filenameSize($row['filename'],'big');
			//原始图片扩展名
            if($row['file_isoss']){
                $row['initfile'] = \model\alioss::getPublicUrl($row['file_oss_path']);
            }else{
                $row['initfile'] = substr($row['filename'],0,strrpos($row['filename'],'.')).'.'.$row['fileextname']; 
            }
            if($row['initfile']){
                $row['initfile'] .='?t='.time();
            }
		    
		}elseif ($row['filetype']=='video') {
            if($row['file_isoss']){
                $row['initfile'] = \model\alioss::getPublicUrl($row['file_oss_path']);
            }else{
                $row['initfile'] = substr($row['filename'],0,strrpos($row['filename'],'.')).'.'.$row['fileextname']; 
            }
        }
        else{
			$row['smallfile'] = $row['filename'];
			$row['bigfile'] = $row['filename'];
		}
        //前端显示可能有缓存
        if($row['smallfile']){
            $row['smallfile'] .='?t='.time();
        }
        if($row['bigfile']){
            $row['bigfile'] .='?t='.time();
        }
		return $row;
   }
    
    //设置主图
    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(),
                'ps_create_time'=>getNowTime(),
                'ps_update_time'=>getNowTime()
            ];
            $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();

		return $fileid;
	}
    
    //删除文件
    public function deleteFile($pid,$fileid)
    {
		$this->db->begin();
        $rows = $this->db->get('files','*',['fileid'=>$fileid]);
        //删除oss
        if($rows['file_isoss']){
            $alioss = new alioss();
            $alioss->deleteObject($rows['file_oss_path'],$rows['file_oss_verid']);
        }
		$this->db->delete('pro_pic',['pic_p_id'=>$pid,'pic_fileid'=>$fileid]);
		$this->files->delete($fileid);
		return $this->db->end();
    }
    
    //删除
    public function saveDeletes($pid,$items,$propicType)
    {
        if(empty($pid) || empty($items) || empty($propicType))
            return false;
        $where = [
            'pic_p_id'=>$pid,
            'pic_fileid'=>$items,
        ];
        //上原始图片者仅删除自己的类型
        if(in_array($propicType,['init_add','beautify_add'])){
            $where['pic_style'] = $propicType;
        }
        //审核人不能操作已审核的
        if(in_array($propicType,['init_check','beautify_check'])){
            $where['pic_status'] = 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','*',['pic_p_id'=>$pid]);
            //     foreach($finds as $frow){
            //         $this->deleteFile($pid,$frow['pic_fileid']);
            //     }
            // }
            $this->deleteFile($pid,$row['pic_fileid']);         
        }
        //上原始图片者或原始图审核者如果全删除了图片，则将任务中的提交时间置空
        if(in_array($propicType,['init_add','init_check'])){
            if(!$this->db->has('pro_pic',['pic_p_id'=>$pid,'pic_style'=>$propicType])){
                $data = [
                    'ppt_submit_user'=>'',
                    'ppt_submit_time'=>null,
                ];
                $this->db->update('pro_pic_task',$data,['ppt_p_id'=>$pid]);
            }
        }
        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 = [
            'pic_p_id'=>$pid,
            'pic_fileid'=>$items,
        ];
        //审核人不能操作已审核的
        if(in_array($propicType,['init_check','beautify_check'])){
            $where['pic_status'] = 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','pic_fileid',['pic_p_id'=>$pid,'pic_style'=>$replayType,'pic_filebase'=>$row['pic_filebase']]))
            {
                //$this->deleteFile($pid,$findFieldId);
                $this->files->delete($findFieldId);
            }
			if(in_array($propicType,['beautify'])){
				$this->db->update('pro_pic',['pic_style'=>'init_replay','pic_status'=>0, 'pic_remark'=>$remark]
					,['pic_p_id'=>$pid,'pic_filebase'=>$row['pic_filebase'],'pic_style'=>'init']);
				$this->db->update('pro_pic',['pic_style'=>'beautify_replay','pic_status'=>0, 'pic_remark'=>$remark]
					,['pic_p_id'=>$pid,'pic_filebase'=>$row['pic_filebase'],'pic_style'=>'beautify']);
			}else{
				$this->db->update('pro_pic',['pic_style'=>'init_replay','pic_status'=>0, 'pic_remark'=>$remark]
				    ,['pic_p_id'=>$pid,'pic_fileid'=>$row['pic_fileid']]);
			}
        }
        $this->db->delete('pro_pic_task',['ppt_p_id'=>$pid]);
        $this->addPicTask($pid);

        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='', $force = false)
    {
        if(empty($pid) || empty($items) || empty($propicType))
            return false;
        $where = [
            'pic_p_id'=>$pid,
            'pic_fileid'=>$items,
        ];
        //审核人不能操作已审核的
        if(in_array($propicType,['init_check','beautify_check'])){
            $where['pic_status'] = 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','pic_fileid',['pic_p_id'=>$pid,'pic_style'=>$backType,'pic_filebase'=>$row['pic_filebase']]))
            {
                $this->deleteFile($pid,$findBackFieldId);
            }
			if(in_array($propicType,['beautify'])){
				$this->db->update('pro_pic',['pic_style'=>'init_back','pic_status'=>0, 'pic_remark'=>$remark]
					,['pic_p_id'=>$pid,'pic_filebase'=>$row['pic_filebase'],'pic_style'=>'init']);
				$this->db->update('pro_pic',['pic_style'=>'beautify_back','pic_status'=>0, 'pic_remark'=>$remark]
					,['pic_p_id'=>$pid,'pic_filebase'=>$row['pic_filebase'],'pic_style'=>'beautify']);
            } elseif (in_array($propicType, ['init'])) {
                $this->db->update(
                    'pro_pic',
                    ['pic_style' => 'init_back', 'pic_status' => 0, 'pic_remark' => $remark],
                    ['pic_p_id' => $pid, 'pic_fileid' => $row['pic_fileid']]
                );
            } elseif (in_array($propicType, ['beautify_back'])) {
                $this->db->update(
                    'pro_pic', 
                    ['pic_style' => 'beautify_back', 'pic_status' => 0],
                    ['pic_p_id' => $pid, 'pic_fileid' => $row['pic_fileid']]
                );
            } elseif (in_array($propicType, ['init_back'])) {
                $this->db->update(
                    'pro_pic',
                    ['pic_style' => 'init_back', 'pic_status' => 0],
                    ['pic_p_id' => $pid, 'pic_fileid' => $row['pic_fileid']]
                );
			}
            
            
            $updateData = ['pic_style'=>$backType,'pic_status'=>0];
            if($remark!=''){
                $updateData['pic_remark'] = $remark;
            }
            $this->db->update('pro_pic',$updateData,['pic_p_id'=>$pid,'pic_fileid'=>$row['pic_fileid']]);
        }
        $this->db->delete('pro_pic_task',['ppt_p_id'=>$pid]);
        $this->addPicTask($pid);
        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,$isbeautify)
    {
        if(empty($pid) || empty($items) || empty($propicType))
            return false;
        $bigType = explode('_',$propicType)[0];
        $where = [
            'pic_p_id'=>$pid,
            'pic_fileid'=>$items,
            'pic_status'=>0,
        ];
        $rows = $this->db->select('pro_pic','*',$where);
        $this->db->begin();
  
		foreach($rows as $row){
            // //删除同名退回与重拍及重复图片
            // $delWhere = [
            //     'pic_p_id'=>$pid,
            //     'pic_fileid'=>$row['pic_fileid'],
            //     'pic_fileid[!]'=>$row['pic_fileid'],
            //     'pic_style'=>[$bigType.'_back',$bigType.'_replay',$bigType],
            //     'pic_filebase'=>$row['pic_filebase']
            // ] ;
            // $findDelRows = $this->db->select('pro_pic','*',$delWhere)
            // if($findDelRows){
            //     foreach ($findDelRows as $delRow){
            //         $this->deleteFile($pid,$delRow['pic_fileid']);
            //     }
            //     // $this->db->delete('pro_pic',$delWhere);
            // }
            //更换类型
            $this->db->update('pro_pic',['pic_check_user'=>getOpuser(),'pic_check_time'=>getNowTime() ,'pic_status'=>1,'pic_style'=>$bigType,'pic_isbeautify'=>$isbeautify],['pic_p_id'=>$pid,'pic_fileid'=>$row['pic_fileid']]);
        }
        //如果图片都审核过了，删除任务清单记录
        if(!$this->db->has('pro_pic',['pic_p_id'=>$pid,'pic_style'=>['init_add','beautify_add']]))
        {
            if($this->db->has('pro_pic',['pic_p_id'=>$pid,'pic_style'=>['init','beautify']])){
                $this->db->delete('pro_pic_task',['ppt_p_id'=>$pid]);
            }
        }
        return $this->db->end();
    }
    
    //加载任意备注
    public function loadAnyRemark($type,$filebase)
    {
        $remark = '';
        if($type=='init_back'){
            $row = $this->db->get('pro_pic',
                ['pic_style','pic_remark'],['pic_style'=>'beautify_back','pic_filebase'=>$filebase,'pic_remark[!]'=>'','pic_remark[!]'=>NULL]);
            if(empty($row)){
                $row = $this->db->get('pro_pic',
                    ['pic_style','pic_remark'],['pic_style'=>'init_back','pic_filebase'=>$filebase,'pic_remark[!]'=>'','pic_remark[!]'=>NULL]);
            }
        }else if($type=='init_replay'){
            $row = $this->db->get('pro_pic',
                ['pic_style','pic_remark'],['pic_style'=>'beautify_replay','pic_filebase'=>$filebase,'pic_remark[!]'=>'','pic_remark[!]'=>NULL]);
            if(empty($row)){
                $row = $this->db->get('pro_pic',
                    ['pic_style','pic_remark'],['pic_style'=>'init_replay','pic_filebase'=>$filebase,'pic_remark[!]'=>'','pic_remark[!]'=>NULL]);
            }
        }else{
            $row = $this->db->get('pro_pic',
                ['pic_style','pic_remark'],['pic_style'=>'init_replay','pic_filebase'=>$filebase,'pic_remark[!]'=>'','pic_remark[!]'=>NULL]);
        }  
        $remark = $row['pic_remark'] ;
        return $remark;
    }
    
    //保存名称与备注
    public function saveNameAndRemark($pid,$items,$propicType)
    {
        if(empty($pid) || empty($items) || empty($propicType))
            return false;

        $this->db->begin();
        foreach($items as $item){
            $where = [
                'pic_p_id'=>$pid,
                'pic_fileid'=>$item['fileid'],
            ];
            $data = [
                'pic_filebase'=>$item['filebase'],
                'pic_remark'=>$item['remark'],
                'pic_lang'=>$item['lang'],
            ];
           
            $this->db->update('pro_pic',$data,$where);
        }
        return $this->db->end();
    }

    /**
     * 添加产品到拍照清单
     * @param string $begin 开始日期
     * @param string $end 结束日期
     * @return mixed
     */
    public function addPicTask($p_id)
    {   
        $innum = $this->db->get('pro','p_innum',['p_id'=>$p_id]);
        $date = getNowDate();
        $now = getNowTime();
        if(!$innum ){
           return ['error'=>false, 'type'=> 'notfound', 'innum'=>$innum];
        }
        $has = $this->db->has('pro_pic_task',['ppt_p_id'=>$p_id]);
        if($has){
            return ['error'=>true, 'type'=> 'has', 'innum'=>$innum];
        }else{
            $data = [
                'ppt_p_id'=>$p_id,
                'ppt_orderno'=>'',
                'ppt_orderid'=>0,
                'ppt_remark'=>$remark??'',
                'ppt_submit_user'=>null,
                'ppt_submit_time'=>null,
                'ppt_create_time'=>$now,
                'ppt_update_time'=>$now,
            ];
            $result = $this->db->replace('pro_pic_task',$data,'ppt_p_id');
            return ['error'=>false,'type'=> $result, 'innum'=>$innum];
        }
    }

     
    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['pic_p_id']){
                $row[$item['pic_style']] = 1;
                $row['create_time'] = $item['create_time'];
                $row['update_time'] = $item['update_time'];
                if($item['pic_style']=='init' or $item['pic_style']=='init_add'){
                    $row['init_has'] = 1;
                }elseif($item['pic_style']=='beautify' or $item['pic_style']=='beautify_add'){
                    $row['beautify_has'] = 1;
                }
                if($item['pic_type']=='video'){
                    $row['video'] = 1;
                }
            }
        }
        return $row;
    }
    

    /**
     * @method 获取任务清单数据
     * @author zhengweihua 
     * @copyright 2026-03-10
     */
    public function getTaskList($params, $rules = [])
    {
        $filters = $params['filters'];
		$page = $params['page'];
		$pagesize = $params['rows'];
		$sidx = empty($params['sidx'])? 'ppt_id': $params['sidx'];
		$sord = empty($params['sord'])? 'desc': $params['sord'];
		$orderby = $params['orderby'];

		$table = 'pro_pic_task(ppt)';
		$join = [
			"[><]pro(pro)" => ["ppt.ppt_p_id" => "p_id"],
            "[><]pro_brand(pb)" => ["pro.p_pb_id" => "pb_id"],
            "[><]pro_factory(fac)"=>['pro.p_pf_id'=>'pf_id'],
            "[><]pro_cate(cate)"=>['pro.p_cate'=>'id'],
			"[>]adm_user(au)"=>['ppt.ppt_submit_user'=>'au_id']
		];
		$refiled = [
			'cate_name'=>'cate.'.cateName(),
			'p_oe'=>'p_oe_format',
            'p_comnum'=>'p_comnum_format',
            'p_innum'=>'p_innum_format',
            'p_pb_name'=>'p_pb_id',
		];
		$this->set('refiled', $refiled);
        $where = $this->filter2medoo($filters,function(&$field,&$op,&$data){
            $field = strtr( $field, $this->get('refiled'));
            if(in_array($field,['p_oe_format','p_comnum_format','p_innum_format'])){
                $data = formatNum($data);
            }
        });

        foreach($rules as $filed=>$val)
		{
			if(empty($val)) continue;
			switch($filed)
			{
				case 'numbers':
					$tnums = [];
					foreach($val as $tk=>$tv){
						$tnums = array_merge($tnums, reSearchNum($tv));
					}
					$tnums = array_unique($tnums);
                    $join['[><]pro_numidx(pn)'] = ['pro.p_id'=>'pn_p_id'];
					$where['pn_formart'.($rules['numlike']? '[~]': '')] = $tnums;
                    $where['GROUP'] ='ppt_p_id';
				break;
                case 'proBrand': $where['p_pb_id'] = explode(',', $rules['proBrand']); break;
			}
		}

		if(!empty($params['pid'])) $where['ppt_p_id'] = $params['pid'];
        //权限 - 商品品牌
        if(!empty($params['pwcode'])){
            $proBrands = \p::areas($params['pwcode']);
            if(!\p::isAdmin() && $proBrands){
                $where['AND #rule_brand'] = ['p_pb_id'=>explode(',',$proBrands)];
            }
        }
       

        $where = $this->listWhere($where,$page,$pagesize,$sidx,$sord,$orderby);
		if($page>0 && $pagesize>0){
			$fields = '*';
			$pages = $this->paging($table,$join,$fields,$where,$page,$pagesize);
			$where["LIMIT"] = [$pages['limit'],$pagesize];
		}
		
		$fields = ['ppt.*','p_id','p_comnum','p_innum','p_oe','pf_name','pb_cn_name(p_pb_name)','p_cn_name(p_name)',cateName().'(cate_name)','au_name'];
        $arr = $this->db->select($table,$join,$fields,$where);
	
		$data = [
			'page'=> $page,
			'total'=> $pages['total'],
			'records' => $pages['records'],
			'rows' => $arr
		];
		return $data;
    }

    /**
     * @method 删除任务清单数据
     * @author zhengweihua 
     * @copyright 2026-03-16
     */
    public function delTaskData($ids)
    {
       
        $idsArr = $this->db->select('pro_pic_task','ppt_id',['ppt_id'=>$ids]);
        if(!$idsArr){
            return exitJson('没有找到相关数据');
        }
        $this->db->begin();
        $this->db->delete('pro_pic_task',['ppt_id'=>$idsArr]);
        $this->db->end();
        return [];
    }


    /**
     * 验证并处理图片数据
     */
    public function validateImageData($imageData)
    {
        // 检查是否为base64格式
        if (preg_match('/^data:image\/(\w+);base64,/', $imageData, $matches)) {
            $imageFormat = $matches[1];
            $imageDataClean = substr($imageData, strpos($imageData, ',') + 1);
            
            // 验证base64数据
            if (!base64_decode($imageDataClean, true)) {
                return false;
            }
        
            // 验证图片格式
            $allowedFormats = ['jpeg', 'jpg', 'png', 'gif', 'webp'];
            if (!in_array(strtolower($imageFormat), $allowedFormats)) {
                throw new \Exception('不支持的图片格式');
            }
            
            return $imageData;
        }elseif (filter_var($imageData, FILTER_VALIDATE_URL)) {
            // 判断是否为有效的图片URL
            $urlInfo = parse_url($imageData);
            $pathInfo = pathinfo($urlInfo['path']);
            $extension = strtolower($pathInfo['extension'] ?? '');
            
            $allowedExtensions = ['jpeg', 'jpg', 'png', 'gif', 'webp'];
            if (!in_array($extension, $allowedExtensions)) {
                throw new \Exception('不支持的图片格式');
            }
              // 获取文件 MIME 类型
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mimeType = finfo_file($finfo, $imageData);
            finfo_close($finfo);
            $imageDataClean ='data:image/'.$mimeType.';base64,'. base64_encode(file_get_contents($imageData));
            
            return $imageData;
        }
        
        return false;
    }

    /**
     * @method 保存处理完的图片
     * @author zhengweihua 
     * @copyright 2026-03-20
     */
    public function saveProcessedImage($fileid,$imageData)
    {
        $arr = $this->db->get('files','*',['fileid'=>$fileid]);
        if(!$arr){
            exitJson(-1,'没有找到图片相关数据');
        }
        $this->db->begin();
        //如果是云存储，需要把新的文件内容上传到云存储，保持文件的内容
        if($arr['file_isoss']){
            $tmpBase = \mvc::$cfg['dir']['cache'].'/'.date('Y-m');
            $operationDir = $tmpBase . '/operation_' . date('Ymd_His') . '_' . uniqid();
            @mkdir($operationDir, 0777, true);
            //把base64数据转换成文件内容
            if (preg_match('/^data:image\/(\w+);base64,/', $imageData, $matches)) {
                // 是base64格式，先保存为临时文件
                $imageFormat = $matches[1];
                $imageDataClean = substr($imageData, strpos($imageData, ',') + 1);
                $imageContent = base64_decode($imageDataClean);
                
                if ($imageContent === false) {
                    throw new \Exception('base64数据解码失败');
                }
                // 生成临时文件
                $tempFilePath = $operationDir . '/input_image.' . $imageFormat;
                $result = file_put_contents($tempFilePath, $imageContent);
                $imagePath = $tempFilePath;
            } else {
                // 是文件路径
                $imagePath = $imageData;
            }
            $alioss = new alioss();
            $result = $alioss->putObjectWithVersioning($arr['file_oss_path'],$imagePath);
            //版本ID会变更
            $this->db->update('files',['file_oss_verid'=>$result['VersionId']],['fileid'=>$fileid]);
        }

        $files = new files();
        $newid = $files->add($arr['fileremark'], $imagePath, $arr['filepath'], $arr['filebasename'], $arr['fileextname'], $arr['file_category'], $arr['file_item'], null, true,$arr['file_isoss'], $arr['file_oss_path'],$result['VersionId']?:$arr['file_oss_verid']);
        $this->db->end();
        if($newid){
            return $newid;
        }
        
    }
    
    /**
     * @method 保存到精修海报图中
     * @author zhengweihua 
     * @copyright 2026-03-20
     */
    public function saveBeautifyImage($fileid,$imageData)
    {
        $this->saveProcessedImage($fileid,$imageData);
        //变更图片状态
        $this->db->update('pro_pic',['pic_status'=>0,'pic_style'=>'beautify_add'],['pic_fileid'=>$fileid]);
    }

    

    /**
     * @method 获取商品图片状态列表
     * @author hongzhang
     * @copyright 2026-03-30
     */
    public function getProImageStatus($params,$rules)
    {
        $filters = $params['filters'];
		$page = $params['page'];
		$pagesize = $params['rows'];
		$sidx = empty($params['sidx'])? '': $params['sidx'];
		$sord = empty($params['sord'])? 'asc': $params['sord'];
		$orderby = $params['orderby'];
        $table = 'pro(pro)';
        $join = [
            '[>]pro_cate(cat)'=>['pro.p_cate' => 'id'],
            '[>]pro_cate(pcat)'=>['cat.parent_id' => 'id'],
            '[>]pro_brand'=>['pro.p_pb_id' => 'pb_id']
        ];

        $refiled = [
			'cat_name'=>'cat.'.cateName(),
			'pcat_name'=>'pcat.'.cateName(),
		];
		$this->set('refiled', $refiled);
		$sidx =  strtr($sidx, $refiled);

        $where = $this->filter2medoo($filters,function(&$field,&$op,&$data){
            $field = strtr( $field, $this->get('refiled'));
            
             if($field == 'init_has'){
                $op = 'sql';
                if($data){
                    $data = " EXISTS(SELECT 1 FROM pro_pic WHERE pic_p_id = pro.p_id AND (pic_style='init_add' OR pic_style='init'))";
                }else{
                    $data = " NOT EXISTS(SELECT 1 FROM pro_pic WHERE pic_p_id = pro.p_id AND (pic_style='init_add' OR pic_style='init'))";
                }
             }elseif($field == 'beautify_has'){
                $op = 'sql';
                if($data){
                    $data = " EXISTS(SELECT 1 FROM pro_pic WHERE pic_p_id = pro.p_id AND (pic_style='beautify_add' OR pic_style='beautify'))";
                }else{
                    $data = " NOT EXISTS(SELECT 1 FROM pro_pic WHERE pic_p_id = pro.p_id AND (pic_style='beautify_add' OR pic_style='beautify'))";
                }
             }else if(in_array($field,['init','beautify','oem','competitor','other'])){
                $op = 'sql';
                if($data){
                    $data = " EXISTS(SELECT 1 FROM pro_pic WHERE pic_p_id = pro.p_id AND pic_style='$field')";
                }else{
                    $data = " NOT EXISTS(SELECT 1 FROM pro_pic WHERE pic_p_id = pro.p_id AND pic_style='$field')";
                }
             }else if($field == 'video'){
                $op = 'sql';
                if($data){
                    $data = " EXISTS(SELECT 1 FROM pro_pic WHERE pic_p_id = pro.p_id AND pic_type='video')";
                }else{
                    $data = " NOT EXISTS(SELECT 1 FROM pro_pic WHERE pic_p_id = pro.p_id AND pic_type='video')";
                }
             }
        });

        foreach($rules as $filed=>$val){
            switch($filed){
                case 'numbers':
					$tnums = [];
					foreach($val as $tk=>$tv){
						$tnums = array_merge($tnums, reSearchNum($tv));
					}
					$tnums = array_unique($tnums);
					if($rules['numlike']) {
						// 使用EXISTS优化模糊查询
						$likeConditions = [];
						foreach ($tnums as $num) {
							if(!$num) continue;
							$likeConditions[] = sprintf("pn_formart LIKE '%s%%'", $num);
						}
						
						if (!empty($likeConditions)) {
							$likeWhere = implode(' OR ', $likeConditions);
							$sql = sprintf("
								SELECT 1 
								FROM pro_numidx 
								WHERE (pn_p_id = pro.p_id OR pn_p_id = pro.p_lnk_p_id) 
								  AND (%s)
								LIMIT 1
							", $likeWhere);
							
							$where['RAW_'.$filed] = raw(sprintf("EXISTS (%s)", $sql));
						}
					} else {
						// 使用EXISTS优化精确查询
						if (!empty($tnums)) {
							$numstr = implode(',', array_map(function($num) { 
								return "'".formatNum($num)."'"; 
							}, $tnums));
							
							$sql = sprintf("
								SELECT 1 
								FROM pro_numidx 
								WHERE (pn_p_id = pro.p_id OR pn_p_id = pro.p_lnk_p_id) 
								  AND pn_formart IN (%s)
								LIMIT 1
							", $numstr);
							
							$where['RAW_'.$filed] = raw(sprintf("EXISTS (%s)", $sql));
						}
					}
				break;
                case 'p_cate': $where['p_cate'] = explode(',', $rules['p_cate']); break;
				case 'proBrand': $where['p_pb_id'] = explode(',', $rules['proBrand']); break;
            }
        }

        //权限 - 商品品牌
        if(!empty($params['pwcode'])){
            $proBrands = \p::areas($params['pwcode']);
            if(!\p::isAdmin() && $proBrands){
                $where['AND #rule_brand'] = ['p_pb_id'=>explode(',',$proBrands)];
            }
        }

        $where = $this->listWhere($where,$page,$pagesize,$sidx,$sord,$orderby);
        if($page>0 && $pagesize>0){
			$fields = '*';
			$pages = $this->paging($table,$join,$fields,$where,$page,$pagesize);
			$where["LIMIT"] = [$pages['limit'],$pagesize];
		}
        if(!isset($where['ORDER']) || empty($where['ORDER'])){
            $where['ORDER'] = ['p_id'=>'DESC'];
        }
        $fields = ['p_id','p_comnum','p_comnum_format','p_innum','p_innum_format','p_pb_id','p_cate','pcat.'.cateName().'(pcat_name)','cat.'.cateName().'(cat_name)','pb_'.LG_NAME.'(pb_name)'];
        $arr = $this->db->select($table,$join, $fields,$where);
        $types = ['init_has','init','beautify_has','beautify','video','oem','competitor','other'];
        if($arr){
            $ids = array_column($arr,'p_id');
            $stateData = [];
            if($ids){
                $stateData = $this->db->select('pro_pic'
                ,['pic_status','pic_p_id','pic_type','pic_style','pic_create_time','pic_update_time']
                ,['pic_p_id' => $ids,'GROUP'=>['pic_p_id','pic_style','pic_type']
                ,'ORDER'=>'pic_update_time']);
            }
            foreach ($arr as $key => &$val){
               $val['captions'] = [
                'p_pb_id'=>$val['pb_name']
               ];
               $val = $this->getProPicState($val,$stateData,$types);
            }
        }
        $data = [
			'page'=> $page,
			'total'=> $pages['total'],
			'records' => $pages['records'],
			'rows' => $arr
		];
		return $data;
    }

    /**
     * @method 获取商品图片报表列表
     * @author hongzhang 
     * @copyright 2026-03-30
     */
    public function getProImageReport($params,$rules)
    {
        $filters = $params['filters'];
		$page = $params['page'];
		$pagesize = $params['rows'];
		$sidx = empty($params['sidx'])? '': $params['sidx'];
		$sord = empty($params['sord'])? 'asc': $params['sord'];
		$orderby = $params['orderby'];
        $table = 'pro(pro)';
        $join = [
            '[>]pro_cate(cat)'=>['pro.p_cate' => 'id'],
            '[>]pro_cate(pcat)'=>['cat.parent_id' => 'id'],
            '[>]pro_brand'=>['pro.p_pb_id' => 'pb_id'],
        ];
       
        $where = $this->filter2medoo($filters,function(&$field,&$op,&$data){
        });

        foreach($rules as $filed=>$val){
            switch($filed){
                case 'numbers':
					$tnums = [];
					foreach($val as $tk=>$tv){
						$tnums = array_merge($tnums, reSearchNum($tv));
					}
					$tnums = array_unique($tnums);
					if($rules['numlike']) {
						// 使用EXISTS优化模糊查询
						$likeConditions = [];
						foreach ($tnums as $num) {
							if(!$num) continue;
							$likeConditions[] = sprintf("pn_formart LIKE '%s%%'", $num);
						}
						
						if (!empty($likeConditions)) {
							$likeWhere = implode(' OR ', $likeConditions);
							$sql = sprintf("
								SELECT 1 
								FROM pro_numidx 
								WHERE (pn_p_id = pro.p_id OR pn_p_id = pro.p_lnk_p_id) 
								  AND (%s)
								LIMIT 1
							", $likeWhere);
							
							$where['RAW_'.$filed] = raw(sprintf("EXISTS (%s)", $sql));
						}
					} else {
						// 使用EXISTS优化精确查询
						if (!empty($tnums)) {
							$numstr = implode(',', array_map(function($num) { 
								return "'".formatNum($num)."'"; 
							}, $tnums));
							
							$sql = sprintf("
								SELECT 1 
								FROM pro_numidx 
								WHERE (pn_p_id = pro.p_id OR pn_p_id = pro.p_lnk_p_id) 
								  AND pn_formart IN (%s)
								LIMIT 1
							", $numstr);
							
							$where['RAW_'.$filed] = raw(sprintf("EXISTS (%s)", $sql));
						}
					}
				break;
                case 'p_cate': $where['p_cate'] = explode(',', $rules['p_cate']); break;
				case 'proBrand': $where['p_pb_id'] = explode(',', $rules['proBrand']); break;
            }
        }

        //权限 - 商品品牌
        if(!empty($params['pwcode'])){
            $proBrands = \p::areas($params['pwcode']);
            if(!\p::isAdmin() && $proBrands){
                $where['AND #rule_brand'] = ['p_pb_id'=>explode(',',$proBrands)];
            }
        }
        $where['RAW #pro_pic'] = raw("EXISTS(SELECT 1 FROM pro_pic WHERE pic_p_id=pro.p_id AND pic_type='img' AND pic_style!='selfup' LIMIT 1)");
       
        $where = $this->listWhere($where,$page,$pagesize,$sidx,$sord,$orderby);
        if($page>0 && $pagesize>0){
			$fields = '*';
			$pages = $this->paging($table,$join,$fields,$where,$page,$pagesize);
			$where["LIMIT"] = [$pages['limit'],$pagesize];
		}
        $fields = ['p_id','p_comnum','p_comnum_format','p_innum','p_innum_format','p_pb_id','p_cate','pcat.'.cateName().'(pcat_name)','cat.'.cateName().'(cat_name)','pb_'.LG_NAME.'(pb_name)'];
        $fields['upload_qty'] = raw("(SELECT count(1) FROM pro_pic WHERE pic_p_id=pro.p_id AND pic_type='img' AND pic_style!='selfup')");
        $fields['download_qty'] = raw("(SELECT count(1) FROM pro_pic WHERE pic_p_id=pro.p_id AND pic_desexport_time IS NOT NULL)");
        $fields['upload_lasttime'] = raw("(SELECT MAX(file_time) FROM pro_pic LEFT JOIN files ON pro_pic.pic_fileid = files.fileid WHERE pro_pic.pic_p_id=pro.p_id AND pic_type='img' AND pic_style!='selfup')");
        $fields['download_lasttime'] = raw("(SELECT MAX(pic_desexport_time) FROM pro_pic WHERE pic_p_id=pro.p_id AND pic_desexport_time IS NOT NULL)");
        if(!isset($where['ORDER']) || empty($where['ORDER'])){
            $where['ORDER'] = ['p_id'=>'DESC'];
        } 
        
        $arr = $this->db->select($table,$join, $fields,$where);
        $types = ['init_has','init','beautify_has','beautify','video','oem','competitor','other'];
        if($arr){
            $ids = array_column($arr,'p_id');
            $stateData = [];
            if($ids){
                $stateData = $this->db->select('pro_pic'
                ,['pic_status','pic_p_id','pic_type','pic_style','pic_create_time','pic_update_time']
                ,['pic_p_id' => $ids,'GROUP'=>['pic_p_id','pic_style','pic_type']
                ,'ORDER'=>'pic_update_time']);
            }
            foreach ($arr as $key => &$val){
               $val['captions'] = [
                'p_pb_id'=>$val['pb_name']
               ];
               $val = $this->getProPicState($val,$stateData,$types);
            }
        }
        $data = [
			'page'=> $page,
			'total'=> $pages['total'],
			'records' => $pages['records'],
			'rows' => $arr
		];
		return $data;
    }

    
    /**
     * @method 批量设置图片语言
     * @author hongzhang 
     * @copyright 2026-04-02
     */
    public function setLangs($fileids,$lang,$action='set')
    {
        if(is_string($fileids)){
            $fileids = explode(',',$fileids);
        }
        if(empty($fileids) || !is_array($fileids)){
            return false;
        }
        $ids = [];
        foreach($fileids as $fileid){
            if($fileid==='' || $fileid===null){
                continue;
            }
            $ids[] = $fileid;
        }
        if(empty($ids)){
            return false;
        }
        if($action==='unset'){
            $this->db->update('pro_pic',['pic_lang'=>''],['pic_fileid'=>$ids,'pic_lang'=>$lang]);
        }else{
            $this->db->update('pro_pic',['pic_lang'=>$lang],['pic_fileid'=>$ids]);
        }
        return true;
    }

    public function getFilesByPidArr($pidArr,$propictype='',$rules=null)
    {

        $table = 'pro_pic';
		$join['[>]files'] = ['pic_fileid'=>'fileid'];
        if($rules['objectVer']){
            $join['[><]object_tags_link'] = ['pic_fileid'=>'otl_val_id'];
            $where['otl_o_id'] = $rules['objectVer'];
            $where['otl_table'] = 'pro';
            $where['otl_type'] = 'pic';
            $where['GROUP'] = ['pic_fileid'];
        }
        
        if(!empty($rules['langs'])){
            if($rules['langs']=='unset'){
                $where['pic_lang'] = '';
            }else{
                $where['pic_lang'] = $rules['langs'];
            }
        }
		$fields = '*';
        $where['pic_p_id'] = $pidArr;
        $tsql = '';
		switch ($propictype) {
		    case 'init_add':
		        $where['pic_style'] = ['init_add','init_back','init_replay'];
		        break;
		    case 'init_back':
		        $where['pic_style'] = ['init_back','init_replay'];
		        break;
		    case 'init_del':
		        $where['pic_style'] = 'init_del';
		        break;
		    case 'init_check':
		        $where['pic_style'] = ['init_add','init'];
		        break;
		    case 'designer':
		        $where['pic_style'] = 'init';
                $where['pic_isbeautify'] = 1;
		        if($rules){
    			    if($rules['checkOption']=='1'){
        			    $where['pic_desexport_time[!]'] = null; //已导出
    			    }else if($rules['checkOption']=='-1'){
        			    $where['pic_desexport_time'] = null; //未导出
    			    }
		        }
		    case 'init':
		        $where['pic_style'] = 'init';
		        break;
		    case 'beautify_add':
		        $where['pic_style'] = ['beautify_add','beautify_back','beautify_replay'];
		        break;
		    case 'beautify_check':
		        $where['pic_style'] = ['beautify_add','beautify'];
		        break;
		    case 'beautify_back':
		        $where['pic_style'] = ['beautify_back','beautify_replay'];
		        break;
		    case 'beautify':
		        $where['pic_style'] = ['beautify'];
		        break;
		    case 'oem':
		    case 'competitor':
		    case 'other':
                $where['pic_style'] = $propictype;
		        break;
            case 'video': 
		        $where['pic_type'] = $propictype;
		        break;
		}
	    if($tsql!=''){ 
	        $where['RAW'] = raw($tsql);
	    }
		$where['ORDER'] = ['pic_sort'=>'ASC','pic_filebase'=>'ASC'];
     
        $rows = $this->db->select($table,$join,$fields,$where);
        $result = [];
        if($rows)
        {
           // 批量获取标签信息
            $tagJoin = [
                '[>]object(o)' => ['otl_o_id'=>'o_id']
            ];
            $picFileIds = array_column($rows, 'pic_fileid');
            $tagWhere = ['otl_table'=>'pro','otl_type'=>'pic','otl_val_id'=>$picFileIds];
            $picTags = $this->db->select('object_tags_link',$tagJoin,'*', $tagWhere);
            $tagMap = [];
            foreach($picTags as $tag) {
                $tagMap[$tag['otl_val_id']][] = $tag[LG_NAME];
            }
        
            $arr = [];
            foreach($rows as $row) {
                $row['isback'] = strpos($row['pic_style'],'_back')>0;
                $row['isreplay'] = strpos($row['pic_style'],'_replay')>0;
                $this->getFileMore($row);
                $row['pic_tags'] = isset($tagMap[$row['pic_fileid']]) ? implode(',', $tagMap[$row['pic_fileid']]) : '';
                $arr[$row['pic_p_id']][] = $row;
            }
            // 对每个 pid 的图片进行格式化，整合到主函数中
            
            foreach($arr as $pid => $files){
                // 整合formatFiles逻辑
                $data = [];
                foreach($files as $k=>$file){
                    $field = 'pic_'.$k;
                    $data[$field] = [
                        'pid' => $file['pic_p_id'],
                        'fileid' => $file['pic_fileid'],
                        'outnum' => $file['pic_outnum'],
                        'innum' => $file['pic_innum'],
                        'smallfile' => $file['smallfile'],
                        'bigfile' => $file['bigfile'],
                        'filename' => $file['filename'],
                        'initfile' => $file['initfile'],
                        'filebase' => strtoupper($file['pic_filebase']),
                        'remark' => $file['pic_remark'],
                        'lang' => $file['pic_lang'],
                        'fileremark' => $file['fileremark'],
                        'ischecked' => ($file['pic_status']=='1'),
                        'isback' => $file['isback'],
                        'back' => $file['back'],
                        'isreplay' => $file['isreplay'],
                        'replay' => $file['replay'],
                        'isdesexport' => !empty($file['pic_desexport_time']),
                        'desexport_time' => $file['pic_desexport_time'],
                        'update_time' => $file['pic_update_time'],
                        'pic_check_time' => $file['pic_check_time'],
                        'tags' => $file['pic_tags'],
                        'filetype' => $file['filetype'],
                    ];
                }
                
                // 处理重拍逻辑
                foreach($data as $k=>$v){
                    if($v['ischecked']==false){
                        foreach($data as $k2=>$v2){
                            if($v['fileid']!=$v2['fileid'] && $v['filebase']==$v2['filebase'] && $v2['ischecked']==true){
                                $data[$k]['isreplay'] = true;
                                $data[$k]['replay'] = [
                                    'bigfile'=>$v2['bigfile'],
                                    'initfile'=>$v2['initfile'],
                                ];
                                unset($data[$k2]);
                            }
                        }
                    }
                }
                
                // 重新索引
                $kData = [];
                $i=0;
                foreach($data as $k=>$v){
                    $field = 'pic_'.$i;
                    $kData[$field] = $v;
                    $i++;
                }
                
                $result[$pid] = $kData;
            } 
        }
        
        return $result;
       
    }

} 
