<?php
namespace model;
/**
 * Class user
 * @package model
 */
class sys extends \model
{
	public function __construct()
    {
		parent::__construct();
	}
	
	public function test()
    {
        $sid = '52736';
		$OEHM_rows = $this->db->select('sample_numidx',['sn_number'],['sn_s_id'=>$sid,'sn_pro_factory'=>1]);
		$OEHM = '';
		foreach ($OEHM_rows as $OEHM_item){
		    if($OEHM!='') $OEHM.='/';
    		$OEHM .= trim($OEHM_item['sn_number']);//formatNum($OEHM);
		}
		$OEHM = substr($OEHM,0,255);
		dd($OEHM);
	}

	public function mysqlInfo(){;
	    if(isset(\mvc::$req['killid']) && is_numeric(\mvc::$req['killid'])){
	        $this->db->query('KILL '.\mvc::$req['killid']);
            echo 'KILL '.\mvc::$req['killid']."<br>";
	    }
        $data=[];
        $st = $this->db->query('SHOW PROCESSLIST;');
        $rows = $st->fetchAll();
        foreach($rows as $k=>$row){
            $data[$k] = $row;
        }
        
        $st = $this->db->query('SHOW GLOBAL VARIABLES');
        $rows = $st->fetchAll();
        foreach($rows as $row){
            $data[$row['Variable_name']] = $row['Value'];
        }
        return $data;
	}
	
    //保存Grid布局
    public function saveGridConfig($uuid,$jsonStr)
    {
		return $this->db->replace('grid_cfg',['gc_config'=>$jsonStr,'gc_uuid'=>$uuid,'gc_user'=>getOpuser()],['gc_uuid','gc_user']);
    }
	
    //获取Grid布局
    public function getGridConfig($uuid)
    {
		$jsonStr = $this->db->get('grid_cfg','gc_config',['gc_uuid'=>$uuid,'gc_user'=>getOpuser()]);
		if(empty($jsonStr)){
    		$jsonStr = $this->db->get('grid_cfg','gc_config',['gc_uuid'=>$uuid,'gc_user'=>'grid']);
		}
		return $jsonStr;
    }
	
    //重置Grid布局
    public function resetGridConfig($uuid)
    {
		return $this->db->delete('grid_cfg',['gc_uuid'=>$uuid,'gc_user'=>getOpuser()]);
    }
    
    //检测是否有PNG图
	public function checkPNG(){
        $dir = \mvc::$cfg['dir']['files'];
	    $this->db->useBuff(false);
        $st = $this->db->query("SELECT * FROM files WHERE filetype='image' AND  fileextname<>'png'");
        $ids = [];
        while($row = $st->fetch()){
            $pngfile = $dir.'/'.ltrim($row['filename'],'/');
            $pngfile = str_replace('.jpg','.png',$pngfile);
            if(file_exists($pngfile)){
                $ids[] = $row['fileid'];
            }
        }
	    $this->db->useBuff(true);
	    foreach($ids as $id){
            $this->db->update('files',['fileextname'=>'png'],['fileid'=>$id]);
	    }
        dd('OK');
	}
	
