<?php
namespace model\pro;
use \model;
use model\fanyi;
use \model\grid\lrtree;
use model\alioss;
use model\tags;
/**
 * Class procate
 * @package model
 */
class cate extends model
{
    public $table = 'pro_cate';
    public $key = 'id';
    public $name = LG_NAME;
    public $order = LG_NAME;
	public $lrtree = null;
	public function __construct()
    {
		parent::__construct();
        $this->options = [
			'table'=>'pro_cate',
			'id'=>'id',
			'parent_id'=>'parent_id',
			'left'=>'left',
			'right'=>'right',
			'level'=>'level',
			'ismove'=>'ismove',
			'cn_name'=>'cn_name',
			'en_name'=>'en_name',
			'py_name'=>'py_name',
			'cat_zhuyi'=>'cat_zhuyi',
			'cat_pzbz'=>'cat_pzbz',
			'cat_zpsl'=>'cat_zpsl',
			'attaqty'=>'attaqty',
			'create_time'=>'create_time',
			'update_time'=>'update_time'
		];
        $this->attaqtys = [
			
		];
		$this->attaqtys2 = [
			
		];
		$this->lrtree = new lrtree($this->options);
	}



	public function attaqtysItems()
	{
		$attaqtysitems = [':'];
		foreach($this->attaqtys as $k=>$v)
		{
			$attaqtysitems[] = $k.':'.$v;
		}
		return implode(',', $attaqtysitems);
	}

	public function attaqtys2Items()
	{
		$attaqtys2items = [':'];
		foreach($this->attaqtys2 as $k=>$v)
		{
			$attaqtys2items[] = $k.':'.$v;
		}
		return implode(',', $attaqtys2items);	
	}

    /**
     * 保存参数示意图
     * @param $data
     * @param $config
     */
    public function save($data,$config)
    {
        $fileid = $data['file_id'];
        $data['param'] = json_decode($data['param'],true);
        $id = $data['param']['id'];
        $this->db->update($this->table,['photo_param' => $fileid],['id' => $id]);
    }

	function addCate($parent_id,$data)
	{
		$this->db->Begin();
		$ruleArr = $data['rule'];
		unset($data['rule']);
	
		$id = $this->lrtree->addNode($parent_id,$data);
		$rule =	new rule();
		$rule->saveCateRuleById($id,$ruleArr);
		$this->db->End();
		return $id;
	}

	function editCate($id,$parent_id,$data)
	{
		$this->db->Begin();
		$ruleArr = $data['rule'];
		unset($data['rule']);
		$result = $this->lrtree->editNodeByChangePid($id,$parent_id,$data);
		$rule =	new rule();
		$rule->saveCateRuleById($id,$ruleArr);
		$this->db->End();
		return $result;
	}

	function delCate($id)
	{
		$pid = $this->db->get('pro_cate', 'id', ['parent_id'=>$id]);
		if(!empty($pid)) exitJson('此分类有子类，请先删除子类');
		
		$pid = $this->db->get('pro', 'p_id', ['p_cate'=>$id]);
		if(!empty($pid)) exitJson('此小类有产品，请先删除产品');
		
		$this->db->Begin();

		$this->lrtree->deleteNode($id);
		//参数绑定
		$this->db->delete('part_param', ['ptpa_cate_id'=>$id]);
		//参数值
		$this->db->delete('pro_param_val', ['ppv_pc_id'=>$id]);
		$this->db->End();
		return [];
	}

	/**
	  * @method 获取中国车型的位置信息
	  * @author soul
	  */
	public function getCnModelFiled($cat_id = 0, $p_id = 0)
	{
		if(!empty($p_id))
		{
			$row = $this->db->get('pro(p)',['[><]pro_cate(cat)'=>['p.p_cate'=>'id']], ['cat.id', 'cat.cat_cnpos'], ['p.p_id'=>$p_id]);
		}
		else
		{
			$row = $this->db->get('pro_cate', ['id', 'cat_cnpos'], ['id'=>$cat_id]);
		}
		$fileds = [];
		if(!empty($row['cat_cnpos']))
		{
			$row['cat_cnpos'] = json_decode($row['cat_cnpos'], true);
			if(is_array($row['cat_cnpos'])) $fileds = array_column($row['cat_cnpos'], 'name', 'filed');
		}
		return $fileds;
	}


    /**
     *  删除参数示意图
     * @param $id
     * @param $photoParam
     * @return false|\PDOStatement
     */
    public function deleteImage($id,$photoParam)
    {
        return $this->db->update($this->table,['photo_param' => ''],['id' => $id]);
    }

    public function list($where='',$page=0,$pagesize=0,$sidx='',$sord='asc',$orderby='')
    {
        if($where){
            $where = $this->filter2medoo($where);
        }
        $arr = $this->lrtree->list($where, $page, $pagesize, $sidx, $sord);
		foreach($arr['rows'] as &$row)
		{
			$row['captions']['attaqty'] = isset($this->attaqtys[$row['attaqty']])? $this->attaqtys[$row['attaqty']]: '';
			$row['captions']['cat_model_fileds'] = $this->getSmallFiledsName($row);
		}
		return $arr;
    }

