<?php 
namespace model\pro;
use model\files;
use model\oe;
use model\freyApi;

class synProPic extends \model
{   
    /**
     * @param  array $scm_no
     * @method 获取图片列表
     * @author zhengweihua 
     * @copyright 2025-04-22
     */
    public function getProPicList($scm_no = [])
    {
        $data = ['scm_no' => implode(',', $scm_no)];
        $urlPath = '/Pic.Pic/lists';
		$freyApi = new freyApi();
        $res = $freyApi->httpCurl($urlPath, 'POST', $data);
        return $res['data'];
    }

    /**
     * @param  string $pic_sn
     * @method  获取图片详情
     * @author zhengweihua 
     * @copyright 2025-04-22
     */
    public function getPicDetail($pic_sn)
    {
		$freyApi = new freyApi();
        $data = [
            'pic_sn' => $pic_sn,
            'token' => $freyApi->getToken()
        ];
        $urlPath = '/Pic.Pic/details';
        $res = $freyApi->httpCurl($urlPath, 'GET', $data);
        return $res['data'];
    }

    

    /**
     * @param  [type] $p_id
     * @param  [type] $data
     * @param  [type] $filename
     * @param  [type] $extname
     * @param  array  $options
     * @method 保存商品图片
     * @author zhengweihua 
     * @copyright 2025-04-22
     */
    public function saveProPic($p_id,$data,$filename,$extname,$options=[])
    {   
        //没有图片内容
        if(!$data) return '';

        $params = ['p_id'=>$p_id];
        $crc32 = strtoupper(dechex(crc32($data)));
		$has = $this->db->get('pro_pic',['[><]files'=>['pic_fileid'=>'fileid']],'*',['file_crc32'=>$crc32,'pic_p_id'=>$p_id,'pic_type'=>'img']);
		if($has){
            $file_exists = \mvc::$cfg['dir']['files'].'/'.$has['filename'];
            if(file_exists($file_exists)){
                return ['fileid'=>$has['fileid']];
            }else{
                $this->db->delete('pro_pic',['pic_fileid'=>$has['fileid']]);
            }
        } 
        $this->db->Begin();
        $fileid = $this->saveFiles('pro','img',$crc32,$filename,$extname,$params,$data);
        //图片保存失败
        if(!$fileid){
			$this->db->rollBack();
            $this->db->update('pro',['temp_pic_init'=>-1],['p_id'=>$p_id]);
            return '';
        }
        $remark = str_replace('.'.strtolower($extname),'',strtolower(basename($filename)));
    
        $data = [
            'pic_sup_id' =>0,
            'pic_p_id'=>$p_id,
            'pic_fileid'=>$fileid,
            'pic_type'=>'img',
            'pic_filebase'=>$remark,
            'pic_opuser'=>getOpuser(),
            'pic_create_time'=>getNowTime(),
            'pic_update_time'=>getNowTime(),
            'pic_from'=>$options['pic_from']?$options['pic_from']:0,
            'pic_ismain'=>0,
            'pic_unisn'=>$options['pic_sn']??'',
        ];
        $this->db->insert('pro_pic',$data);
    
        //是否存在人工的主图
        $mainpic = $this->db->get('pro_pic', 'pic_fileid', ['pic_p_id'=>$p_id, 'pic_from'=>99,'pic_type'=>'img', 'pic_ismain'=>1]);
		
        if(!$mainpic && $options['is_main']){
            $pro = new pro();
            $pro->setProMainPic($fileid,$p_id,'img');
        } 

        $this->db->update('pro',['p_pic_syntime'=>getNowTime()],['p_id'=>$p_id]);
        
        $this->db->End();
    }