    //http://127.0.0.1/qgmvc/gsp/admin/sys/changeOutNum?innum=G-01-CH-0003&outnum=S010047
    //http://192.168.0.63/gsp/admin/sys/changeOutNum?innum=&outnum=
    public function changeOutNum($innum,$outnum)
    {
		$innum = trim($innum);
		$outnum = trim($outnum);
		$outnumFormat = formatNum($outnum);
		if(empty($innum) || empty($outnumFormat)){
		    dd('失败: 参数有误');
		}
		$pid = $this->db->get('p_code','pc_p_id',['pc_innum'=>$innum]);
		if(!$pid){
		    dd('失败: INNUM 不存在');
		}
		if(
		    $this->db->has('p_code',['pc_outnum'=>$outnumFormat])
		    ||
		    $this->db->has('p_code_number',['pcn_pf_id'=>2,'pcn_format'=>$outnumFormat])
		 ){
		    dd('失败: OUTNUM 已存在');
		}
		$this->db->begin();
		$this->db->update('p_code',['pc_outnum'=>$outnum],['pc_p_id'=>$pid]);
		$this->db->update('p_code_number',['pcn_number'=>$outnum,'pcn_format'=>$outnumFormat],['pcn_pc_id'=>$pid,'pcn_pf_id'=>2]);
		$this->db->update('pro',['p_outnum'=>$outnum,'p_outnum_format'=>$outnumFormat],['p_id'=>$pid]);
		$this->db->update('pro_numidx',['pn_number'=>$outnum,'pn_formart'=>$outnumFormat],['pn_p_id'=>$pid,'pn_pf_id'=>2]);
		$this->db->update('pro_numidx_temp',['pnt_outnum'=>$outnum],['pnt_p_id'=>$pid]);
		$this->db->update('pro_pic_task',['ppt_outnum'=>$outnum],['ppt_innum'=>$innum]);
		$this->db->update('pro_pic',['ppic_outnum'=>$outnum],['ppic_p_id'=>$pid]);
		$this->db->update('sample',['s_outnum'=>$outnum],['s_innum'=>$innum]);
		$this->db->end();
		
	    dd('外编码 '.$outnum.' 修改成功');
    }

	
    //恢复文件
    public function recoveryFiles()
    {
        function getDbFiles($db,$fp,$objFile,$objImage,$file_category,$file_item,$fileremark,$number,$extname,$src){
           if($row = $db->get('files','*',['file_category'=>$file_category,'file_item'=>$file_item,'fileremark'=>$fileremark]))
           {
               $fileid = $row['fileid'];
               $dist = \mvc::$cfg['dir']['files'].'/'.$row['filename'];
               if(true || !file_exists($dist)){
                   mkdirs(dirname($dist));
                   copy($src,$dist);
                   $objFile->buildAllImage($file_category,$file_item,$dist);
                   if($file_category=='proimage' && $file_item=='beautify'){
                        if($number==$fileremark){
                            if($pid = $db->get('pro','p_id',['p_innum'=>$number])){
                                $objImage->setMain($pid,$fileid);
                            }
                        }
                   }
               }
           }else{
               fputcsv($fp, [$file_category,$file_item,$fileremark,'不存在']);
           }
        }
        
        $dir = \mvc::$cfg['dir']['files'].'/importServer/recovery';
		$arr = scandir($dir);
	    $objFile = makeOne(\model\files::class);
	    $objImage = makeOne(\model\pro\image::class);
        $logpath = 'import/'.date('Ym');
        $logfilename = 'log'.getOpuser().'RecoveryFiles.csv';
        $logfile = \mvc::$cfg['dir']['files'].'/'.$logpath.'/'.$logfilename;
        mkdirs(\mvc::$cfg['dir']['files'].'/'.$logpath);
        $fp = fopen($logfile, 'w'); //记录日志
	    
		foreach($arr as $path)
		{
		    list($file_category,$file_item) = explode('_',$path);
		    if($path=='.' || $path=='..' || empty($file_item))
		        continue;
		   
		   $subarr = scandir($dir.'/'.$path);
		   foreach($subarr as $filename){
    		    if($filename=='.' || $filename=='..')
    		        continue;
    		    $info = explode('.',strtolower(basename($filename)));
                $extname = end($info);
                $fileremark = strtolower($info[0]);
                $number = preg_split('/[_]/',$fileremark)[0];
                getDbFiles($this->db,$fp,$objFile,$objImage,$file_category,$file_item,$fileremark,$number,$extname,$dir.'/'.$path.'/'.$filename);
		   }
		}
		fclose($fp);
        //消息记录与在线提醒
        $url = \mvc::$cfg['path']['files'].'/'.$logpath.'/'.$logfilename;
        $msg = [
        	'amsg_title'=> '图片恢复导入完成',
        	'amsg_body'=> '图片恢复导入完成',
        	'amsg_url'=> $url,
        	'amsg_urltitle'=> basename($url),
        ];
        makeOne(\model\message::class)->send([getOpuser()],$msg);
        socketSendMsg([getOpuser()],$msg);
    }

