<?php
namespace admin\action\pro;
use \model\carmodel;
use \model\pro\cate;
use \model\check;
class cateAction  extends \action{
	function list(){
		$req = \mvc::$req;
        $cate = new cate();
		$data = $cate->list2($req, $req['filters'], $req['page'], $req['rows'], $req['sidx'], $req['sord']);
		$this->successJson($data);
	}
	
	function list2(){
        $req = \mvc::$req;
		//前置条件
		$rules = $this->urlRulesToWhere($req);
        $data = (new cate())->list2($rules,$req['filters'], $req['page'], $req['rows'], $req['sidx'], $req['sord'],'');
        $this->successJson($data);
	}
	
	function listOppo(){
        $req = \mvc::$req;
		//前置条件
		$rules = $this->urlRulesToWhere($req);
        $data = (new cate())->listOppo($rules,$req['filters'], $req['page'], $req['rows'], $req['sidx'], $req['sord'],'');
        $this->successJson($data);
	}

	function getAttaqtys()
	{
		$arr = [['key'=>'', 'value'=>'']];
		$cate = new cate();
		foreach($cate->attaqtys as $k=>$v)
		{
			$arr[] = ['key'=>$k, 'value'=>$v];
		}
		$this->successJson($arr);
	}
	function getMasAttaqtys()
	{
		$arr = [['key'=>'', 'value'=>'']];
		$cate = new cate();
		foreach($cate->attaqtys2 as $k=>$v)
		{
			$arr[] = ['key'=>$k, 'value'=>$v];
		}
		$this->successJson($arr);
	}


	/**
	  * @method 是否有产品
	  * @param  id int [必填] ID
	  * @return bool
	  */
	public function hasPro($id)
    {
        $pro = makeOne(\model\pro\pro::class);
        $result = $pro->has('p_cate',$id);
        $this->successJson($result);
    }

	/**
	  * @method 取参数示意图
	  * @return url
	  */
	public function param_photo($cid)
    {
        $url = '';
        $cate = new cate();
        if($row = $cate->getRowByKey($cid)){
            if($row['photo_param']){
                $url = makeOne(\model\files::class)->getFilename($row['photo_param']);
                $url = makeOne(\lib\file::class)->formatDir($url);
                $url = ltrim($url,'/');
            }
        }
        $this->successJson(['filename'=>$url]);
    }

	/**
	  * @method 明细
	  * @param  id int [必填] ID
	  * @author soul
	  */
	public function form()
    {
		$req = \mvc::$req;
		$carmodel = new carmodel();
		$cate = new cate();
		\view::set('smallModelfields', $carmodel->smallModelCatefields);
		\view::set('smallMustFileds', $carmodel->smallMustFileds);
		$dataArr = [];
		if(!empty($req['id']))
		{
			$dataArr = $cate->lrtree->getNode($req['id']);
			$dataArr['cat_model_fileds'] = !empty($dataArr['cat_model_fileds'])? json_decode($dataArr['cat_model_fileds'], true): [];
			$dataArr['captions']['cat_cnpos'] = '';
			if(!empty($dataArr['cat_cnpos']))
			{
				$tarr = [];
				$cnpos = json_decode($dataArr['cat_cnpos'], true);
				foreach($cnpos as $rv)
				{
					$row = $rv['name'];
					if(isset($rv['seq'])) $row .= ':'.$rv['seq'];
					$tarr[] = $row;
				}
				$dataArr['captions']['cat_cnpos'] = implode("\n", $tarr);
			}
		}
		\view::set('attaqtysitems', $cate->attaqtysItems());
		\view::set('attaqtys2items', $cate->attaqtys2Items());
		\view::set('dataArr', $dataArr);
		\view::put();
    }

