<?php
// +----------------------------------------------------------------------
// | 文海代码生成器
// +----------------------------------------------------------------------
// | Copyright (c) 2021 https://www.kaifashu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 开发树
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\common\model\Document as DocumentModel;
use app\common\model\DocumentCategory as DocumentCategoryModel;
use app\common\model\DocumentCategoryContent as DocumentCategoryContentModel;
use app\common\validate\DocumentCategory as DocumentcategoryValidate;
use think\Db;

/**
 *文章分类
 */
class DocumentCategory extends Auth
{

    /**
     * 后台文章分类首页
     * @return none
     */
    public function index() {

        $model=new DocumentCategoryModel();
        $lists = $model
            -> where('status','>',-1)
            -> field('id,pid,title,sort,display')
            -> order('sort asc,id asc') -> select();

        $lists=list_to_tree($lists);
        $this -> assign('listJson', json_encode($lists));
        return $this -> fetch();
    }
    /**
     * 新增
     */
    public function add($pid=0){
        $thisModel=new DocumentCategoryModel();
        if($this->request->isGet()){
            $IsShowList=$thisModel->is_showList;
            $categorylist = $thisModel
                -> where('status',1)
                -> field('id,title,status,pid')
                -> select();
            $categorylist=list_to_tree($categorylist);
            $categorylist=list_to_char_tree($categorylist);
            $this->assign('cid',$pid);
            $this->assign('dclist', $categorylist);
            $this->assign('IsShowList',$IsShowList);
            return $this -> fetch();
        }
        //分类内容模型
        $contentModel=new DocumentCategoryContentModel();

        $postData=$this->request->param();

        //验证
        $documentcategoryValidate = new DocumentcategoryValidate();
        if (!$documentcategoryValidate -> check($postData)) {
            $this -> error($documentcategoryValidate -> getError());
        }
        $re=$contentModel->add_data($postData);
        if($re){
            //删除分类缓存
            cache('DATA_DOCUMENT_CATEGORY_LIST', null);
            $this->success('新增成功！','index');
        }
        else{
            $this->error('新增失败！');
        }

    }
    /**
     * 编辑
     */
    public function edit(){
        $thisModel=new DocumentCategoryModel();
        $contentModel=new DocumentCategoryContentModel();
        $id=input('id');
        $categoryInfo = $thisModel -> get($id);
        if (!$categoryInfo) {
            $this -> error('分类不存在或已删除！');
        }
        if($this->request->isGet()){
            $IsShowList=$thisModel->is_showList;
            $this->assign('IsShowList',$IsShowList);
            $info=$thisModel->get($id);
            $this->assign('info',$info);
            $infos=$contentModel->get($id);
            $this->assign('infos',$infos);
            //获取分类列表，这里去除它自己
            $categorylist = $thisModel
                ->where('status','>',-1)
                ->where('id','<>',$id)
                ->field('id,title,status,pid')
                ->select();
            $categorylist=list_to_tree($categorylist);
            $categorylist=list_to_char_tree($categorylist);
            $this -> assign('dclist', $categorylist);

            return $this -> fetch();
        }
        $paramData=$this->request->param();
        //验证
        $documentcategoryValidate = new DocumentcategoryValidate();
        if (!$documentcategoryValidate -> check($paramData)) {
            $this -> error($documentcategoryValidate -> getError());
        }
        $re=$contentModel->edit_data($paramData,$categoryInfo);
        if($re){
            //删除分类缓存
            cache('DATA_DOCUMENT_CATEGORY_LIST', null);
            $this->success('编辑成功！','index');
        }
        else{
            $this->error('编辑失败！');
        }
    }
    /**
     * 删除
     */
    public function del(){
        $id= input('ids/d');
        $thisModel=new DocumentCategoryModel();
        $contentModel=new DocumentCategoryContentModel();
        //判断该分类下有没有子分类，有则不允许删除
        $child = $thisModel->where('pid',$id)->where('status','>',-1)->find();
        if (!empty($child)) {
            $this -> error('请先删除该分类下的子分类!');
        }
        //判断该分类下有没有文章
        $documentModel=new DocumentModel();
        $document_list = $documentModel -> where('category_id',$id)->where('status','>',-1)->find();
        if (!empty($document_list)) {
            $this -> error('请先删除该分类下的文章!');
        }
        $re=true;
        // 启动事务
        Db::startTrans();
        try {
            //伪删除
            $where[] =['id','in',$id];
            $thisModel->save([
                'status'  => -1
            ],$where);
            //删除副表数据
            $contentModel->del($id);
            //更新上级child_id
            $thisModel->del_category_child_item($id);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $re=false;
        }
        if($re){
            //删除分类缓存
            cache('DATA_DOCUMENT_CATEGORY_LIST', null);

            $this->success('删除成功！');
        }
        else{
            $this->error('删除失败！');
        }

    }
    /**
     * 排序
     */
    public function sort(){
        if ($this->request->isPost()){
            $data['id']=input('id/d');
            $data['sort']=input('sort');
            $thisModel=new DocumentCategoryModel();
            //验证
            $documentcategoryValidate = new DocumentcategoryValidate();
            if (!$documentcategoryValidate -> scene('sort') -> check($data)) {
                $this -> error($documentcategoryValidate -> getError());
            }
            $re=$thisModel->edit($data);
            if($re){
                //删除分类缓存
                cache('DATA_DOCUMENT_CATEGORY_LIST', null);
                $this->success('操作成功！');
            }else{
                $this->error($thisModel->getError());
            }
        }
    }
    /**
     * 显示隐藏
     */
    public function set_display(){
        if ($this->request->isPost()){
            $data['id']=input('id/d');
            $data['display']=input('val/d');
            $thisModel=new DocumentCategoryModel();
            $res=$thisModel->edit($data);
            if($res){
                if ($data['display'] == 1) {
                    //隐藏
                    $setDisplay = "document_category_display_xian";
                }
                if ($data['display'] == 0) {
                    //显示
                    $setDisplay = "document_category_display_yin";
                }
                //删除分类缓存
                cache('DATA_DOCUMENT_CATEGORY_LIST', null);
                $this->success('操作成功！','');
            }else{
                $this->error($thisModel->getError());
            }
        }
    }