	//http://192.168.0.63/gsp/admin/sys/delProduct?outnum=xxx
	public function delProduct($outnum)
	{
		$outnum = trim($outnum);
		$outnumFormat = formatNum($outnum);
		$proArr = $this->db->get('pro', ['p_id', 'p_pic', 'p_state_main'],['p_outnum_format'=>$outnumFormat]);
		if(empty($proArr)) 
			$proArr = $this->db->get('p_code', ['pc_id(p_id)', 'pc_state_main(p_state_main)'],['pc_outnum'=>$outnumFormat]);
		if(empty($proArr))  dd('失败: OUTNUM 不存在');
		if($proArr['p_state_main'] == 'Y6')
		{
			$pid = $proArr['p_id'];
			
			$fileids = [];
			$rows = $this->db->select('pro_pic', 'ppic_fileid', ['ppic_p_id'=>$pid]);
			if(!empty($rows))
				$fileids = array_merge($fileids, $rows);
			$this->db->begin();
			
			//优先执行
			$this->db->delete('pro_model_area_link_temp', ['RAW'=>raw(sprintf(" pmat_pmlt_id in (select pmlt_p_id from pro_model_link_temp where pmlt_p_id=%d)", $pid))]);
			$this->db->delete('tags_link', ['RAW'=>raw(sprintf(" tl_type='_promodel' and tl_value_id in (select pmlt_id from pro_model_link_temp where pmlt_p_id=%d)", $pid))]);

			$this->db->delete('pro_model_area_link', ['RAW'=>raw(sprintf(" pma_pml_id in (select pml_id from pro_model_link where pml_p_id=%d)", $pid))]);
			$this->db->delete('tags_link', ['RAW'=>raw(sprintf(" tl_type='promodel' and tl_value_id in (select pml_id from pro_model_link where pml_p_id=%d)", $pid))]);
		
			$this->db->delete('tags_link', ['RAW'=>raw(sprintf(" tl_type='number' and tl_value_id in (select pn_id from pro_numidx where pn_p_id=%d)", $pid))]);
			$this->db->delete('tags_link', ['RAW'=>raw(sprintf(" tl_type='_number' and tl_value_id in (select pnt_id from pro_numidx_temp where pnt_p_id=%d)", $pid))]);
			$this->db->delete('tags_link', ['tl_type'=>'pro', 'tl_value_id'=>$pid]);
			
			$delTableArr = [
				['pro','p_id'],
				['p_code','pc_id'],
				['p_code_number','pcn_pc_id'],
				['gsp_pro_param_val','ppv_p_id'],
				['pro_attaqty','pa_p_id'],
				['pro_exchange','pe_p_id1','pe_p_id2'],
				['pro_fatherson','pf_father_pid','pf_son_pid'],
				['pro_merge','pch_p_id_from','pch_p_id_to'],
				['pro_model_change','pml_p_id'],
				['pro_model_cn_link','pml_p_id'],
				['pro_model_link','pml_p_id'],
				['pro_model_link_temp','pmlt_p_id'],
				['pro_numidx','pn_p_id'],
				['pro_numidx_change','pn_p_id'],
				['pro_numidx_temp','pnt_p_id'],
				['pro_pair','pp_p_id1', 'pp_p_id2'],
				['pro_pic','ppic_p_id'],
				['pro_pic_task','ppt_p_id'],
				['pro_state_date','pst_p_id'],
			];
			foreach($delTableArr as $tv)
			{
				$where = [$tv[1]=>$pid];
				if(count($tv) > 2)
				{
					$orArr = [];
					for($i = 1; $i < count($tv); $i++)
					{
						$orArr[$tv[$i]] = $pid;
					}
					$where = ['OR'=>$orArr];
				}
				$this->db->delete($tv[0], $where);
			}

			$this->db->update('sample', ['s_p_id'=>0, 's_outnum'=>''], ['s_p_id'=>$pid]);
			$this->db->end();
			
			if(!empty($fileids))
			{
				$files = new \model\files();
				$files->delete($fileids, true);
			}
			if(!empty($proArr['p_pic']))
			{
				$mainf = ['catalog_gsp','catalog_g','tecdoc'];
				foreach($mainf as $mf)
				{
					foreach(['small.jpg', 'mid.jpg', 'big.jpg'] as $sf)
					{	
						//pro\ xxx \ pid % 100  \ pidsmall.jpg 
						$delfile = \mvc::$cfg['dir']['files'].'/pro/'.$mf.'/'.($pid%100).'/'.$pid.$sf;
						@unlink();
					}
				}
			}
			dd('外编码 '.$outnum.' 删除成功');
		}
		else
		{
			dd('失败: 只能删除Y6状态的产品');
		}
	}
	
