<?php
namespace siruisoft\common\model;

use siruisoft\common\model\ModelBase;
use think\Db;
/**
 * @Author: 思睿软件
 * @Date:   2020-01-09 09:07:49
 * @Last Modified by:   Administrator
 * @Last Modified time: 2020-03-11 19:07:04
 * Category 统一类
 * 要求: 所有category同构,主键id
 */


class Category extends ModelBase{

	protected $_id ='id';   //数据表主键

	//当前数据表
	protected $_table;

    //展示的标题字段 尽量使用title
	protected $_title = 'title';

	//存放所有类别 优化查询
	protected $_all = [];

	protected  $_table_map=[
	            'topic'   => 'topic_category',
	            'goods'   => 'goods_category',
	       ];
    

    function  setId($id){
		$this->_id= $id;
		return $this;
	}


	function getId(){
		return $this->_id;
		return $this;
	}

	function  setTable($table){
		$this->_table = strtolower($table);
		return $this;
	}


	function  getTable(){
		return $this->_table;
		return $this;
	}

	//通过type 设置table
	function setType($type){
		$this->setTable($this->_table_map[$type]);
		return $this;
	}



	function  setTitle($title){
		$this->_title = strtolower($title);
		return $this;
	}


	function  getTitle(){
		return $this->_title;
		return $this;
	}


	/**
	 * 所有类别
	 * @Author   思睿软件<363359328@qq.com>
	 * @DateTime 2020-01-09T09:10:12+0800
	 * @return   [type]                   [description]
	 */
	function  getAllCategorys(){
		if(empty($this->_table) || !in_array($this->_table,$this->_table_map)) return [];
		$ckey = $this->_table.'_all';
		$rows = cache($ckey);
		if(1==config('open_cache')){
			if($rows) return $rows;
		}
		$rows = Db::name($this->_table)->order('sort ASC')->select();
		if($rows){
			cache($ckey,$rows);
		}
		return $rows;
	}

	/**
	 * [getSonCategorys 获取所有儿子类别]
	 * @Author   思睿软件<363359328@qq.com>
	 * @DateTime 2020-01-09T09:51:28+0800
	 * @param    integer                  $pid [description]
	 * @return   [type]                        [description]
	 */
	function getSonCategorys($id=0){
		empty($this->_all) && $this->_all=$this->getAllCategorys();
		$rets =[];
		foreach ($this->_all as $key => $value) {
			if($value['pid']==$id){
				$rets[]= $value;
			}
		}
		return $rets;
	}

	/**
	 * [getChildCategorys 获取所有的子孙节点]
	 * @Author   思睿软件<363359328@qq.com>
	 * @DateTime 2020-01-09T10:11:40+0800
	 * @param    integer                  $id [description]
	 * @return   [type]                       [description]
	 */
	function getChildCategorys($id=0){
		empty($this->_all) && $this->_all=$this->getAllCategorys();
		static $rets = array();
        foreach ($this->_all as $value) {
            if ($value['pid']==$id) {
                $rets[] = $value;
                $this->getChildCategorys($value[$this->_id]);
            }
        }
        return $rets;
	}


	//所有孩子的id
	function getChildIds($id=0){
		empty($this->_all) && $this->_all=$this->getAllCategorys();
		static $rets = array();
        foreach ($this->_all as $value) {
            if ($value['pid']==$id) {
                $rets[] = $value[$this->_id];
                $this->getChildCategorys($value[$this->_id]);
            }
        }
        return $rets;
	}


    //获取所有祖先 返回ids =[]
	function getParents($id){
		empty($this->_all) && $this->_all=$this->getAllCategorys();
		static $rets = array();
		//当前类别
		$row = getOneByItem($this->_all,'id',$id);
		array_unshift($rets, $row);
		if($row['pid']>0){
			$this->getParents($row['pid']);
		}
        return $rets;
	}

	/**
	 * 获取完整名称  形如:职业培训/医疗卫生/执业医师技能/临床医师
	 * @Author   思睿软件<363359328@qq.com>
	 * @DateTime 2020-01-09T10:41:12+0800
	 * @param    [type]                   $id [description]
	 * @return   [type]                       [description]
	 */
	function getFullName($id){
		$full = $this->getParents($id);
		$rets =[];
		foreach ($full as $key => $value) {
			$rets[] = $value[$this->_title];
		}
		return implode('/', $rets);
	}


