<?php
namespace model\pdflib;
class pdfset extends \model
{
	public function __construct()
    {
		parent::__construct();
		$this->captions = [
		    'pml_pos1'=>[
		        'F' =>   'Front',
		        'R' =>   'Rear',
		        'F/R' => 'Front/Rear',
		    ],
		];
	}

    /**检测上传
     * @param 
     * @return
     */
	public function uploadCheck($filecount,$reqfilename,$reqfilesize,$uploadID,$extname,$category,$item,$params)
	{
		$id = $params['id'];
		if(empty($id)) {
			throw new \Exception ( '上传图片时，ID丢失' );
		}
		$cfg = \mvc::$cfg['upload']['category'][$category]['items'][$item];
		
		$count = 0;
		$photos = $this->db->get('pdf_tpl_link','pdftl_json',['pdftl_id'=>$id]);
		if($photos){
			$count = count(json_decode($photos));
		}
		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)
	{
		$id = $params['id'];
		if(empty($id)) {
			throw new \Exception ( '上传产品图片时，样品ID丢失' );
		}
		$cfg = \mvc::$cfg['upload']['category'][$category]['items'][$item];
		if($cfg['tojpeg']) $extname = 'jpg';
		$photos = $this->db->get('pdf_tpl_link','pdftl_json',['pdftl_id'=>$id]);
		if(empty($photos)) $photos = '[]'; 
		$arr = json_decode($photos);
		array_push($arr,[
			'fileid'=>$fileid,
			'filename'=>$dir.'/'.$filebase.'.'.$extname
		]);
		$this->db->update('pdf_tpl_link',['pdftl_json'=>json_encode($arr)],['pdftl_id'=>$id]);
	}

	/**
	 * 保存模板相关
	 * @return bool
	 */
	public function saveTplLink($id,$data){
		return $this->db->update('pdf_tpl_link',$data,['pdftl_id'=>$id]);
	}


	/**
	 * 更改车型区域
	 * @return bool
	 */
	public function changeArea($cateId,$ma_id){
		return $this->db->update('pdf_cate',['pdfc_area'=>$ma_id],['pdfc_id'=>$cateId]);
	}

	/**
	 * 更改版本
	 * @return bool
	 */
	public function changeVer($cateId,$ver){
		return $this->db->update('pdf_cate',['pdfc_ver'=>$ver],['pdfc_id'=>$cateId]);
	}


	/**
	 * 所有PDF大版
	 * @return array
	 */
	public function getCateAll(){
		return $this->db->select('pdf_cate','*',[]);
	}

	/**
	 * 取指定PDF大版
	 * @return array
	 */
	public function getCateByKey($id){
		return $this->db->get('pdf_cate','*',['pdfc_id'=>$id]);
	}

	/**
	 * 取大版下的所有子版
	 * @return array
	 */
	public function getTpls($cateid){
		return $this->db->select('pdf_tpl_link','*',['pdftl_pdfc_id'=>$cateid,'ORDER'=>'pdftl_sort']);
	}

	/**
	 * 取指定子版信息
	 * @return array
	 */
	public function getTplRow($tplid){
		return $this->db->get('pdf_tpl_link',['[>]pdf_tpl'=>['pdftl_pdft_code'=>'pdft_code']],'*',['pdftl_id'=>$tplid]);
	}
	
	/**
	 * 取指定子版信息列表
	 * @return array
	 */
	public function getTplRows($tplid){
		return $this->db->select('pdf_tpl_link',['[>]pdf_tpl'=>['pdftl_pdft_code'=>'pdft_code']],'*',['pdftl_id'=>$tplid]);
	}

	/**
	 * 获取列的配置
	 * @return array
	 */
	public function getColsSetCfg(){
		$rows = $this->db->select('pdf_tpl','*',['pdft_cols[!]'=>'','ORDER'=>['pdft_name']]);
		$data = [];
		foreach($rows as $row){
			$cols = json_decode($row['pdft_cols'],true);
			$cols = explode('<@>',implode('<@>',$cols));
			$data[$row['pdft_code']]=[
				'name'=>$row['pdft_name'],
				'cols'=>$cols
			];
		}
		return $data;
	}