    //批量删除样品
	public function deleteSample()
    {
		if(!\p::isAdmin()){
		    dd('非法操作');
		    exit();
		}
		$sample = make(\model\sample\sample::class);
		$filename = \mvc::$cfg['dir']['files'].'/temp/sampleDelete.csv';
		$arr = file($filename);
        $this->db->begin();
		foreach($arr as $plmseq){
		    $plmseq = trim($plmseq);
		    $row = $sample->getRowByFieldValue('s_plmseq',$plmseq);
		    $ids = $row['s_id'];
		    if($ids){
                $this->db->delete('history',['h_mod'=>'sample','h_mod_id'=>$ids]);
                $this->db->delete('sample_supplier',['ss_s_id'=>$ids]);
                $this->db->delete('sample_process',['sp_s_id'=>$ids]);
                $this->db->delete('sample_numidx',['sn_s_id'=>$ids]);
                $this->db->delete('sample_devechange',['sb_id'=>$ids]);
                $this->db->delete('sample_develop_change',['sdc_s_id'=>$ids]);
                $this->db->delete('sample_model_link',['sml_s_id'=>$ids]);
                $this->db->delete('sample_model_txt',['smt_s_id'=>$ids]);
                $this->db->delete('sample_tech',['st_s_id'=>$ids]);
                $this->db->delete('sample',['s_id'=>$ids]);
		    }
		}
        $this->db->end();
        exit('操作完成');
    }
    //批量清除样品车型样品
	public function clearModelSample()
    {
		if(!\p::isAdmin()){
		    dd('非法操作');
		    exit();
		}
		$sample = make(\model\sample\sample::class);
		$filename = \mvc::$cfg['dir']['files'].'/temp/sampleClearModel.csv';
		$arr = file($filename);
        $this->db->begin();
		foreach($arr as $plmseq){
		    $plmseq = trim($plmseq);
		    $row = $sample->getRowByFieldValue('s_plmseq',$plmseq);
		    $ids = $row['s_id'];
		    if($ids){
                $this->db->delete('sample_model_link',['sml_s_id'=>$ids]);
                $this->db->delete('sample_model_txt',['smt_s_id'=>$ids]);
		    }
		}
        $this->db->end();
    }
    
	public function get_event_month_sample_sql()
    {
		$sql = "SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE table_name = 'month_sample' AND NOT COLUMN_COMMENT like 'ADD%'";
		$rows = $this->db->query($sql)->fetchAll();
		$fields = [];
		$fields[] = "DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 1 MONTH),'%Y') `year`";
		$fields[] = "DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 1 MONTH),'%m') `month`";
		$fields[] = "DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 1 MONTH),'%Y%m') `yearmonth`";
		$fields[] = "cate.parent_id `bigcate`";
		$fields[] = "s_cate `cate`";
		$fields[] = "s_state_main `state`";
		$fields[] = "IFNULL(DATEDIFF(s_stop_time,s_send_plm_time),-1)+1 `cycle`";
		foreach($rows as $row){
		    $fields[]= '`'.$row['COLUMN_NAME'].'`';
		}
		$select = "SELECT ". implode(',',$fields) . " FROM gspcatalog.sample";
		$select.= " LEFT OUTER JOIN gspcatalog.pro_cate cate ON s_cate = cate.id";
		$insert = "INSERT IGNORE INTO `month_sample` ".$select.";\r\n";
		echo $insert;
	}
	