    /**
     * @param  [type] $oe_id
     * @param  [type] $data
     * @param  [type] $filename
     * @param  [type] $extname
     * @param  array  $options
     * @method 保存零件图片
     * @author zhengweihua 
     * @copyright 2025-04-22
     */
    public function saveOePic($oe_id,$data,$filename,$extname,$options=[])
    {
        $params = ['oe_id'=>$oe_id];
        $pic_sn = $options['pic_sn']??'';
        if(!$pic_sn) return [];
		$has = $this->db->get('oe_pic',['[><]files'=>['pic_fileid'=>'fileid']],'*',['pic_unisn'=>$pic_sn,'pic_oe_id'=>$oe_id,'pic_type'=>'img']);
		if($has) {
            $file_exists = \mvc::$cfg['dir']['files'].'/'.$has['filename'];
            if(file_exists($file_exists)){
                return ['fileid'=>$has['fileid']];
            }else{
                $this->db->delete('oe_pic',['pic_fileid'=>$has['fileid']]);
            }
        }

        $crc32 = strtoupper(dechex(crc32($data)));
        $fileid = $this->saveFiles('poe','img',$crc32,$filename,$extname,$params,$data);
        $remark = str_replace('.'.strtolower($extname),'',strtolower(basename($filename)));
        

        $data = [
            'pic_sup_id' =>0,
            'pic_oe_id'=>$oe_id,
            'pic_fileid'=>$fileid,
            'pic_type'=>'img',
            'pic_filebase'=>$remark,
            'pic_opuser'=>getOpuser(),
            'pic_create_time'=>getNowTime(),
            'pic_update_time'=>getNowTime(),
            'pic_from'=>$options['pic_from']?$options['pic_from']:0,
            'pic_ismain'=>0,
            'pic_unisn'=>$options['pic_sn']??'',
        ];
        $this->db->insert('oe_pic',$data);
        

		//是否存在人工的主图
        $mainpic = $this->db->get('oe_pic', 'pic_fileid', ['pic_oe_id'=>$oe_id, 'pic_from'=>99,'pic_type'=>'img', 'pic_ismain'=>1]);
		if(!$mainpic && $options['is_main']){
            $oe = new oe();
            $oe->setOeMainPic($fileid,$oe_id,'img');
        } 
    }

    /**
     * @param  [type] $oe_id
     * @param  [type] $fileid
     * @param  [type] $extname
     * @param  [type] $options
     * @method 备份一份图片给零件
     * @author zhengweihua 
     * @copyright 2025-08-02
     */
    public function synPicToOe($oe_id,$fileid,$filename,$extname,$options)
    {
        $pic_sn = $options['pic_sn']??'';
        if(!$pic_sn) return [];
		$has = $this->db->get('oe_pic',['[><]files'=>['pic_fileid'=>'fileid']],'*',['pic_unisn'=>$pic_sn,'pic_fileid'=>$fileid,'pic_oe_id'=>$oe_id,'pic_type'=>'img']);
		if($has) {
            return ['fileid'=>$has['fileid']];
        }
        $remark = str_replace('.'.strtolower($extname),'',strtolower(basename($filename)));
        $data = [
            'pic_sup_id' =>0,
            'pic_oe_id'=>$oe_id,
            'pic_fileid'=>$fileid,
            'pic_type'=>'img',
            'pic_filebase'=>$remark,
            'pic_opuser'=>getOpuser(),
            'pic_create_time'=>getNowTime(),
            'pic_update_time'=>getNowTime(),
            'pic_from'=>1116,
            'pic_ismain'=>0,
            'pic_unisn'=>$options['pic_sn']??'',
        ];
        $this->db->insert('oe_pic',$data);
        //是否存在人工的主图
        $mainpic = $this->db->get('oe_pic', 'pic_fileid', ['pic_oe_id'=>$oe_id, 'pic_from'=>99,'pic_type'=>'img', 'pic_ismain'=>1]);
		if(!$mainpic && $options['is_main']){
            $oe = new oe();
            $oe->setOeMainPic($fileid,$oe_id,'img');
        } 
    }