	/**
	  * @method 为大版选择 品名
	  * @param
	  */
    function saveSetCate($id,$proCateIds){
		$cols = $this->getCateCols($id);
		$proCate = make(\model\pro\cate::class);
		$err = '';
		// foreach($proCateIds as $pcid){
		// 	foreach($cols as $col){
		// 		$has = $this->db->has('gsp_part_param',['ptpa_pc_id'=>$pcid,'pdfcol[~]'=>$col]);
		// 		if(!$has){
		// 			$t = explode('=>',$col);
		// 			$code = $t[0];
		// 			$param = $t[1];
		// 			$codename = $this->db->get('pdf_tpl','pdft_name',['pdft_code'=>$code]);
		// 			$catename = $this->db->get('pro_cate','en_name',['id'=>$pcid]);
		// 			//$err = sprintf("品名:[ %s ]没有绑定[ %s ]中的参数列[ %s ]",$catename,$codename,$param);
		// 			//break;
		// 		}
		// 	}
		// 	if($err!='') break;
		// }
		if($err==''){
			$this->db->update('pdf_cate',['pdfc_cates'=>implode(',',$proCateIds)],['pdfc_id'=>$id]);
			return true;
		}else{
			return $err;
		}
	}


	/**
	  * @method 取大版下所有的配置列信息
	  * @param
	  */
    function getCateCols($cateId){
		$join['[>]pdf_tpl_link'] = ['pdft_code'=>'pdftl_pdft_code'];
		$where = ['pdftl_pdfc_id'=>$cateId,'pdft_cols[!]'=>''];
		$rows = $this->db->select('pdf_tpl',$join,['pdft_code','pdft_cols'],$where);
		$data = [];
		foreach($rows as $row){
			$code = $row['pdft_code'];
			$arr = json_decode($row['pdft_cols']);
			foreach($arr as $v){
				$data[] = $code.'=>'.$v;
			}
		}
		return $data;
	}

    function formatTplFields($tpl)
	{
		return [
			//类别信息
			$tpl['pdfc_style'],
			$tpl['pdfc_title'],
			$tpl['pdfc_remark'], //
			$tpl['pdfc_cates'], //所选品名
			$tpl['pdfc_area'], //区域
			$tpl['pdfc_ver'], //版本
			//母板
			$tpl['pdft_type'],
			$tpl['pdft_name'], //typeName
			$tpl['pdft_cols'], //cols
			//子板
			$tpl['pdftl_id'],
			$tpl['pdftl_pdft_code'],
			$tpl['pdftl_pdft_code'].'.'.$tpl['pdftl_id'],
			$tpl['pdftl_name'],
			$tpl['pdftl_title'],
			$tpl['pdftl_remark'],
			$tpl['pdftl_cates'],
			($tpl['pdftl_json']) ? json_decode($tpl['pdftl_json'],true) : [],
			($tpl['pdftl_has_index']==1),
		];
	}

	/**
	  * @method 0小数显示处理  
	  */
    function formartDecimal0($value){
        $value = trim($value);
        if(is_numeric($value)){
            $value = round($value,0);
			$value = floatval($value);
        }
		if(empty($value)) $value = '';
        return $value;
    }
    
	/**
	  * @method 2小数显示处理1
	  */
    function formartDecimal1($value){
        $value = trim($value);
        if(is_numeric($value)){
            $value = round($value,2);
			$value = floatval($value);
        }
		if(empty($value)) $value = '';
        return $value;
    }
	/**
	  * @method 3小数显示处理
	  */
    function formartDecimal2($value){
        if(is_numeric($value)){
            $value = round($value,3);
			$value = floatval($value);
        }
		if(empty($value)) $value = '';
        return $value;
    }
    