	function list2($rules, $where='',$page=0,$pagesize=0,$sidx='',$sord='asc',$orderby=''){
	    $page=1;
	    $pagesize = 1000;
	    $orderby='level,parent_id,en_name';
	    
        $table = $this->table.'(c)';
        $this->fields = ['c.*', 'prl.prl_code_a'];
        $this->join = ['[>]pro_rule_link(prl)' => ['c.id'=>'prl_val_id', 'AND'=>"prl.prl_type='cate' AND prl.prl_pb_id=1"]];
		$this->joinWhere = [];
		$this->group = [];
        $where = $this->filter2medoo($where,function(&$field,&$op,&$data){
            if($field=='en_name' || $field=='cn_name'|| $field=='py_name'){
                $op = 'eq';
                $field = 'id';
                $data = $this->likeAndChilds($data,true);
				if(empty($data)) $data = 0;
            }
			if($field=='cat_model_fileds' || $field=='cat_cnpos')
			{
				if($data == 1)
				{
					$op = 'not';
					$data = '{}';
				}
				else if($data == 0)
				{
					$data = '{}';
				}
			}
			if($field == 'oe_counts'){
				$temp = [
					'eq'=>'=',
					'le'=>'<=',
					'lt'=>'<',
					'gt'=>'>',
					'ge'=>'>='
				];
				$opr = $temp[$op];
				$op = 'RAW_'.$field;
				$data = raw(sprintf("id in (SELECT `cate1`.`id` FROM`pro_cate` AS `cate1` 
				LEFT JOIN `pro_cate` AS `cate2` ON `cate1`.`id` = `cate2`.`parent_id`
				LEFT JOIN `pro_cate` AS `cate3` ON `cate2`.`id` = `cate3`.`parent_id`
				LEFT JOIN `oe_item` AS `oe` ON `cate1`.`id` = `oe`.`oe_cate_id` OR `cate2`.`id` = `oe`.`oe_cate_id` OR `cate3`.`id` = `oe`.`oe_cate_id` 
				GROUP BY  `cate1`.`id` HAVING COUNT(oe.oe_id) %s %d)",$opr,$data));
			}

			if($field == 'pro_counts'){
				$temp = [
					'eq'=>'=',
					'le'=>'<=',
					'lt'=>'<',
					'gt'=>'>',
					'ge'=>'>='
				];
				$opr = $temp[$op];
				$op = 'RAW_'.$field;
				$data = raw(sprintf("id in (SELECT `cate1`.`id` FROM`pro_cate` AS `cate1` 
				LEFT JOIN `pro_cate` AS `cate2` ON `cate1`.`id` = `cate2`.`parent_id`
				LEFT JOIN `pro_cate` AS `cate3` ON `cate2`.`id` = `cate3`.`parent_id`
				LEFT JOIN `pro` AS `p` ON `cate1`.`id` = `p`.`p_cate` OR `cate2`.`id` = `p`.`p_cate` OR `cate3`.`id` = `p`.`p_cate` 
				GROUP BY  `cate1`.`id` HAVING COUNT(p.p_id) %s %d)",$opr,$data));
			}
			if($field == 'cat_procurement'){
				$op = 'RAW_'.$field;
				$data = raw(sprintf("cat_procurement in (SELECT ar_id FROM `adm_role` WHERE ar_isprocurement=1 AND ar_name like '%%%s%%')",$data));
			}
			if($field == 'cat_pmanager'){
				$op = 'RAW_'.$field;
				$data = raw(sprintf("cat_pmanager in (SELECT ar_id FROM `adm_role` WHERE ar_ispmanager=1 AND ar_name like '%%%s%%')",$data));
			}
			
        });
		if($where==null) $where = [];
		
		
		$pwids = \p::cates($rules['pwcode']);
		if(!\p::isAdmin() && $pwids != ''){
			$where['id'] = $this->getParentIds($pwids,true);
		}
		
		if(!empty($this->joinWhere)){
			$where = array_merge($where, $this->joinWhere);
		}

		if(!empty($this->group)){
			$where = array_merge($where, $this->group);
		}
        $where = $this->listWhere($where,$page,$pagesize,$sidx,$sord,$orderby);

		if($page>0 && $pagesize>0){
            if(empty($this->join)){
                $pages = $this->paging($table,$where,$page,$pagesize);
            }else{
                $pages = $this->paging($table,$this->join,'*',$where,$page,$pagesize);
            }
			$where["LIMIT"] = [$pages['limit'],$pagesize];
		}
        if(empty($this->join)){
            $rows = $this->db->select($table,$this->fields,$where);
        }else{
            $rows = $this->db->select($table,$this->join,$this->fields,$where);
        }
		//查零件总数量
		$oeCntSql = sprintf("SELECT cate_id,SUM(product_count) AS product_count FROM (
			SELECT cate1.id AS cate_id,COUNT(oe.oe_id) AS product_count
			FROM pro_cate AS cate1
			LEFT JOIN oe_item AS oe ON cate1.id = oe.oe_cate_id
			GROUP BY cate1.id
			UNION ALL
			SELECT cate1.id AS cate_id,COUNT(oe.oe_id) AS product_count
			FROM pro_cate AS cate1
			LEFT JOIN pro_cate AS cate2 ON cate1.id = cate2.parent_id
			LEFT JOIN oe_item AS oe ON cate2.id = oe.oe_cate_id
			GROUP BY cate1.id
			UNION ALL
			SELECT cate1.id AS cate_id,COUNT(oe.oe_id) AS product_count
			FROM pro_cate AS cate1
			LEFT JOIN pro_cate AS cate2 ON cate1.id = cate2.parent_id
			LEFT JOIN pro_cate AS cate3 ON cate2.id = cate3.parent_id
			LEFT JOIN oe_item AS oe ON cate3.id = oe.oe_cate_id
			GROUP BY cate1.id) AS subquery GROUP BY cate_id ORDER BY cate_id");
		$st = $this->db->query($oeCntSql);
		$oeCntRows = $st->fetchAll();
		$oeCntRows = array_column($oeCntRows,'product_count','cate_id');
		//查商品总数量
		$proCntSql = sprintf("SELECT cate_id,SUM(product_count) AS product_count FROM (
		SELECT cate1.id AS cate_id,COUNT(p.p_id) AS product_count
		FROM pro_cate AS cate1
		LEFT JOIN pro AS p ON cate1.id = p.p_cate
		GROUP BY cate1.id
		UNION ALL
		SELECT cate1.id AS cate_id,COUNT(p.p_id) AS product_count
		FROM pro_cate AS cate1
		LEFT JOIN pro_cate AS cate2 ON cate1.id = cate2.parent_id
		LEFT JOIN pro AS p ON cate2.id = p.p_cate
		GROUP BY cate1.id
		UNION ALL
		SELECT cate1.id AS cate_id,COUNT(p.p_id) AS product_count
		FROM pro_cate AS cate1
		LEFT JOIN pro_cate AS cate2 ON cate1.id = cate2.parent_id
		LEFT JOIN pro_cate AS cate3 ON cate2.id = cate3.parent_id
		LEFT JOIN pro AS p ON cate3.id = p.p_cate
		GROUP BY cate1.id) AS subquery GROUP BY cate_id ORDER BY cate_id");

		$st = $this->db->query($proCntSql);
		$proCntRows = $st->fetchAll();
		$proCntRows = array_column($proCntRows,'product_count','cate_id');
		$sortRows = [];
        $this->treeSortRows($rows,$sortRows);
        
        foreach($rows as $row){
            $sortRows[] = $row; //遗留
        }
		$rolesArr = $this->db->select('adm_role',['ar_id','ar_name'],['OR'=>['ar_ispmanager'=>1,'ar_isprocurement'=>1]]);	

		$rolesArr = array_column($rolesArr,null,'ar_id');
        foreach($sortRows as $k=>&$row){
			$t = json_decode($row['cat_cnpos'], true);
			if(!is_array($t)) $t = [];
			$row['oe_counts'] = $oeCntRows[$row['id']]?:'';
			$row['pro_counts'] = $proCntRows[$row['id']]?:'';
			$row['captions']['cat_cnpos'] = implode(',', array_column($t, 'name'));
			$row['captions']['attaqty'] = isset($this->attaqtys[$row['attaqty']])? $this->attaqtys[$row['attaqty']]: '';
			$row['captions']['cat_pmanager'] = isset($rolesArr[$row['cat_pmanager']])? $rolesArr[$row['cat_pmanager']]['ar_name']: '';
			$row['captions']['cat_procurement'] = isset($rolesArr[$row['cat_procurement']])? $rolesArr[$row['cat_procurement']]['ar_name']: '';
            //叶子节点
            if($row['right']-$row['left']==1){
                $row['leaf'] = true;
            }else{
                $row['leaf'] = false;
            }
			$row['tcd_name'] = trim($row['tcd_name'], ';');
			$row['prl_code_a'] = $row['prl_code_a'] ?? '';
        }
		unset($row);
		
		$data = [
			'page'=> $page,
			'total'=> $pages['total'],
			'records' => $pages['records'],
			'rows' => $sortRows
		];
		return $data;
	}
	function listOppo($rules, $where='',$page=0,$pagesize=0,$sidx='',$sord='asc',$orderby=''){
	    $page=1;
	    $pagesize = 1000;
	    $orderby='level,parent_id,en_name';
	    
        $table = $this->table.'(c)';
        $this->fields = ['*'];
        $this->join['[>]oppo_pro_cate'] = ['c.id'=>'opc_id'];
		$this->joinWhere = [];
		$this->group = [];
        $where = $this->filter2medoo($where,function(&$field,&$op,&$data){
            if($field=='en_name' || $field=='cn_name' || $field=='py_name'){
                $op = 'eq';
                $field = 'id';
                $data = $this->likeAndChilds($data,true);
				if(empty($data)) $data = 0;
            }
			if($field=='cat_model_fileds' || $field=='cat_cnpos')
			{
				if($data == 1)
				{
					$op = 'not';
					$data = '{}';
				}
				else if($data == 0)
				{
					$data = '{}';
				}
			}
        });
		if($where==null) $where = [];
		if(!empty($rules['pwcode']))
		{
			$pwids = \p::cates($rules['pwcode']);
			if($pwids != ''){
				$where['id'] = $this->getParentIds($pwids,true);
			}
		}
		if(!empty($this->joinWhere)){
			$where = array_merge($where, $this->joinWhere);
		}

		if(!empty($this->group)){
			$where = array_merge($where, $this->group);
		}
        $where = $this->listWhere($where,$page,$pagesize,$sidx,$sord,$orderby);

		if($page>0 && $pagesize>0){
            if(empty($this->join)){
                $pages = $this->paging($table,$where,$page,$pagesize);
            }else{
                $pages = $this->paging($table,$this->join,'*',$where,$page,$pagesize);
            }
			$where["LIMIT"] = [$pages['limit'],$pagesize];
		}
        if(empty($this->join)){
            $rows = $this->db->select($table,$this->fields,$where);
        }else{
            $rows = $this->db->select($table,$this->join,$this->fields,$where);
        }
		//dd($this->db->last());
		
		$sortRows = [];
        $this->treeSortRows($rows,$sortRows);
        
        foreach($rows as $row){
            $sortRows[] = $row; //遗留
        }
		
        foreach($sortRows as $k=>&$row){
			$t = json_decode($row['cat_model_fileds'], true);
			if(!is_array($t)) $t = [];
			$row['captions']['cat_model_fileds'] = implode(',', $t);

			$t = json_decode($row['cat_cnpos'], true);
			if(!is_array($t)) $t = [];
			$row['captions']['cat_cnpos'] = implode(',', array_column($t, 'name'));

            //叶子节点
            if($row['right']-$row['left']==1){
                $row['leaf'] = true;
            }else{
                $row['leaf'] = false;
            }
        }
        
		$data = [
			'page'=> $page,
			'total'=> $pages['total'],
			'records' => $pages['records'],
			'rows' => $sortRows
		];
		return $data;
	}
	
	function treeSortRows(&$rows,&$sortRows,$parent=0)
	{
	    foreach($rows as $k=>$row){
	        if($row['parent_id']==$parent){
	            $sortRows[] = $row;
	            unset($rows[$k]);
	            $this->treeSortRows($rows,$sortRows,$row['id']);
	        }
	    }
	}

	/*模糊摸查名称*/
    public function like($value){
        $value = trim($value);
        $where = ['OR'=>[
                    'cn_name[~]'=>$value,
                    'en_name[~]'=>$value,
                    'keyword[~]'=>$value
                    ]
                 ];
        $rows = $this->db->select($this->table,"id",$where);
        $rows = array_unique($rows);
        if(count($rows)==1) $rows = $rows[0];
        return $rows;
    }

	/*精确查名称*/
    public function eqname($value, $pcate = '', $isend = 1){
        $value = trim($value);
        $pcate = trim($pcate);
		if(!empty($pcate))
		{
			$join = ["[>]pro_cate(pcat)" => ["cat.parent_id" => "id"]];
			$where = [
			'AND #'=>[
					'OR #1'=>[
						'pcat.cn_name'=>$pcate,
						'pcat.en_name'=>$pcate,
						'pcat.py_name'=>$pcate,
					],
					'OR #2'=>[
						'cat.cn_name'=>$value,
						'cat.en_name'=>$value,
						'cat.py_name'=>$value,
						'cat.cat_as[~]'=>','.$value.',',
						// 'tcd_name[~]'=>';'.$value.';',
					],
				]
			];
			if($isend) $where['cat.right'] = raw('`cat`.`left`+1');
			return $this->db->get('pro_cate(cat)', $join,"cat.id",$where);
		}
		else
		{
			$where = [
				'AND #'=>[
					'OR'=>[
						'cn_name'=>$value,
						'en_name'=>$value,
						'py_name'=>$value,
						'cat_as[~]'=>','.$value.',',
						// 'tcd_name[~]'=>';'.$value.';',
					]
				]
			 ];
		    if($isend) $where['right'] = raw('`left`+1');
			return $this->db->get($this->table,"id",$where);
		}
    }
	
	//仅通过TCD名称匹配品名，可能返回多个
	public function eqnameByTcd($value, $pcate = '', $isend = 1){
        $value = trim($value);
        $pcate = trim($pcate);
		if(!empty($pcate))
		{
			$join = ["[>]pro_cate(pcat)" => ["cat.parent_id" => "id"]];
			$where = [
			'AND #'=>[
					'OR #1'=>[
						'pcat.cn_name'=>$pcate,
						'pcat.en_name'=>$pcate,
						'pcat.py_name'=>$pcate,
					],
					'OR #2'=>[
						'tcd_name[~]'=>';'.$value.';',
					],
				]
			];
			if($isend) $where['cat.right'] = raw('`cat`.`left`+1');
			return $this->db->select('pro_cate(cat)', $join,"cat.id",$where);
		}
		else
		{
			$where = [
				'AND #'=>[
					'OR'=>[
						'tcd_name[~]'=>';'.$value.';',
					]
				]
			 ];
		    if($isend) $where['right'] = raw('`left`+1');
			return $this->db->select($this->table,"id",$where);
		}
    }

    public function getCate($id){
        return $this->db->get($this->table,'*', ['id'=>$id]);
    }

	/*模糊摸查别名*/
    public function likeAs($value){
        $value = trim($value);
        $where = ['as[~]'=>$value];
        $rows = $this->db->select($this->table,"id",$where);
        $rows = array_unique($rows);
        if(count($rows)==1) $rows = $rows[0];
        return $rows;
    }

	/*模糊摸查名称，并返回所有子节点*/
    public function likeAndChilds($value,$hasSelf=false){
        $value = trim($value);
        $where = ['OR'=>[
                    'cn_name[~]'=>$value,
                    'en_name[~]'=>$value,
                    'py_name[~]'=>$value,
					'sp_name[~]'=>$value,
					'al_name[~]'=>$value,
                    ]
                 ];
        $ids = $this->db->select($this->table,"id",$where);
        $ids = array_unique($ids);
		$rows=[];
		if($ids){
			if($rows = $this->db->select($this->table,"id",['OR'=>['id'=>$ids,'parent_id'=>$ids]])){
    			$rows = array_unique($rows);
			}
			if($rows && $rows = $this->db->select($this->table,"id",['OR'=>['id'=>$ids,'parent_id'=>$rows]])){
    			$rows = array_unique($rows);
			}
		}
        if(count($rows)==1) $rows = $rows[0];
        return $rows;
    }

	/*模糊摸查名称，并返回所有父节点*/
    public function getParentIds($ids,$hasSelf=false){
        if(is_string($ids)) $ids = explode(',',$ids);
        $frows = $this->db->select($this->table,['left','right'],['id'=>$ids]);
		
        $arrAnd = [];
        $opLeft  = $hasSelf ? 'left[<=]' : 'left[<]';
        $opRight = $hasSelf ? 'right[>=]' : 'right[>]';
        foreach ($frows as $fk=>$frow){
            $arrAnd['AND #'.$fk] = [$opLeft=>$frow['left'],$opRight=>$frow['right']];
        }
        $where['OR'] = $arrAnd;
        $arrIds = $this->db->select($this->table,'id',$where);
        return $arrIds;
    }


	public function searchPart($word,$isbigCate=false,$limit=10000, $pwids = '',$pcate = '')
	{
		$word = trim($word);
		$data = [];
		if($word!=''){
			$fields = ['c.id', 'c.cn_name', 'c.en_name', 'c.py_name'];
			$where['OR'] =[
				'c.keyword[~]'=>$word,
				'c.cn_name[~]'=>$word,
				'c.en_name[~]'=>$word,
				'c.py_name[~]'=>$word,
				'c.al_name[~]'=>$word
			];
			$where['LIMIT'] = $limit;
			if(!empty($pcate)){
				$where['RAW_pids'] = raw(sprintf(" c.parent_id in (select id from pro_cate where cn_name ='%s' or en_name='%s' or py_name = '%s')",$pcate,$pcate,$pcate));
			}
		    if($isbigCate){
		        $where['RAW'] = raw("c.`right`-c.`left`>1");
				if(!empty($pwids))
					$where['RAW_ids'] = raw(" c.id in (select parent_id from pro_cate where id in (".$pwids."))");
		    }else{
		        $where['RAW'] = raw("c.`right`-c.`left`=1");
				if(!empty($pwids))
					$where['c.id'] = explode(',', $pwids);
		        $fields = array_merge($fields,[
		            'big.id(pid)', 'big.cn_name(pcn_name)', 'big.en_name(pen_name)', 'big.py_name(ppy_name)'
		        ]);
    			$join = [
    				"[><]pro_cate(big)" => ["c.parent_id" => "id"]
    			];
		    }
		    if(!$join){
		        $join = $fields; $fields = $where; $where = null;
		    }
			
			$data = $this->db->select('pro_cate(c)', $join, $fields, $where);
		}else if($isbigCate){
		    $where['RAW'] = raw("`right`-`left`>1");
			if(!empty($pwids))
				$where['RAW_ids'] = raw(" id in (select parent_id from pro_cate where id in (".$pwids."))");
			$data = $this->getAll($where);
		}else{
			if(!empty($pwids))
				$where['RAW_ids'] = raw(" id in (".$pwids.")");
			if(!empty($pcate)){
				$where['RAW_pids'] = raw(sprintf(" parent_id in (select id from pro_cate where cn_name ='%s' or en_name='%s' or py_name = '%s')",$pcate,$pcate,$pcate));
			}
			$data = $this->getAll($where);
		}
		return $data;
	}

	/**
	  * @method 复制属性
	  * @param  $from_cate  int  [必填] 
	  * @param  $to_cate  string  [必填] 逗号分隔
	  * @param  $fileds  string  [必填] cat_model_fileds,cat_zhuyi...
	  * @author soul
	  */
    function copyFileds($from_cate, $to_cate, $fileds)
	{
		$canSetFiled = ['cat_model_fileds', 'cat_zhuyi', 'cat_pzbz', 'cat_zpsl'];
		$setfiles = [];
		foreach(explode(',', $fileds) as $fk)
		{
			if(in_array($fk, $canSetFiled)) $setfiles[] = $fk;
		}
		if(empty($setfiles)) exitJson('参数异常');

		$fromArr = $this->db->get('pro_cate', $setfiles, ['id'=>$from_cate]);
		if(empty($fromArr)) exitJson('数据不存在');
		$this->db->update('pro_cate', $fromArr, ['id'=>explode(',', $to_cate)]);
		return [];
    }
    
	/**
	  * @method 取二级产品线,通过指定ID
	  * @param  $ids  array 
	  */
    function getBigCatesByIds($ids=[])
	{
	    $where = [];
	    if(!empty($ids)){
	       $where['OR']['parent_id'] = $ids; 
	       $where['OR']['id'] = $ids; 
	    }
	    $where['RAW'] = raw("`right`-`left`>1");
	    
		$rows = $this->db->select('pro_cate', '*', $where);
		$data = [];
		foreach ($rows as $row){
            $hasWhere['left[>]'] = $row['left']*1;
            $hasWhere['right[<]'] = $row['right']*1;
            $hasWhere['RAW'] = raw("`right`-`left`>1");
		    if(!$this->db->has('pro_cate',$hasWhere)){
		        $data[] = $row;
		    }
		}
		return $data;
    }
    
	/**
	  * @method 取二级产品线,通过小类
	  * @param  $cates  array 
	  */
    function getBigCatesByCates($cates)
	{
        $where['id'] = $cates; 
		$rows = $this->db->select('pro_cate', ['parent_id'], $where);
		$parent_ids = [];
		foreach ($rows as $row){
            $parent_ids[] = $row['parent_id'];
		}
		return $this->db->select('pro_cate', '*', ['id'=>$parent_ids]);
    }
    
	/**
	  * @method 通过产品线,取所有小类
	  * @param  $cates  array 
	  */
    function getCatesByBigCates($ids)
	{
		return $this->db->select('pro_cate', ['id','cn_name','en_name','py_name'], ['parent_id'=>$ids]);
    }

	//获取小类的竞品统计信息
	function cleanGaTj($cat_id)
	{
		$data = [];
		$row = $this->db->get('pro_cate', ['id','cn_name','en_name','py_name', 'tcd_name'], ['id'=>$cat_id]);
		if(!empty($row))
		$names = [];
		if(!empty($row['tcd_name'])){
			$names[] = $row['tcd_name'];
		}else{
			if(!empty($row['cn_name'])) $names[] = $row['cn_name'];
			if(!empty($row['en_name'])) $names[] = $row['en_name'];
			if(!empty($row['py_name'])) $names[] = $row['py_name'];
		}
		if(!empty($names)){
			$ypApi = new \model\ypApi();
			$res = $ypApi->Get('tcd/cleanGaTj', ['ganame'=>implode(';', $names)]);
			$data = $res['data'];
		}
		return $data;
	}

	function canMoveSubtree($id,$parent_id,$limitLevel=3)
	{
		if(!$id && !$parent_id) return ['status'=>true,'msg'=>''];
		$maxLevel =0;
		if(!$id){
			$curNode['level'] =0;
		}else{
			
			// 获取子树的当前层级
			$curNode = $this->db->get('pro_cate','*',['id'=>$id]);
			$left = $curNode['left']*1;
			$right = $curNode['right']*1;
			$oldparent = $curNode['parent_id']*1;
			if ($oldparent == $parent_id) {
				return ['status' => true, 'msg' => ''];
			}
			// 计算子树的最大层级
			$maxLevel =$this->db->max('pro_cate','level',[
				'left'."[>=]" => $left,
				'right'."[<=]" => $right,
			]);
		}
		
		$newParent = $this->db->get('pro_cate','*',['id'=>$parent_id]);
		// 检查新层级是否超过3级
		$newMaxLevel = $newParent['level'] + ($maxLevel - $curNode['level']) + 1;
		if ($newMaxLevel > $limitLevel) {
			return ['status'=>false,'msg'=>'系统只支持'.$limitLevel.'级小类，请选择另一个小类来添加'];
		}
	
		return ['status'=>true,'msg'=>''];
	}

	/**
	 * @param  int $cat_id
	 * @param  Array $param
	 * @method 将参数转换到参数表
	 * @author zhengweihua 
	 * @copyright 2025-01-08
	 */
	function formatParam($cat_id,$param)
	{	
		$rows = $this->db->select('part_param', ['ptpa_id','cn_name','en_name','py_name','tcd_name', 'ptpa_type','ptpa_unit','ptpa_decimal'], ['ptpa_cate_id'=>$cat_id]);
		$array = array_column($rows, null, 'cn_name');
		$fanyi = new fanyi();
		$this->db->Begin();
		foreach ($param as $key => $val) {
			if(!isset($array[$val['cn_name']])){
				$type = !$val['unit']?'string':'double';
				$py_name = $fanyi->translate($val['cn_name'],'zh','ru');
				$addData = [
					'ptpa_cate_id'           => $cat_id,
					'cn_name'         => trim($val['cn_name']),
					'en_name'         => trim($val['name']),
					'py_name'         => $py_name['dst']?trim($py_name['dst']):trim($val['name']),
					'tcd_name'         => trim($val['cn_name']),
					'ptpa_type'            => $type,
					'ptpa_length'          => 50,
					'ptpa_decimal'         => $type == 'double'?2:0,
					'ptpa_unit'            => trim($val['unit']) ?: '',
					'ptpa_is_edit'         => 1,
					'update_time'          => date('Y-m-d H:i:s'),
					'create_time'          => date('Y-m-d H:i:s'),
				];
				$this->db->insert('part_param', $addData);
			}elseif (isset($array[$val['cn_name']])) {
				$tcdNameArr = explode(';',$array[$val['cn_name']]['tcd_name']);
				$tcdNameArr = array_filter($tcdNameArr);
				if(!in_array($val['cn_name'],$tcdNameArr)){
					$tcdNameArr[] = $val['cn_name'];
					$this->db->update('part_param', ['tcd_name' => implode(';',$tcdNameArr)], ['ptpa_id' => $array[$val['cn_name']]['ptpa_id']]);
				}
			}
		}
		$this->db->End();
		return [];
	}


	function getCatesByCfg($cfg)
	{	
		$where = [$cfg['field'].'[!]'=>0];
		if($cfg['condition']){
			$where = array_merge($where, $cfg['condition']);
		}
		$rows = $this->db->select($cfg['table'],$cfg['field'],$where);
		return array_unique($rows);
	}

	 // 返回所有类型id
	function getAllIds()
	{
		$rows = $this->db->select('pro_cate','id',[]);
		return $rows;
	}

	/**
	 * @method 获取小类文件列表
	 * @author hongzhang
	 * @copyright 2026-02-25
	 */
	function fileList($params, $rules=[])
	{
		$filters = $params['filters'];
		$page = $params['page'];
		$pagesize = $params['rows'];
		$sidx = empty($params['sidx'])? 'pcf_sort': $params['sidx'];
		$sord = empty($params['sord'])? 'desc': $params['sord'];
		$orderby = $params['orderby'];

		$cateId = $params['key'];
		$table = 'pro_cate_file';
		$join = [
			'[>]files(file)' => ['pcf_fileid' => 'fileid'],
			'[>]object_tags_link(otl)' => [
				'pcf_fileid' => 'otl_val_id',
				'AND' => "otl.otl_table = 'cate' AND otl.otl_type = 'pic'"
			],
		];
		
		$where = $this->filter2medoo($filters,function(&$field,&$op,&$data){
			if($field == 'pcf_tags'){
				$field = 'otl_o_id';
			}
		});
		$where['pcf_cat_id'] = $cateId;
		$where['GROUP'] = ['pcf_fileid'];
		$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 = ['pcf_fileid','pcf_pb_id','pcf_type','pcf_remark','pcf_sort','pcf_opuser','pcf_lang','pcf_update_time','file.*'];
		
		$arr = $this->db->select($table,$join, $fields,$where);
		// 文件类型
		$fileType = ['img'=>'图片','video'=>'视频','cad'=>'CAD','other'=>'其他'];
		// 品牌
		$brand = $this->db->select('pro_brand',['pb_id','pb_'.LG_NAME.'(pb_name)'],[]);
		$brand = array_column($brand,'pb_name', 'pb_id');
		//语言
		$lang = \mvc::$cfg['LANGS'];
		
		if($arr){
			foreach ($arr as $key => &$val){
				// 如果是上传到阿里云的文件，需要拼接oss路径
				$fileUrl = '';
				
				if($val['file_isoss']){
					// $oss = new alioss();
					$fileUrl = \model\alioss::getPublicUrl($val['file_oss_path']);
				}else{
					$fileUrl = $val['filepath'].'/'.$val['filebasename'].'.'.$val['fileextname'];
				}
				$val['fileUrl'] = $fileUrl;
				$val['is_oss'] = $val['file_isoss']?1:0;

				// 拼接标签
				$tags = new tags();
				$tagArr = array_column($tags->getObjTags('pic'),'value','key');
				$tagIds =  $this->db->select('object_tags_link',['otl_o_id'],['otl_table'=>'cate','otl_type'=>'pic','otl_val_id'=>$val['pcf_fileid']]);
				$tagNameArr = [];
				if($tagIds){
					foreach ($tagIds as $tagRow) {
						if(isset($tagArr[$tagRow['otl_o_id']])){
							$tagNameArr[] = $tagArr[$tagRow['otl_o_id']];
						}
					}
				}
				
				$val['captions'] = [
					'pcf_type'=>$fileType[$val['pcf_type']]??'',
					'pcf_pb_id'=>$brand[$val['pcf_pb_id']]??'',
					'pcf_lang'=>$lang[$val['pcf_lang']]['name']??'',
					'pcf_tags'=>'<span>'.implode(',',$tagNameArr).'</span>',
				];
			}
		}
		$data = [
			'page'=> $page,
			'total'=> $pages['total'],
			'records' => $pages['records'],
			'rows' => $arr
		];
		return $data;
	}
	/**
	 * @method 将小类附件保存到pro_cate_file表
	 * @author hongzhang
	 * @copyright 2026-02-25
	 */
	function saveCateFile($cateId,$fileId,$extname)
	{
		$type = '';
		// 品牌默认为1
		$pb_id = 1;
		// 文件分类
		switch ($extname) {
			case 'jpg':
			case 'jpeg':
			case 'png':
			case 'gif':
			case 'tif':
			case 'bmp':
				$type = 'img';
				break;
			case 'mp4':
			case 'av':
				$type = 'video';
				break;
			case 'cad':
				$type = 'cad';
				break;
			default:
				$type = 'other';
				break;
		}

		$this->db->insert('pro_cate_file',[
			'pcf_cat_id'=>$cateId,
			'pcf_fileid'=>$fileId,
			'pcf_type'=>$type,
			'pcf_pb_id'=>$pb_id,
			'pcf_opuser'=>getOpuser()
		]);
	}

	/**
	 * @method 编辑小类文件(备注，排序等)
	 * @author hongzhang
	 * @copyright 2026-02-26
	 */
	function editFile($params)
	{
		$fileId = isset($params['fileid']) ? $params['fileid'] : $params['id'];
		$editArr = [];
		// 编辑排序
		if($params['pcf_sort']){
			$editArr['pcf_sort'] = $params['pcf_sort'];
		}
		//编辑备注
		if($params['pcf_remark']){
			$editArr['pcf_remark'] = $params['pcf_remark'];
		}
		//编辑类型
		if($params['pcf_type']){
			$editArr['pcf_type'] = $params['pcf_type'];
		}
		//编辑品牌
		if($params['pcf_pb_id']){
			$editArr['pcf_pb_id'] = $params['pcf_pb_id'];
		}
		//编辑语言
		if($params['pcf_lang'] != 'undefined'){
			$editArr['pcf_lang'] = $params['pcf_lang'];
		}
		if($editArr){
			$editArr['pcf_opuser'] = getOpuser();
		}
		$this->db->update('pro_cate_file',$editArr,['pcf_fileid'=>$fileId]);
		return [];
	}

	/**
	 * @method 删除小类文件
	 * @author hongzhang
	 * @copyright 2026-02-26
	 */
	function deleteFile($params)
	{
		if($params['ids']){
			$ids = explode(',',$params['ids']);
			$files = $this->db->select('files', '*', ['fileid' => $ids]);
			$ossIds = [];
			$localIds = [];
			$oss = null;
			
			foreach ($files as $file) {
				if ($file['file_isoss']) {
					if (!$oss) $oss = new alioss();
					if ($oss->doesObjectExist($file['file_oss_path'])) {
						$oss->deleteObject($file['file_oss_path']);
					}
					$ossIds[] = $file['fileid'];
				} else {
					$localIds[] = $file['fileid'];
				}
			}

			if (!empty($ossIds)) {
				$this->db->delete('files', ['fileid' => $ossIds]);
				$this->db->delete('pro_cate_file', ['pcf_fileid' => $ossIds]);
			}

			if (!empty($localIds)) {
				$fileModel = new \model\files();
				$fileModel->delete($localIds);
				$this->db->delete('pro_cate_file', ['pcf_fileid' => $localIds]);
			}
			$this->db->delete('object_tags_link', ['otl_table'=>'cate','otl_type'=>'pic','otl_val_id'=>$ids]);
		}
		return [];
	}

	/**
	 * @method 获取拍照标准，注意事项，照片示例图片文件信息
	 * @author hongzhang
	 * @copyright 2026-02-27
	 */
	function getFileInfo($fileIdsArr){
		$fileids = json_decode($fileIdsArr,true);
		$fileInfoArr = [];
		if($fileIdsArr && $fileids){
			$filesArr = $this->db->select('files','*',['fileid'=>$fileids]);
			foreach ($filesArr as $val) {
				$fileInfoArr[] = [
					'fileid'=>$val['fileid'],
					'filename'=>$val['filename'],
					'orgname' => $val['fileremark'].'.'.$val['fileextname']
				];
			}
		}
		return $fileInfoArr;
	}

	/**
	 * @param  int $cateId
	 * @method 获取需要填充经理的零件列表
	 * @author zhengweihua 
	 * @copyright 2026-03-02
	 */
	public function getfillOeManager($cateId = '')
	{	
		$where['OR'] = [
			'cat_pmanager[!]' => 0,
			'cat_procurement[!]' => 0
		];
		if($cateId){
			$where['id'] = $cateId;
		}
		$arrs = $this->db->select('pro_cate', ['cat_pmanager','cat_procurement','id'], $where);
		if(!$arrs){
			return [];
		}
		$catesArr = array_column($arrs, null, 'id');
		//获取缺少经理的零件
		$oeWhere['oe_cate_id'] = array_column($arrs, 'id');
		$oeWhere['OR'] = [
			'oe_pmanager' => 0,
			'oe_procurement' => 0
		];
		$rows = $this->db->select('oe_item',['oe_id','oe_cate_id'], $oeWhere);
		dd($this->db->last());
		foreach ($rows as $key => &$val) {
			if($val['oe_pmanager'] == 0){
				$val['oe_pmanager'] = $catesArr[$val['oe_cate_id']]['cat_pmanager'] ?: 0;
			}
			if($val['oe_procurement'] == 0){
				$val['oe_procurement'] = $catesArr[$val['oe_cate_id']]['cat_procurement'] ?: 0;
			}
		}
		unset($val);

		return $rows;
	}

	/**
	 * @param  Array $params
	 * @method 填充零件的经理和采购员
	 * @author zhengweihua 
	 * @copyright 2026-03-02
	 */
	public function fillOeManager($params)
	{
		$this->db->begin();	
		foreach ($params as $key => $val) {
			if($val['oe_pmanager'] == 0 && $val['oe_procurement'] == 0||!$val['oe_id']){
				continue;
			}
			$this->db->update('oe_item', ['oe_pmanager'=>$val['oe_pmanager'],'oe_procurement'=>$val['oe_procurement']], ['oe_id' => $val['oe_id']]);
		}
		$this->db->end();
		return [];
	}
}
