<?php

namespace app\admin\model;

use think\Cache;
use think\Model;
use think\Url;
use tree\Tree;

class Category extends Model {
    protected $autoWriteTimestamp = true;
    protected $IsMenuIds = [];

    protected static function init()
    {
        //编辑后可用
        Category::event('after_update', function () {
            Cache::tag('category_data')->clear();
        });
        //新增后可用
        Category::event('after_insert', function () {
            Cache::tag('category_data')->clear();
        });
        //写入后  貌似没用到
        Category::event('after_write', function () {
            Cache::tag('category_data')->clear();
        });
        //删除后
        Category::event('after_delete', function () {
            Cache::tag('category_data')->clear();
        });
    }

    //获取栏目列表数据
    public function adminCategoryTableData(){
        $where = ['c.delete_time' => 0];
        $field=('c.*,m.name as model_name');
        $categories = $this->alias('c')->join("models m","c.model_id = m.id")->order("c.sort ASC")->field($field)->where($where)->select()->toArray();
        //获取模型的一维数组 以便提取控制器名称
        $models=model('models')->adminGetModelArray();
        $icon = ['&nbsp;&nbsp;│', '&nbsp;&nbsp;├─', '&nbsp;&nbsp;└─'];
        $nbsp = '&nbsp;&nbsp;';
        $newCategories = [];

        foreach ($categories as $key=>$item) {
            //生成模型控制器
            $controller_name = $models[$item['model_id']];
            if($item['parent_id'] == 0){
                $child = $this->getChild($item['id'],$categories);
                $child_count = count($child);
                $item['icon'] = '';
                $item['add_url'] = $item['model_id'] == 4 || $child_count > 0 ? '' : url("admin/$controller_name/add", ["category" => $item['id']]);
                array_push($newCategories,$item);
                foreach ($child as $ck=>$cv){
                    if($ck == $child_count - 1){
                        $child[$ck]['icon'] = $nbsp.$icon[2];
                    }else{
                        $child[$ck]['icon'] = $nbsp.$icon[1];
                    }
                    // 添加按钮
                    $controller_name = $models[$cv['model_id']];
                    $child[$ck]['add_url'] = $cv['model_id'] == 4 ? '' : url("admin/$controller_name/add", ["category" => $cv['id']]);
                }

                $newCategories = array_merge($newCategories,$child);
            }
        }
        return $newCategories;
    }

    //得到子级数组
    public function getChild($myId,&$arr){
        $newArr = [];
        if (is_array($arr)) {
            foreach ($arr as $id => $a) {
                if ($a['parent_id'] == $myId) {
                    $newArr[] = $a;
                }
            }
        }
        return $newArr ? $newArr : [];
    }

    //获取栏目 select树形结构数据
    public function adminCategorySelectData($currentCid = 0)
    {
        $where = ['delete_time' => 0];
        if (!empty($currentCid)) {
            $where['id'] = ['neq', $currentCid];
        }
        $categories = $this->order("sort ASC")->where($where)->select()->toArray();
        $icon = ['&nbsp;&nbsp;│', '&nbsp;&nbsp;├─', '&nbsp;&nbsp;└─'];
        $nbsp = '&nbsp;&nbsp;';
        $newCategories = [];
        foreach ($categories as $item) {
            if($item['parent_id'] == 0){
                $child = $this->getChild($item['id'],$categories);
                $child_count = count($child);
                $item['icon'] = '';
                array_push($newCategories,$item);
                foreach ($child as $ck=>$cv){
                    if($ck == $child_count - 1){
                        $child[$ck]['icon'] = $nbsp.$icon[2];
                    }else{
                        $child[$ck]['icon'] = $nbsp.$icon[1];
                    }
                }
                $newCategories = array_merge($newCategories,$child);
            }
        }
        return $newCategories;
    }