	/**
	  * @method FITTING POSITION
	  */
    function getFittingPosition($frAxle,$fr,$lr,$ucl,$ico){
        $frAxleArr = [
            'F'=>'Front Axle',
            'R'=>'Rear Axle',
            'F/R'=>'Front Axle;Rear Axle',
        ];
        $frArr = [
            'F'=>'Front',
            'R'=>'Rear',
            'F/R'=>'Front;Rear',
        ];
        $lrArr = [
            'L'=>'Left',
            'R'=>'Right',
            'L/R'=>'Left & Right',
        ];
        $uclArr = [
            'U'=>'Upper',
            'C'=>'Centre',
            'L'=>'Lower',
        ];
        $icoArr = [
            'O'=>'Outer',
            'C'=>'Centre',
            'I'=>'Inner',
        ];
        $values = [];
        if($frAxle && $frAxleArr[$frAxle]) $values[] = $frAxleArr[$frAxle];
        //if($fr && $frArr[$fr]) $values[] = $frArr[$fr];
        if($lr && $lrArr[$lr]) $values[] = $lrArr[$lr];
        if($ucl && $uclArr[$ucl]) $values[] = $uclArr[$ucl];
        if($ico && $icoArr[$ico]) $values[] = $icoArr[$ico];
        return $values ? implode(' ',$values) : '-';
    }
    
	/**
	  * @method FITTING POSITION
	  */
    function getFittingPositionWithFr($frAxle,$fr,$lr,$ucl,$ico){
        $frAxleArr = [
            'F'=>'Front Axle',
            'R'=>'Rear Axle',
            'F/R'=>'Front Axle;Rear Axle',
        ];
        $frArr = [
            'F'=>'Front',
            'R'=>'Rear',
            'F/R'=>'Front;Rear',
        ];
        $lrArr = [
            'L'=>'Left',
            'R'=>'Right',
            'L/R'=>'Left & Right',
        ];
        $uclArr = [
            'U'=>'Upper',
            'C'=>'Centre',
            'L'=>'Lower',
        ];
        $icoArr = [
            'O'=>'Outer',
            'C'=>'Centre',
            'I'=>'Inner',
        ];
        $values = [];
        if($frAxle && $frAxleArr[$frAxle]) $values[] = $frAxleArr[$frAxle];
        if($fr && $frArr[$fr]) $values[] = $frArr[$fr];
        if($lr && $lrArr[$lr]){
            if($frAxle && $frAxleArr[$frAxle] && $frAxle=='F/R'){
                 $values[0] = 'Front Axle '.$lrArr[$lr].';Rear Axle '.$lrArr[$lr];
            }else{
                $values[] = $lrArr[$lr];
            }
        }
        if($ucl && $uclArr[$ucl]) $values[] = $uclArr[$ucl];
        if($ico && $icoArr[$ico]) $values[] = $icoArr[$ico];
        return $values ? implode(' ',$values) : '-';
    }
    
	/**
	  * @method FITTING POSITION
	  */
    function getFittingPosition2($frAxle,$fr,$lr,$ucl,$ico){
        $frAxleArr = [
            'F'=>'Front Axle',
            'R'=>'Rear Axle',
            'F/R'=>'Front Axle;Rear Axle',
        ];
        $frArr = [
            'F'=>'Front',
            'R'=>'Rear',
            'F/R'=>'Front;Rear',
        ];
        $lrArr = [
            'L'=>'Left',
            'R'=>'Right',
            'L/R'=>'Left & Right',
        ];
        $uclArr = [
            'U'=>'Upper',
            'C'=>'Centre',
            'L'=>'Lower',
        ];
        $icoArr = [
            'O'=>'Outer',
            'C'=>'Centre',
            'I'=>'Inner',
        ];
        $values = [];
        if($frAxle && $frAxleArr[$frAxle]) $values[] = $frAxleArr[$frAxle];
        if($fr && $frArr[$fr]) $values[] = $frArr[$fr];
        if($lr && $lrArr[$lr]) $values[] = $lrArr[$lr];
        if($ucl && $uclArr[$ucl]) $values[] = $uclArr[$ucl];
        if($ico && $icoArr[$ico]) $values[] = $icoArr[$ico];
        return $values ? implode(' ',$values) : '-';
    }