    /**
     * 工具页面：重置所有分类的child_id和parent_id
     */
    public  function reset_category_child_parent_id(){
        $category_lists = db('document_category') -> field('id,pid')->order('id asc') -> select();

        foreach ($category_lists as $var){
            //更新子类（child 字段） begin
            //每次循环前 将数组清空
            array_splice($this->childList, 0, count($this->childList));
            //调用递归方法
            $list_child=$this->new_get_category_child_id($category_lists,$var['id']);

            if($list_child){
                //有子类 处理数据
                $var_child_lists=implode(",", array_reverse($list_child));//array_reverse()以相反的元素顺序返回数组。
                //将处理好的字符串 更新到child字段
                db('document_category') ->where('id',$var['id'])->setField('child',$var_child_lists);
            }else{
                //没有子类  更新为空
                db('document_category') ->where('id',$var['id'])->setField('child','');
            }
            //更新子类 over

            //更新 父类 parent_id字段 begin
            //每次循环前 将数组清空
            array_splice($this->parentList, 0, count($this->parentList));
            //调用递归方法
            $list_parent=$this->new_get_category_parent_id($category_lists,$var['pid']);
            if($var['pid']==0){
                //顶级分类  更新为空
                db('document_category') ->where('id',$var['id'])->setField('parent_id','');
            }else{
                //有父类 处理数据
                //将根id加入到数组
                array_push($list_parent,$var['pid']);
                //去除 数组中的 0、null、""。
                $list_parent=array_filter($list_parent);
                //转换为 字符串
                $var_parent_lists=implode(",",$list_parent);
                //将处理好的字符串 更新到child字段
                db('document_category') ->where('id',$var['id'])->setField('parent_id',$var_parent_lists);
            }
        }
        $this -> success('已重置所有分类的child和parent_id！',null,'stop');
    }
    //定义全局变量 子类列表数组
    private $childList=array();
    //子类递归方法
    private function new_get_category_child_id($lists,$pid){
        foreach ($lists as $item){
            if($item['pid']==$pid){
                $arr=$this->new_get_category_child_id($lists,$item['id']);
                array_push($this->childList ,$item['id']);
            }
        }
        return $this->childList;
    }

    //定义全局变量 父类列表数组
    private $parentList=array();
    //父类递归方法
    private function new_get_category_parent_id($lists,$pid){
        foreach ($lists as $item){
            if($item['id']==$pid){
                $arr=$this->new_get_category_parent_id($lists,$item['pid']);
                array_push($this->parentList ,$item['pid']);
            }
        }
        return $this->parentList;
    }

    /**
     * 分类转换为数据树（栏目分类页面）
     */
    private function list_to_html_tree($lists) {

        $treeList=[];
        foreach($lists as $key=>$item){
            $item['line']='';

            for($x=0;$x<$item['level'];$x++){
                $item['line']='<span class="zz-tree-item-line"></span>'.$item['line'];
            }

            if(isset($item['child'])){
                $item['icon']='<span class="zz-tree-icon '.($item['level']>0?'zz-tree-after-line':'').'"><i class="layui-icon zz-tree-ctrl layui-icon-subtraction"></i></span>';
                $treeItem=$this->list_to_html_tree($item['child']);
                unset($item['child']);
                array_push($treeList,$item);
                $treeList=array_merge($treeList,$treeItem);
            }
            else{
                $item['icon']='<span class="zz-tree-icon '.($item['level']>0?'zz-tree-after-line':'').'"><i class="layui-icon zz-tree-sigle layui-icon-file"></i></span>';
                array_push($treeList,$item);
            }
        }
        return $treeList;
    }


}