<?php

namespace app\controller\manager;

use app\model\Log;
use app\model\Menu;
use app\model\Menu as MenuModel;
use app\model\Role as RoleModel;
use app\model\Rules;
use app\repository\CmsRepository;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Db;
use think\response\Json;
use think\response\View;

/**
 * 角色管理
 *
 * Class Role
 * @package app\controller\manager
 */
class Role extends Base
{

    /**
     * 删除
     *
     * @return Json
     */
    public function del(): Json
    {
        if ($this->request->isPost()) {
            $ids = input('post.ids/a', []);
            if (empty($ids)) {
                $ids[] = input('post.id/d');
            }
            RoleModel::deleteByIds($ids);
            Log::write(get_class().'Del', 'del', '涉及到的ID为：'.implode(',', $ids));
            return $this->json();
        }
        return $this->json(4001, '非法请求!');
    }

    /**
     * 编辑
     *
     * @return Json|View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function edit()
    {
        $id = input('id/d', 0);

        if (!$info = RoleModel::findById($id)) {
            return $this->json(4001, '记录不存在');
        }

        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'title' => 'require',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            try {
                $info->save($item);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

        $this->data['item'] = $info;

        return $this->view();
    }

    /**
     * 单个字段编辑
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function modify(): Json
    {
        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'field' => 'require',
                'value' => 'require',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            if (!$info = RoleModel::findById($item['id'])) {
                return $this->json(4001, '记录不存在');
            }

            $update = [$item['field'] => $item['value']];

            try {
                $info->save($update);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }
        return $this->json(4000, '非法请求');
    }

    /**
     * 添加
     *
     * @return Json|View
     * @throws Exception
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $item = input('post.');

            $validate = $this->validateByApi($item, [
                'title' => 'require',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            try {
                RoleModel::create($item);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

        return $this->view();
    }

    /**
     * 角色权限
     *
     * @return Json|View
     * @throws Exception
     */
    public function rule()
    {
        $id = input('id/d', 0);

        if (!$item = RoleModel::findById($id)) {
            return $this->json(4001, '记录不存在');
        }

        if ($this->request->isPost()) {
            $ids    = input('post.ids');
            $roleUpdate = $ids;//角色更新数据
            $ids    = explode(',', $ids);

            Db::startTrans();
            try {
                //查询角色已有权限
                $hasRules = Rules::where('ptype', 'p')->where('v0', $id)->select()->toArray();
                //角色最新权限列表
                $currentRules = MenuModel::where('id', 'in', $ids)->field('name')->select()->toArray();

                foreach ($currentRules as &$rule) {
                    $route = explode(':', $rule['name']);
                    $v1 = $route[0];
                    $v2 = $route[1] ?? 'index';

                    $rule['ptype'] = 'p';
                    $rule['v0'] = $id;
                    $rule['v1'] = $v1;
                    $rule['v2'] = $v2;
                }

                foreach ($hasRules as $k => $has) {
                    foreach ($currentRules as $m => $current) {
                        if ($has['ptype'] == $current['ptype'] && $has['v0'] == $current['v0'] && $has['v1'] == $current['v1'] && $has['v2'] == $current['v2']) {
                            unset($currentRules[$m]);//删除当前权限列表已存在的 currentRules剩下的就是需要添加的记录
                            unset($hasRules[$k]);//删除已有权限中存在的 hasRules剩下的就是需要删除的记录
                        }
                    }
                }

                $insert = $currentRules;//需要添加的数据
                $delete = $hasRules;//需要删除的数据

                $deleteIds = array_column($delete, 'id');//需要删除的ID
                (new Rules())->saveAll($insert);
                (new Rules())->where('id', 'in', $deleteIds)->delete();
                cache('tauthz', null);//权限缓存清空

                $item->save(['rules' => $roleUpdate]);
                Db::commit();
                return $this->json();
            } catch (ValidateException $e) {
                Db::rollback();
                return $this->json(4001, $e->getError());
            }
        }

        $selected = explode(',', $item['rules']);

        $this->data['authJson'] = $this->authJson($selected);
        $this->data['item']     = $item;

        return $this->view();
    }

    /**
     * 构造json数据
     *
     * @param  array  $selected
     * @return false|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function authJson(array $selected = [])
    {
        $username = session('auth')['username'] ?? '';//非超级管理员admin 部分展示权限

        $menus = Menu::field("id,pid,title,sort")
            ->where('status', Menu::STATUS_NORMAL)
            ->when($username != 'admin', function ($q) {
                $q->where('show_role', 1);
            })
            ->order('sort', 'desc')
            ->order('id', 'asc')
            ->select()->toArray();
        foreach ($menus as $k => $m) {
            $menus[$k]['checked'] = in_array($m['id'], $selected);
            $menus[$k]['open']    = true;
        }
        $menus = CmsRepository::getInstance()->buildMenuChild(0, $menus);
        return json_encode($menus, JSON_UNESCAPED_UNICODE);
    }

    /**
     * 列表
     *
     * @return View|Json
     * @throws Exception
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $page  = input('page/d', 1);
            $limit = input('size/d', 20);
            $items = RoleModel::findList([], [], $page, $limit, function ($q) {
                return $q->order('sort', 'desc')->order('id', 'asc');
            });

            return $this->json(0, '操作成功', $items);
        }

        $this->data['username'] = $this->auth['username'] ?? '';
        return $this->view();
    }
}