    //根据不同model获取select树状结构数据
    public function adminCategorySelectDataToModelId($currentCid = 0,$banId = 0){
        $where = ['delete_time' => 0];
        if (!empty($currentCid)) {
            $where['id'] = ['neq', $currentCid];
        }
        $categories = $this->order("sort ASC")->where($where)->select()->toArray();
        $icon = ['&nbsp;&nbsp;│', '&nbsp;&nbsp;├─', '&nbsp;&nbsp;└─'];
        $nbsp = '&nbsp;&nbsp;';
        $newCategories = [];
        foreach ($categories as $item) {
            if($item['parent_id'] == 0){
                $child = $this->getChild($item['id'],$categories);
                $child_count = count($child);
                $item['icon'] = '';
                $item['is_ban'] = $child_count > 0 || $item['model_id'] != $banId  ? 1 : 0;
                array_push($newCategories,$item);
                foreach ($child as $ck=>$cv){
                    if($ck == $child_count - 1){
                        $child[$ck]['icon'] = $nbsp.$icon[2];
                    }else{
                        $child[$ck]['icon'] = $nbsp.$icon[1];
                    }
                    $child[$ck]['is_ban'] = $cv['model_id'] != $banId ? 1 : 0;
                }
                $newCategories = array_merge($newCategories,$child);
            }
        }
        return $newCategories;
    }

    //获取category_id的子级
    public function checkCategoryChild($id){
        $this->geAllChildIdsToCategoryId($id);
        if(count($this->IsMenuIds) == 1){
            return false;
        }else{
            return true;
        }
    }

    //是否显示  如果有子级同时修改子级
    public function adminIsMenuToCategory($id){
        $data=$this->getCategoryData($id);
        $this->geAllChildIdsToCategoryId($id);
        foreach ($this->IsMenuIds as $k=>$v){
            $update[$k]['id']=$v;
            $update[$k]['is_menu']=$data['is_menu'] == 1 ? 0 : 1;
        }
        $up=$this->isUpdate(true)->saveAll($update);
        return $up;
    }

    //获取一个id下包含自己id的所有子级id
    public function geAllChildIdsToCategoryId($id){
        $this->IsMenuIds[]=$id;
        $data=$this->where(['parent_id'=>$id,'delete_time'=>0])->field('id,name,parent_id')->select();
        if(count($data) == 0){
            return;
        }else{
            $data=$data->toArray();

            foreach ($data as $val){
                $this->geAllChildIdsToCategoryId($val['id']);
            }
        }
    }

    //获取一条数据
    public function getCategoryData($id){
       $field='c.id,c.parent_id,c.model_id,c.name,c.is_menu,m.name as model_name,m.tablename';
       $data=$this->alias('c')->join('__MODELS__ m','c.model_id=m.id')->field($field)->find($id);
       if(is_null($data)){
           return false;
       }
        return $data->toArray();
    }

    //添加
    public function add($param){
        $res=$this->isUpdate(false)->allowField(true)->save($param);
        if($param['model_id'] != 4){
            $fun='lists';
            if ((int)$param['model_id'] == 1 || (int)$param['parent_id'] == 0){
                $fun='index';
            }
            $id=$this->id;
            $this->edit(['id'=>$id,'url'=>$this->getUrlToModelId($id,$param['model_id'],$fun)]);
        }
        return $res;
    }

    //编辑
    public function edit($param){
        return $this->isUpdate(true)->allowField(true)->save($param);
    }

    //删除
    public function del($id){
        return $this->destroy($id);
    }

    //根据模型id查找内容(目前主要是链接模型使用了)
    public function adminGetDataToModelId($model_id){
        return $this->where(['delete_time'=>0,'model_id'=>$model_id])->order('id desc')->select()->toArray();
    }

    //生成前台可访问url
    public function getUrlToModelId($id,$model_id,$fun='index'){
        $model_data=model('models')->adminGetTableNameToModelId($model_id);
        Url::root('/');
        $url=url('index/'.$model_data['tablename'].'/'.$fun,['category'=>$id]);
        return $url;
    }

}