	/**
	 * [categoryList 层级展示 父亲----孩子---孙子...父亲---孩子---...]
	 * @Author   思睿软件<363359328@qq.com>
	 * @DateTime 2020-01-09T09:49:19+0800
	 * @param    [type]                   $categorys [description]
	 * @return   [type]                              [description]
	 */
	function categoryList($id=0,$level=0){
		empty($this->_all) && $this->_all=$this->getAllCategorys();
		static $rets = [];
        foreach ($this->_all as $key=>$value){
            if ($value['pid'] == $id) {
                if ($level == 0) {
                    $value['new_title'] = $value[$this->_title];
                } elseif ($level>0) {
                    $value['new_title'] = str_repeat('&emsp;&emsp;',$level+1). '└ '.$value[$this->_title];
                }
                $rets[] = $value;
                $this->categoryList($value[$this->_id],($level+1));
            }
        }
        return $rets;
	}
    
    /**
     * [tree     构建层级关系child存放孩子]
     * @Author   思睿软件<363359328@qq.com>
     * @DateTime 2020-01-09T12:28:25+0800
     */
    function tree($pid=0){
    	empty($this->_all) && $this->_all=$this->getAllCategorys();
    	if($this->_all){
    		return $this->makeTree($this->_all,$pid);
    	}
    	return [];
    }

	/**
	 * [Tree 获取类别的层级树 child 存放孩子节点]
	 * @Author   思睿软件<363359328@qq.com>
	 * @DateTime 2020-01-09T10:44:38+0800
	 * @param    integer                  $pid   [description]
	 * @param    integer                  $level [description]
	 * @return   [type]                          [description]
	 */
	protected function makeTree($array,$pid = 0)
    {
        $rets = [];
        foreach ($array as $key => $value) {
            if ($value['pid'] == $pid) {
                $value['child'] = $this->makeTree($array, $value[$this->_id]);
                if (!$value['child']) {
                    unset($value['child']);
                }
                $rets[] = $value;
            }
        }
        return $rets;
    }


    /**
     * [addCategory 添加和修改,同时清除缓存]
     * @Author   思睿软件<363359328@qq.com>
     * @DateTime 2020-01-09T12:37:25+0800
     * @param    [type]                   $data [description]
     */
    function  publish($data,$id=0){
    	if(empty($data)){
    		return ['error'=>1,'msg'=>'非法操作'];
    	}

    	$ckey = $this->_table.'_all';
    	$condition[] = [$this->_title,'=',$data['title']];
    	$condition[] =['pid','=',intval($data['pid'])];
    	if($id>0){
    		$condition[]= [$this->_id,'<>',$id];
    	}
    	if(Db::name($this->_table)->where($condition)->count()>0){
    		return ['error'=>1,'msg'=>'类别已经存在'];
    	}
    	try {
    		if($id>0){  //编辑
    			Db::name($this->_table)->where($this->_id,$id)->update($data);
    		}else{
    			Db::name($this->_table)->insert($data);
    		}
    		cache($ckey,null);
    		return ['error'=>0,'msg'=>'操作成功'];
    	} catch (Exception $e) {
    		echo $e->getMessage();
    		return ['error'=>1,'msg'=>'操作失败'];
    	}
    }


    /**
     * [delByIds 删除类别,只允许一个一个删除,清除缓存]
     * @Author   思睿软件<363359328@qq.com>
     * @DateTime 2020-01-09T12:46:26+0800
     * @param    [type]                   $ids [description]
     * @return   [type]                        [description]
     */
    function  delById($id){
    	if($id<=0){
    		return ['error'=>1,'msg'=>'非法操作'];
    	}
    	$ckey = $this->_table.'_all';
       	if(Db::name($this->_table)->where('pid',$id)->count()>0){
       		return ['error'=>1,'msg'=>'有子类别不能删除'];
       	}
        try {
    		Db::name($this->_table)->where($this->_id,$id)->delete();
    		cache($ckey,null);
    		return ['error'=>0,'msg'=>'操作成功'];
    	} catch (Exception $e) {
    		return ['error'=>1,'msg'=>'操作失败'];
    	}
    }



    function getById($id){
    	if($id<=0){
    		return ['error'=>1,'msg'=>'非法操作'];
    	}
    	$row = Db::name($this->_table)->where($this->_id,$id)->find();
    	return ['error'=>0,'msg'=>'操作成功','data'=>$row];
    }


    //清除单表缓存
    function clearcache(){
    	$ckey = $this->_table.'_all';
    	cache($ckey,null);
    }


    function getFullNameByFullPath($full_ids){
    	$ids = array_filter(explode(',', $full_ids));
    	if(count($ids)==0) return '';
    	$all = $this->getAllCategorys();
    	$ret =[];
    	foreach ($ids as $key => $value) {
    		$row = get_one_by_item($all,$this->_id,$value);
    		$ret[] = $row[$this->_title];
    	}
    	return implode('/', $ret);
    }


    function hasChilds($id){
    	empty($this->_all) && $this->_all=$this->getAllCategorys();
		foreach ($this->_all as $key => $value) {
			if($value['pid']==$id){
				return 1;
			}
		}
		return 0;
	}

}