<?php

namespace app\admin\controller\school\help;

use app\admin\model\AuthRule;
use app\common\controller\Backend;
use fast\Tree;
use think\Cache;

/**
 * 帮助分类
 *
 * @icon fa fa-circle-o
 */
class Cate extends Backend
{

    /**
     * Cate模型对象
     * @var \app\admin\model\school\help\Cate
     */
    protected $model = null;

    protected $rulelist = [];

    protected $qSwitch = true;
    protected $qFields = ["pid"];

    public function _initialize()
    {
        $this->model = new \app\admin\model\school\help\Cate;
        parent::_initialize();

        $this->view->assign("statusList", $this->model->getStatusList());

        Tree::instance()->init(collection($this->model->order('weigh DESC,id ASC')->select())->toArray())->icon = array('&nbsp;&nbsp;&nbsp;&nbsp;│', '&nbsp;&nbsp;&nbsp;&nbsp;├', '&nbsp;&nbsp;&nbsp;&nbsp;└');
        $this->rulelist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');
        $ruledata = [0 => __('None')];
        foreach ($this->rulelist as $k => &$v) {
//            $v['name'] = str_replace('&nbsp;', ' ', $v['name']);
            $ruledata[$v['id']] = $v['name'];



        }
        unset($v);
        $this->view->assign('ruledata', $ruledata);

        $this->view->assign("cateList", (new \app\admin\model\school\help\Article)->getCateList());
        $this->view->assign("cateListJson", json_encode((new \app\admin\model\school\help\Article)->getCateList(), JSON_UNESCAPED_UNICODE));

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */



    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            //如果发送的来源是 Selectpage，则转发到 Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }


            $list = $this->rulelist;
            $total = count($this->rulelist);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                if ($params['pid']) {
                    $parent = \app\admin\model\school\help\Cate::get($params['pid']);
                    if ($parent && $parent['level_num'] > 1) {
                        $this->error(__('分类不能超过二级！'));
                    }
                }
                $result = $this->model->save($params);
                if ($result === false) {
                    $this->error($this->model->getError());
                }

                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
//                if (!$params['ismenu'] && !$params['pid']) {
//                    $this->error(__('The non-menu rule must have parent'));
//                }
                if ($params['pid'] == $row['id']) {
                    $this->error(__('Can not change the parent to self'));
                }
                if ($params['pid'] != $row['pid']) {
                    $childrenIds = Tree::instance()->init(collection($this->model->order('weigh DESC,id ASC')->select())->toArray())->getChildrenIds($row['id']);
                    if (in_array($params['pid'], $childrenIds)) {
                        $this->error(__('Can not change the parent to child'));
                    }
                }
                if ($params['pid']) {
                    $parent = \app\admin\model\school\help\Cate::get($params['pid']);
                    if ($parent && $parent['level_num'] > 1) {
                        $this->error(__('分类不能超过二级！'));
                    }
                }

                //这里需要针对name做唯一验证
                $ruleValidate =  \app\admin\model\school\help\Cate::where( 'name' , $params['name'] )-> where( 'id' , '<>' , $row['id'] )->find();

                if( $ruleValidate ){
                    $this->error( '分类名称已存在' );
                }

                $result = $row->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }

                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $delIds = [];
            foreach (explode(',', $ids) as $k => $v) {
                $delIds = array_merge($delIds, Tree::instance()->getChildrenIds($v, true));
            }
            $delIds = array_unique($delIds);
            $count = $this->model->where('id', 'in', $delIds)->delete();
            if ($count) {

                $this->success();
            }
        }
        $this->error();
    }

}