	function setForm(){
		$req = \mvc::$req;
        $cate = new cate();
		$re = ['：'=>':', '，'=>',', '；'=>';'];
		$setArr = [
			'cn_name'=>$req['cn_name'],
			'en_name'=>$req['en_name'],
			'as'=>$req['as'],
			'keyword'=>$req['keyword'],
			'attaqty'=>$req['attaqty'],
			'attaqty2'=>$req['attaqty2'],
			'cat_zhuyi'=>$req['cat_zhuyi'],
			'cat_pzbz'=>$req['cat_pzbz'],
			'cat_zpsl'=>$req['cat_zpsl'],
			'cat_model_fileds'=>[],
			'cat_cnpos'=>[],
			'cat_cnpos_fileds'=>'',
			'cat_cnpos_vals'=>strtr($req['cat_cnpos_vals'], $re),
			'cat_cn_numtype'=>$req['cat_cn_numtype'],
			'autobarcode'=>$req['autobarcode'],
			'is_moreline' => $req['is_moreline'],
			'bpm_product_line' => $req['bpm_product_line'],
			'develop_days' => $req['develop_days'],
			'iv_value'=>$req['iv_value'],
			'iv_werks'=>$req['iv_werks'],
			'iv_werks'=>$req['iv_werks'],
			'smart_lock'=>$req['smart_lock'],
			'smart_cc_ids'=>$req['smart_cc_ids'],
		];
		
		if(!empty($req['cat_model_fileds']))
		{
			foreach($req['cat_model_fileds'] as $fk=>$v)
			{
				if(!empty($v['checked']))
					$setArr['cat_model_fileds'][$fk] = $v['name'];
			}
		}
		if(!empty($req['cat_cnpos']))
		{
			$fileds = ['pml_pos0','pml_pos1','pml_pos2','pml_pos3','pml_pos4',];
			$seqArr = [];
			$ofileds = [];
			$req['cat_cnpos'] = strtr($req['cat_cnpos'], $re);
			foreach(explode("\n", $req['cat_cnpos']) as $v)
			{
				$tarr = explode(':', $v);
				$name = $tarr[0];
				if(empty($name)) continue;
				$filed = array_shift($fileds);
				$row = ['filed'=>$filed, 'name'=>$name];
				if(count($tarr) > 1)
				{
					$row['seq'] = (int) $tarr[1];
					$ofileds[$row['seq']] = $filed;
				}
				ksort($ofileds);
				$setArr['cat_cnpos'][] = $row;
			}
			$setArr['cat_cnpos_fileds'] = implode(',', $ofileds);
		}

		$setArr['cat_model_fileds'] = json_encode($setArr['cat_model_fileds'], JSON_UNESCAPED_UNICODE);
		$setArr['cat_cnpos'] = json_encode($setArr['cat_cnpos'], JSON_UNESCAPED_UNICODE);
		$check = new check();
		$checkArr = $setArr;
		$checkArr['parent_id'] = $req['parent_id'];
		$exist = $check->checkExist('pro_cate', $checkArr, $req['id']);
		if(!empty($exist)) exitJson('名称已存在');
		if(!empty($req['id'])){
			if($cate->editCate($req['id'], $req['parent_id'], $setArr)){
				$this->successJson();
			}
		}else{
			if($cate->addCate($req['parent_id'], $setArr)){
				$this->successJson();
			}
		}
	}


	function move($prevKey,$key,$nextKey){
        $cate = new cate();
		if($cate->lrtree->moveNode($prevKey,$key,$nextKey)){
			$this->successJson();
		}
	}

	function delete($id){
        $cate = new cate();
		$data = $cate->delCate($id);
		$this->successJson($data);
	}

    function getNode($id){
        $cate = new cate();
        $data = $cate->lrtree->getNode($id);
        $this->successJson($data);
    }

	function getNodesByIds($ids){
        $cate = new cate();
        $data = $cate->lrtree->getNodesByIds($ids);
        $this->successJson($data);
    }

    function getParent($id){
        $cate = new cate();
        $data = $cate->lrtree->getParent($id);
        $this->successJson($data);
    }

    function getParents($id,$hasSelf){
        $cate = new cate();
        $data = $cate->lrtree->getParents($id,$hasSelf);
        $this->successJson($data);
    }

    function getChilds($id){
        $cate = new cate();
        $data = $cate->lrtree->getChilds($id);
        $this->successJson($data);
    }

	 /**
	  * @method 重构树
	  */
    function restructure($root){
		set_time_limit(3600);
        (new cate())->lrtree->restructure($root);
        $this->successJson();
    }

	 /**
	  * @method 品名选择
	  * @param  $pwcode  string  [选填]  权限代码
	  * @param  $style  string  [选填] 选择模式 anychk:多选  空(默认):单选
	  * @param  $pcateid  string  [选填] 指定产品线 逗号分隔
	  * @author soul
	  */
    function select()
	{
		$req = \mvc::$req;
		$style = !empty($req['style']) && $req['style'] == 'anychk'? 'anychk': '';
        $cate = new cate();
        $allPart = $cate->lrtree->getChilds(0);
		$allPart = array_column($allPart, null, 'id');
		
		//指定产品线
		$rulecate = null;
		if(!empty($req['pcateid']))
		{
			$rulecate = [];
			foreach(explode(',', $req['pcateid']) as $id)
			{
				$rows = $cate->lrtree->getChilds($id);
				$rulecate = array_merge($rulecate, array_column($rows, 'id'));
			}
		}
		
		//是否有权限控制
		if(!empty($req['pwcode']))
		{
			$pwids = \p::cates($req['pwcode']);
			if($pwids != '' && !\p::isAdmin())
			{
				if($rulecate !== null)
					$rulecate = array_intersect($rulecate, explode(',', $pwids));
				else
					$rulecate = explode(',', $pwids);
			}
		}

		if($rulecate !== null)
		{
			foreach($rulecate as $cid)
			{
				$pcatid = $allPart[$cid]['parent_id'];
				$rulecate[] = $pcatid;
				if(!empty($allPart[$pcatid]))
				$rulecate[] = $allPart[$pcatid]['parent_id'];
			}
			foreach($allPart as $k=>$v)
			{
				if(!in_array($v['id'], $rulecate))
					unset($allPart[$k]);
			}
			\view::set('ispwcode', 1);
		}
		
		//拼装零件树
		$partTree = [];
		foreach($allPart as $k=>$v)
		{
			if(empty($partTree[$v['parent_id']]))
				$partTree[$v['parent_id']] = [$v['id']];
			else
				$partTree[$v['parent_id']][] = $v['id'];
		}
		\view::set('req', $req);
		\view::set('allPart', $allPart);
		\view::set('style', $style);
		\view::set('partTree', $partTree);
		\view::put();
    }