	/**
	  * @method 大版PDFLIB配置
	  */
    function getCateInfo($cate,$selectModels='',$gspband='gsp')
	{
		$g_brand_id = 4;
		$cateId = $cate['pdfc_id'];
		if(empty($cate['pdfc_cates'])){
			throw new \Exception ( sprintf('未选择品名') );
		}
		//取PDF导出版本号
		$pdfVerRows = $this->db->select('object',['o_id','cn_name(name)','code'],['o_parent_id'=>39,'ORDER'=>['o_sort'=>'DESC','o_id'=>'DESC'],'LIMIT'=>2]);
		if(empty($pdfVerRows)){
			msgJson( sprintf('未定义目录导出版本号') );
		}
		$newVer = '';
		$newVerName = '';
		$newVerType = '';
		$lastVer = '';
		foreach($pdfVerRows as $pdfVerRow){
			if($lastVer=='' && $newVer!='') {
				$lastVer = $pdfVerRow['o_id'];
			}
			if($newVer=='') $newVer = $pdfVerRow['o_id'];
			if($newVerType=='') $newVerType = $pdfVerRow['code'];
			if($newVerName=='') $newVerName = $pdfVerRow['name'];
		}
		if($newVer==''){
			msgJson( sprintf('未定义目录导出版本号') );
		}

		//取子模板
		$pd = new \model\pdflib\pdfData($cate['pdfc_cates']);

 		$tpls = $this->db->select(
			'pdf_tpl_link',
			[
				'[>]pdf_tpl'=>['pdftl_pdft_code'=>'pdft_code'],
				'[>]pdf_cate'=>['pdftl_pdfc_id'=>'pdfc_id']
			],
			'*',
			['pdftl_pdfc_id'=>$cateId,'pdftl_has_index'=>1,'ORDER'=>'pdftl_sort']
		);
		//数据
		$values = [];
		$numbers = [];
		$newNumbers = [];
		$dataVer = "'01','02','03','04','99','05','06','07','00'";
		$number_ckresult2 = "10121";
		$isleaflet = false;
		foreach($tpls as $tpl){
			list($cateStyle,$cateTitle,$cateRemark,$cateList,$cateArea,$cateVer,
				  $type,$typeName,$cols,
				  $id,$code,$key,$name,$title,$remark,$tplCates,$jsonArr,$hasIndex
			) = $this->formatTplFields($tpl);
			if(empty($cateVer)) $cateVer= 0;
			if(empty($cateArea)) $cateArea= 0;
		    if($code=='leaflet'){
		        $isleaflet = true;
		    }
			$value = null;
			$dataFilename = __DIR__ . DIRECTORY_SEPARATOR . 'code'. DIRECTORY_SEPARATOR . $code.'.php';
			if(file_exists($dataFilename)){
				// if($type=='newnumber'){
				// 	$newNumbers = $pd->getPdfVerNewNumbers($cateId, $cateVer,$cateArea,$newVerType,$newVer,$lastVer,$numbers, $gspband);
				// 	//dd($newNumbers);
				// 	//dd($dataFilename, $pdfVerRows, $cateVer, $cateArea, $newVerType, $newVer, $lastVer, $newNumbers);
				// }
				$value = require($dataFilename);
			}else{
				throw new \Exception ( sprintf('未定义 %s 模板',$code) );
			}
			if($value && isset($value['style'])){
				$values[$key] = $value;
			}
		};
		if($isleaflet){
		    $values = changeValue($values);
		}
		if($cateId!=8){ //忽略悬挂宣传页
		    $pd->savePdfVerData($cateId, $cateVer,$cateArea,$newVerType,$newVer,$numbers);
		}
		//配置
		$options = [];
		$modelIndexKeys = [];
		$modelKeys = [];
		foreach($values as $key=>$value){
			$options['setup'][] = $key;
			if($value['compute']){
				$type = array_key_exists('type',$value) ? $value['type'] : '';
				if($type == 'model-index'){
					$modelIndexKeys[] = $key;
				}else if($type == 'model'){
					$modelKeys[] = $key;
				}else{
					$options['compute'][] = $key;
				}
			}
		}
		foreach($modelKeys as $v){
			$options['compute'][] = $v;
		}
		if(!empty($modelKeys)){
			foreach($modelIndexKeys as $v){
				$options['compute'][] = $v;
			}
		}
		//dd($options,$values);
		return ['options'=>$options,'values'=>$values];
	}
}