    /**
     * @param  [type] $category
     * @param  [type] $item
     * @param  [type] $crc32
     * @param  [type] $filename
     * @param  [type] $extname
     * @param  [type] $params
     * @param  [type] $data
     * @method 保存图片
     * @author zhengweihua 
     * @copyright 2025-04-22
     */
    public function saveFiles($category,$item, $crc32,$filename,$extname,$params,$data)
    {   //不再维持同一个文件同一个记录
      
        //保存到files里
        $uploadID =  guid();
        $cfg = \mvc::$cfg['upload']['category'][$category]['items'][$item];

        if(isset($cfg['path'])){
            $dir = call_user_func_array($cfg['path'], [$uploadID,$item,$extname,$params,$filename]);
        }else{
            $dir = call_user_func_array(\mvc::$cfg['upload']['category'][$category]['path'],[$uploadID,$item,$extname,$params,$filename]);
        }
        if(isset($cfg['filebase'])){
            $filebase = call_user_func_array($cfg['filebase'],[$uploadID,$item,$extname,$params,$filename]);
        }else{
            $filebase = call_user_func_array(\mvc::$cfg['upload']['category'][$category]['filebase'], [$uploadID,$item,$extname,$params,$filename]);
        }

        $absdir = \mvc::$cfg['dir']['files'].'/'.$dir;

        mkdirs($absdir);
        if(isset($cfg['tojpeg']) && $cfg['tojpeg'] && $extname!='jpg'){
            $extname = 'jpg';
        }
        file_put_contents($absdir.'/'.$filebase.'.'.$extname, $data);
        $fileType = $cfg['filetype'];
        $remark = str_replace('.'.strtolower($extname),'',strtolower(basename($filename)));
    
        $this->db->Begin();
        $fileData = [
            'filename' => $dir.'/'.$filebase.'.'.$extname,
            'fileextname'=>$extname,
            'fileremark' => $remark,
            'filetype' => $fileType,
            'file_category' => $category,
            'file_item' => $item,
            'file_time' => getNowTime(),
            'file_crc32'=>$crc32,
            'filepath'=>$dir,
            'filebasename'=>$filebase
        ];
        $this->db->insert('files',$fileData);
        $fileid = $this->db->id();
       
		$files = new files();
		if(isset($fileType) && $fileType=='image'){
			$image = make(\lib\image::class,100);
			if(isset($cfg['tojpeg']) && $cfg['tojpeg'] && $extname!='jpg'){
				$dist = $dir.'/'.$filebase.'.jpg';
				$image->ToJPG($filename,\mvc::$cfg['dir']['files'].'/'.$dist,false);
				$files->updateFilename($dist,$fileid);
				$filename = \mvc::$cfg['dir']['files'].'/'.$dist;
			}
			if(isset($cfg['size'])){
			    //由大到小生成缩略图
			    $arrSize = $cfg['size'];
                uksort($arrSize,function($a,$b)use($arrSize){
                   return $arrSize[$b][0] - $arrSize[$a][0];
                });
			    $sizefilename = $absdir.'/'.$filebase.'.'.$extname;
                
				foreach($arrSize as $key=>$size){
                    if($key=='small'){
                        $sizefilename = $absdir.'/'.$filebase.'.'.$extname;
                    }
					$dist = $dir.'/'.$filebase.$key.'.jpg';
					$watermark = \mvc::$cfg['dir']['static'].'/images/watermark/'.$category.'/'.$item.'.png';
					if(file_exists($watermark)){
					    try {
    						$image->ResizeWatermark($sizefilename,\mvc::$cfg['dir']['files'].'/'.$dist,$size[0],$size[1],$watermark);
					    } catch (\Exception $e) {
					        $newid=0;
					    }
					}else{
					    try {
    						$image->Resize($sizefilename,\mvc::$cfg['dir']['files'].'/'.$dist,$size[0],$size[1]);
					    } catch (\Exception $e) {
					        $newid=0;
					    }
						$sizefilename = \mvc::$cfg['dir']['files'].'/'.$dist;
					}
				}
			}
    		if(isset($newid) && $newid==0){
    		    @unlink($filename);
    		}
		}
        $this->db->End();
        // 图片保存失败
        if(isset($newid) && $newid==0){
           return $newid;
        }
        return $fileid;
    }


