<?php
namespace app\controller\manager;

use app\model\{AuthRule, AuthGroup, Log};
use app\validate\AuthRule as VAuthRule;
use Exception;
use think\exception\ValidateException;
use think\response\Json;

class Rule extends Base
{
    /**
     * 权限排序
     * 暂不允许父级变更
     *
     * @return Json
     * @throws Exception
     */
    public function sort()
    {
        if ($this->request->isAjax()) {
            $id = input('post.id');
            $sort = input('post.sort');
            $num = input('post.num/d', 1);
            if($num <= 0){
                $num = 1;
            }
            if(!in_array($sort, ['up', 'down'], true)){
                return $this->json(2, '参数错误');
            }
            $item = AuthRule::getById($id);
            if(empty($item)){
                return $this->json(3, '权限不存在');
            }
            if($sort == 'up'){
                $where = "parent_id = {$item['parent_id']} and sort < {$item['sort']}";
                $order = "sort desc";
            }else{
                $where = "parent_id = {$item['parent_id']} and sort > {$item['sort']}";
                $order = "sort asc";
            }
            $forSortItems = AuthRule::getListByWhereAndOrder($where, $order, $num);
            if(!empty($forSortItems)){
                $updateData = [];
                $forSortCount = count($forSortItems);
                for($i = 0; $i < $forSortCount; $i++){
                    if($i == 0){
                        $updateData[] = [
                            'id' => $forSortItems[$i]['id'],
                            'sort' => $item['sort']
                        ];
                    }else{
                        $updateData[] = [
                            'id' => $forSortItems[$i]['id'],
                            'sort' => $forSortItems[$i - 1]['sort']
                        ];
                    }
                }
                $updateData[] = [
                    'id' => $item['id'],
                    'sort' => $forSortItems[$i - 1]['sort']
                ];
                if(!empty($updateData)){
                    $model = new AuthRule();
                    $model->saveAll($updateData);
                    $sortStr = $sort == 'up' ? '上移' : '下调';
                    Log::write('rule', 'sort', "权限排序，ID：{$id} ，标题：{$item['title']}，{$sortStr}了{$num}位");
                    return $this->json();
                }
            }
            return $this->json(4, '无须调整排序!');
        }
        return $this->json(1, '非法请求！');
    }

    /**
     * 权限删除
     */
    public function del()
    {
        if ($this->request->isAjax()) {
            $ids = input('post.ids/a');
            $items = AuthRule::where('id', 'in', $ids)->select();
            if(!$items){
                return $this->json(1, '无此权限');
            }
            if(AuthRule::where('parent_id', 'in', $ids)->count()){
                return $this->json(2, '当前权限有下级权限，不可删除');
            }
            AuthRule::destroy($ids);
            AuthGroup::resetGroupRulesCache();
            $ids = implode(',', $ids);
            Log::write('rule', 'del', "权限删除，ID：{$ids}");
            return $this->json();
        }
        return $this->json(1, '非法请求！');
    }

    /**
     * 权限修改
     */
    public function edit()
    {
        if($this->request->isPost()){
            $item = input('post.item/a');
            $id = input('post.id');
            $rule = AuthRule::getById($id);
            if(empty($rule)){
                return $this->json(1, '请选择正确的权限');
            }
            $rule2 = AuthRule::getByName($item['name']);
            if(!empty($rule2) && $rule2['id'] != $id){
                return $this->json(2, '已存在相同权限['.$item['name'].']');
            }
            try {
                validate(VAuthRule::class)->check($item);
                AuthRule::updateById($id, $item);
                AuthGroup::resetGroupRulesCache();
                Log::write('rule', 'edit', "权限编辑，ID：{$id}, 标题：{$item['title']}");
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(3, $e->getError());
            }
        }
        $id = input('param.id/d');
        $rule = AuthRule::getById($id);
        if(empty($rule)){
            return $this->json(1,'无此权限信息，请核对之后再操作!');
        }else{
            $this->data['item'] = $rule;
            if($rule['parent_id'] > 0){
                $parent = AuthRule::getById($rule['parent_id']);
                $this->data['parent'] = $parent;
            }
            return $this->view();
        }
    }

    /**
     * 权限添加
     */
    public function add()
    {
        if($this->request->isPost()){
            $item = input('post.item/a');
            try {
                validate(VAuthRule::class)->check($item);
                $rule = AuthRule::getByName($item['name']);
                if(!empty($rule)){
                    return $this->json(1, '已存在相同权限');
                }
                $rule = AuthRule::create($item);
                //基本权限的话需要重置所有已有角色权限缓存
                if ($item['is_base'] > 0) {
                    AuthGroup::resetGroupRulesCache();
                } else {
                    AuthGroup::resetGroupRulesCache(1);
                }
                Log::write('rule', 'add', "权限新增，ID：{$rule->id}, 标题：{$item['title']}");
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(2, $e->getError());
            }
        }
        $parentId = input('param.parent_id/d',0);
        if($parentId > 0){
            $parent = AuthRule::getById($parentId);
            $this->data['parent'] = $parent;
        }
        $this->data['parentId'] = $parentId;
        return $this->view();
    }

    /**
     * 权限列表(全部)
     */
    public function index()
    {
        $list = AuthRule::getListTree();
        $this->data['items'] = $list;
        return $this->view();
    }
}