    /**更换图片水印
    * @param $type 类型,只能是 g,gsp
    */
	public function watermark($type)
    {
        if(!in_array($type,['g','gsp'])){
            exit('type 只能是 g 或者 gsp');
        }
        $waterFile = './static/images/watermark/'.$type.'.png';
        if(!file_exists($waterFile)){
            exit('水印文件不存在:'.$waterFile);
        }
        echo "开始重新生成水印...\r\n";
        $image = make(\lib\image::class,100);
        $logfile = \mvc::$cfg['dir']['log'].'/watermark_change.csv';
        $fp = fopen($logfile, 'w'); //记录日志
        $hasError = false;
        $rows  = $this->db->select('pro',['[>]files'=>['p_pic'=>'fileid']],['p_id','p_outnum','filename'],['p_pic[>]'=>0]);
        $count = count($rows);
        $i=0;
		$cfg = \mvc::$cfg['upload']['category']['proimage']['items']['catalog_'.$type];
        foreach($rows as $row){
            $i++;
            if($row['filename']){
                $pid = $row['p_id'];
                $initFilename = \mvc::$cfg['dir']['files'].'/'.ltrim($row['filename'],'/');
                if(file_exists($initFilename)){
                    foreach(['big','mid','small'] as $key){
                        $filename = \mvc::$cfg['dir']['files'].'/pro/catalog_'.$type . '/' . ($pid % 100) . '/' . $pid. $key .'.jpg';
						//$res = $image->Watermark($initFilename,$filename,$waterFile);
						//原图尺寸过大 2023/2/10
						$size = $cfg['size'][$key];
						$res = $image->ResizeWatermark($initFilename,$filename,$size[0],$size[1],$waterFile);
                        if($res !== true){
                            $hasError = true;
                            fputcsv($fp, [$filename,'导入失败,请检测是否是一个有效的图片']);
                        }else{
							@chmod($filename, 0777);
                        }
                    }
                }
                echo $row['p_outnum']. "  ". $i .'/'. $count."\r\n";
            }
        }
        fclose($fp);
        echo '日志文件位置:'.$logfile."\r\n";
        echo "生成水印完成。\r\n";
	}


	 //g,gsp小图加水印
    public function resetSmallPicWatermark()
	{
        echo "开始重新生成水印...\r\n";
		$image = make(\lib\image::class,100);
        $logfile = \mvc::$cfg['dir']['log'].'/resetSmallPicWatermark.csv';
        $fp = fopen($logfile, 'w'); //记录日志
        $hasError = false;
        $rows  = $this->db->select('pro',['[>]files'=>['p_pic'=>'fileid']],['p_id','p_outnum','filename'],['p_pic[>]'=>0]);
        $count = count($rows);
        $i=0;
        foreach($rows as $row)
		{
			$i++;
            if(empty($row['filename'])) continue;
			$pid = $row['p_id'];
			$initFilename = \mvc::$cfg['dir']['files'].'/'.ltrim($row['filename'],'/');
			if(file_exists($initFilename)){
				foreach(['catalog_g','catalog_gsp'] as $item){	
					$watermark = \mvc::$cfg['dir']['static'].'/images/watermark/pro/'.$item.'.png';
					$cfg = \mvc::$cfg['upload']['category']['proimage']['items'][$item];
					$key = 'small';
					$size = $cfg['size'][$key];
					$filename = \mvc::$cfg['dir']['files'].'/pro/'.$item . '/' . ($pid % 100) . '/' . $pid. $key .'.jpg';
					$res = $image->ResizeWatermark($initFilename,$filename,$size[0],$size[1],$watermark);
					if($res !== true){
						$hasError = true;
						fputcsv($fp, [$filename,'导入失败,请检测是否是一个有效的图片']);
					}
				}
			}
			else{
				fputcsv($fp, [$row['p_outnum'], $initFilename,'不存在']);
			}
			echo $row['p_outnum']. "  ". $i .'/'. $count."\r\n";
           
        }
        fclose($fp);
        echo '日志文件位置:'.$logfile."\r\n";
        echo "生成水印完成。\r\n";
	}
	
}