    /**
     * @method 获取图片保存到excel中
     * @author zhengweihua 
     * @copyright 2025-04-24
     */
    public function savePicToExcel($path)
    {
        $inputFileName = $path; // Excel 文件路径
        // 使用 IOFactory 创建 Reader 对象
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
        $reader->setReadDataOnly(true); // 只读取数据，不读取样式等信息

        // 加载 Excel 文件
        $spreadsheet = $reader->load($inputFileName);
        $sheet = $spreadsheet->getActiveSheet();
      
        // 获取最大行数
        $highestRow = $sheet->getHighestRow();
        $sheet->getColumnDimension('AG')->setWidth(20);
        $sheet->getColumnDimension('AH')->setWidth(20);
        $sheet->getColumnDimension('AI')->setWidth(20);
        // 遍历 B 列的数据
        for ($row = 2; $row <= $highestRow; $row++) {
            $sheet->getRowDimension($row)->setRowHeight(50); // 设置行高
            $cellValue = $sheet->getCell('B' . $row)->getValue(); // 获取 B 列的值
            if(!$cellValue) continue;
            $cellValue = formatNum($cellValue);
            //原中台的主图
            $join = [
                '[><]pro_pic(pic)'=>['pro.p_id'=>'pic_p_id'],
                '[><]files'=>['pic.pic_fileid'=>'fileid'],
            ];
            $img1 = $this->db->get('pro',$join,['filepath','filename','filebasename','fileextname'],['p_comnum_format'=>$cellValue,'pic_type'=>'img','pic_ismain'=>1,'pic_from'=>'1116','pic_unisn[!]'=>'','LIMIT'=>1]);
            if($img1)
            {
                $imgPath = \mvc::$cfg['dir']['files'].'/'.$img1['filepath'].'/'.$img1['filebasename'].'small.'.$img1['fileextname'];
                if(file_exists($imgPath))
                {   
                    $fileSize = filesize($imgPath);
                    if($fileSize> 256)
                    {
                        $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
                        // 插入图片
                        $drawing->setPath($imgPath);
                        $drawing->setWidth(100);
                        $drawing->setCoordinates('AG'. $row);
                        $drawing->setWorksheet($sheet);
                    }
                   
                }else{
                    $img1 = '';
                }
            }
           
            //TCD图
            $img2 = $this->db->get('pro',$join,['filepath','filename','filebasename','fileextname'],['p_comnum_format'=>$cellValue,'pic_type'=>'img','pic_from'=>'1069','LIMIT'=>1]);
            if($img2)
            {
                $imgPath = \mvc::$cfg['dir']['files'].'/'.$img2['filepath'].'/'.$img2['filebasename'].'small.'.$img2['fileextname'];
                if(file_exists($imgPath))
                {   
                    $fileSize = filesize($imgPath);
                    if($fileSize> 256){
                        $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
                        // 插入图片
                        $drawing->setPath($imgPath);
                        $drawing->setWidth(100);
                        $drawing->setCoordinates('AH'. $row);
                        $drawing->setWorksheet($sheet);
                    }
          
                }
            }   
            //EPC图
            $img3 = $this->db->get('pro',$join,['filepath','filename','filebasename','fileextname'],['p_comnum_format'=>$cellValue,'pic_type'=>'img','pic_from'=>'1070','LIMIT'=>1]);
            if($img3)
            {
                $imgPath = \mvc::$cfg['dir']['files'].'/'.$img3['filepath'].'/'.$img3['filebasename'].'small.'.$img3['fileextname'];
                if(file_exists($imgPath))
                {   
                    $fileSize = filesize($imgPath);
                    if($fileSize> 256){
                        $drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
                        // 插入图片
                        $drawing->setPath($imgPath);
                        $drawing->setWidth(100);
                        $drawing->setCoordinates('AI'. $row);
                        $drawing->setWorksheet($sheet);
                    }
      
                }
            }
			if($row%100) file_put_contents(\mvc::$cfg['dir']['files'].'/log.txt', $row);
        }

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $newfile = str_replace('.xlsx', '_new.xlsx', $inputFileName);
		$writer->save($newfile); // 直接覆盖原始文件
		return [$newfile];
        /*ob_clean();
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$inputFileName.'"');
        header('Cache-Control: max-age=0');
        $writer->save("php://output"); */
    }


    /**
     * @param  [type] $start_date
     * @method 获取产品记录
     * @author zhengweihua 
     * @copyright 2025-06-17
     */
    public function getProLogList($params)
    {   
        if(!$params['start_date']){
           return [];
        }
        $data = $params;
        $data['end_date'] = $params['end_date']??date('Y-m-d',strtotime('+1 day'));
        $urlPath = '/Pdm.ProductLog/getLog';
		$freyApi = new freyApi();
        $res = $freyApi->httpCurl($urlPath, 'POST', $data);
        return $res['data']; 
    }