	 /**
	  * @method 通过关键字查询品名
	  * @param  $word  string  [必填] 关键字
	  * @author soul
	  */
    function searchPart()
	{
		$req = \mvc::$req;
		$cate = new cate();
        $data = $cate->searchPart($req['word']);

		//指定产品线
		$rulecate = null;
		if(!empty($req['pcateid']))
		{
			$rulecate = [];
			foreach(explode(',', $req['pcateid']) as $id)
			{
				$rows = $cate->lrtree->getChilds($id);
				$rulecate = array_merge($rulecate, array_column($rows, 'id'));
			}
		}
		
		//是否有权限控制
		if(!empty($req['pwcode']))
		{
			$pwids = \p::cates($req['pwcode']);
			if($pwids != '' && !\p::isAdmin())
			{
				if($rulecate !== null)
					$rulecate = array_intersect($rulecate, explode(',', $pwids));
				else
					$rulecate = explode(',', $pwids);
			}
		}

		//是否有权限控制
		if($rulecate !== null)
		{
			foreach($data as $k=>$v)
			{
				if(!in_array($v['id'], $rulecate))
					unset($data[$k]);
			}
			$data = array_values($data);
		}

		$this->successJson($data);
    }
	
    public function getAllKeyValues($fields=null)
    {
		$req = \mvc::$req;
		$cate = new cate();
		$isBigCate = isset($req['isBigCate']) && $req['isBigCate'];
		$no_moreline = isset($req['no_moreline']) && $req['no_moreline'];
		if((isset($req['query']) && isset($req['limit'])) || $isBigCate)
		{
			//是否有权限控制
			$pwids = !empty($req['pwcode'])? \p::cates($req['pwcode']): '';
			$rows = $cate->searchPart($req['query'],$isBigCate,$req['limit'], $pwids);
		}else{
			$pwids = !empty($req['pwcode'])? \p::cates($req['pwcode']): '';
			$rows = $cate->searchPart('',false,999999, $pwids);
		}
        $data = [];
        $regi=0;
		$firstkey = isset($req['firstkey'])? $req['firstkey']: 0;
        if(isset($req['hasFirst']) && $req['hasFirst']){
            $data[0] = ['key'=>$firstkey, 'value'=>'' ];
            $regi = 1;
        }
        foreach($rows as $k=>$row){
            if($no_moreline){
                if($row['is_moreline']) continue;
            }
            $data[$k+$regi] = ['key'=>$row['id'], 'value'=> $row[cateName()] ];
        }
        $this->successJson($data);
    }

	/**
	  * @method 复制属性
	  * @param  $from_cate  int  [必填] 
	  * @param  $to_cate  string  [必填] 逗号分隔
	  * @param  $fileds  string  [必填] cat_model_fileds,cat_zhuyi...
	  * @author soul
	  */
    function copyFileds()
	{
		$req = \mvc::$req;
		$cate = new cate();
        $data = $cate->copyFileds($req['from_cate'], $req['to_cate'], $req['fileds']);
		$this->successJson($data);
    }

	/**
	  * @method 取二级产品线, 通过指定ID
	  * @param  $ids  string|array 
	  */
    function getBigCatesByIds($ids='')
	{
		$cate = new cate();
		if(is_string($ids)){
		    $ids = ($ids=='') ? [] : explode(',',$ids);
		}
        $data = $cate->getBigCatesByIds($ids);
		$this->successJson($data);
    }

	/**
	  * @method 取二级产品线, 通过指定ID
	  * @param  $cates string|array
	  */
    function getBigCatesByCates($cates='')
	{
		$cate = new cate();
		if(is_string($cates)){
		    $cates = ($cates=='') ? [] : explode(',',$cates);
		}
        $data = $cate->getBigCatesByCates($cates);
		$this->successJson($data);
    }
    
	/**
	  * @method 通过产品线,取所有品名
	  * @param  $cates  array 
	  */
    function getCatesByBigCates($ids)
	{
		$cate = new cate();
		if(is_string($ids)){
		    $ids = ($ids=='') ? [] : explode(',',$ids);
		}
        $data = $cate->getCatesByBigCates($ids);
		$this->successJson($data);
    }
}