    /**
     * @param  array $product_ids
     * @method 获取产品信息列表
     * @author zhengweihua 
     * @copyright 2025-06-17
     */
    public function getProductInfoList($product_ids=[])
    {   
        if(empty($product_ids)) return [];
        $data = ['product_ids' => implode(',',$product_ids)];
        $urlPath = '/Pdm.ProductLog/getProductInfoList';
        $freyApi = new freyApi();
        $res = $freyApi->httpCurl($urlPath, 'POST', $data);
        return $res['data']; 
    }

    /**
     * @param  array $link_ids
     * @method  产品关联事业部信息
     * @author zhengweihua 
     * @copyright 2025-06-16
     */
    public function getCompanyLink($link_ids =[])
    {
        $data = ['link_ids' => implode(',',$link_ids)];
        $urlPath = '/Pdm.ProductLog/getCompanyLink';
        $freyApi = new freyApi();
        $res = $freyApi->httpCurl($urlPath, 'POST', $data);
        return $res['data']; 
    }

    /**
     * @method 获取配置数据
     * @author zhengweihua 
     * @copyright 2025-06-17
     */
    public function getConfigData()
    {
        $urlPath = '/Pdm.ProductLog/getConfigData';
		$freyApi = new freyApi();
        $res = $freyApi->httpCurl($urlPath, 'GET');
        return $res['data']; 
    }

    /**
     * @method 获取所有用户
     * @author zhengweihua 
     * @copyright 2025-06-18
     */
    public function getAllUser()
    {
        $urlPath = '/User/getAll';
        $freyApi = new freyApi();
        $res = $freyApi->httpCurl($urlPath, 'GET');
        return $res['data']; 
    }

    /**
     * @method 创建/更新 物料
     * @author zhengweihua 
     * @copyright 2025-07-02
     */
    public function pdmProductSave($ids)
    {   
        if(empty($ids)) return [];
        if(is_array($ids)){
            $p_ids = implode(',',$ids);
        }else{
            $p_ids = $ids;
        }
        $urlPath = '/Pdm.Product/save';
        $data = [
            'p_ids' => $p_ids
        ];
		$freyApi = new freyApi();
        $res = $freyApi->httpCurl($urlPath, 'POST', $data);
        return $res;
    }

    /**
     * @param  array $frey_nos
     * @method 同步事业部产品图片
     * @author zhengweihua 
     * @copyright 2025-07-17
     */
    public function getCompanyProductPics($frey_nos = [])
    {
        $data = ['frey_nos' => implode(',', $frey_nos)];
        $urlPath = '/Pic.Pic/GetCompanyProductPics';
		$freyApi = new freyApi();
        $res = $freyApi->httpCurl($urlPath, 'POST', $data);
        return $res['data'];  
    }


    public function getPicDetailByUrl($url)
    {   
        if(empty($url)) return [];
        $mimeMap = [
			'image/jpeg' => 'jpg',
			'image/png' => 'png',
			'image/gif' => 'gif',
			'image/bmp' => 'bmp',
			'image/webp' => 'webp'
		];
		
		//是否是有效网址
		if(filter_var($url, FILTER_VALIDATE_URL))
		{
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 设置超时时间为5秒
			$data = curl_exec($ch);
            
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			$contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

			
			if($httpCode >= 200 && $httpCode < 300 && !empty($data)) {
                $extname = $mimeMap[$contentType] ?? '';
                
                // 如果内容类型不是图片，返回空
                if(empty($extname)) {
                    errorLog(['url' => $url, 'html' => $data], 'synPrPic');
                    return [];
                }
                // 额外验证：检查内容是否真的是图片数据
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $actualMimeType = finfo_buffer($finfo, $data);
                finfo_close($finfo);
                
                $actualExt = $mimeMap[$actualMimeType] ?? '';
                if(empty($actualExt)) {
                    errorLog(['url' => $url, 'html' => $data], 'synPrPic');
                    return [];
                }
                
                return [
                    'data' => $data,
                    'ext' => $extname,
                ];
            }
		}
        errorLog(['url' => $url, 'html' => $data], 'synPrPic');
        return [];
    }
}
