<?php


namespace app\admin\controller;

use app\BaseController;
use app\admin\model\Role as RoleModel;
use app\admin\model\Admin;
use app\admin\model\RoleMenu;
use app\admin\model\User;
use app\admin\validate\RoleValidate;
use think\facade\Db;
use think\facade\Cache;
use Exception;

class Role extends BaseController
{

    /**
     * @api {get} /role/list 查看角色列表
     */
    public function list()
    {
        try {
            $params = $this->request->param();
            $query = new RoleModel();
            if (!empty($params['name'])) {
                $query = $query->where('name', 'like', '%'.$params['name'].'%');
            }
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            $count = $query->count();
            $list = $query->order('id', 'desc')
                ->limit($limit)
                ->page($page)
                ->select();
            
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success(['count' => $count, 'list' => $list]);
    }

    /**
     * @api {post} /role/update 添加/修改
     * @apiGroup 角色
     * @apiVersion 1.0.0
     * @apiUse header
     * @apiUse lang
     *
     * 'id' => $params['id'],
     * @apiParam {Integer} id ID
     * @apiParam {String} name 名称
     * @apiParam {String} desc 描述
     */
    public function update()
    {
        DB::startTrans();
        try {
            $params = (new RoleValidate())->post()->goCheck('edit');
            $id = $this->request->param('id',0);
            $menuId = $params['menu_id'] ?? [];
            $is_exists = RoleModel::where('name', $params['name'])->where('id', '<>', $id)->find();
            if ($is_exists) {
                return $this->error('角色名称不可重复');
            }

            unset($params['menu_id']);
            if ($id) {    
                //删除当前角色的菜单
                RoleMenu::where(['role_id' => $id])->delete();
        
                RoleModel::where('id', $id)->update($params);
                $role_id = $id;

                //同步角色头像到user表
                $admin_ids = Admin::where('role_id', $id)->column('id');
                if($admin_ids){
                    User::where('role','>',0)->whereIn('uid', $admin_ids)->update(['avatar'=>$params['avatar']]);
                }

                //删除角色权限的缓存
                Cache::delete('role_menu_'.$role_id);
            } else {
                $role = RoleModel::create($params);
                $role_id = $role->id;
            }

            //添加角色的权限
            $data = [];
            foreach ($menuId as $item) {
                if (empty($item)) {
                    continue;
                }
                $data[] = [
                    'role_id' => $role_id,
                    'menu_id' => $item,
                ];
            }
            RoleMenu::insertAll($data);
            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success();

    }

    //删除
    public function delete()
    {
        try {
            $params = (new RoleValidate())->goCheck('id');

            //校验角色是否绑定管理员
            $count = Admin::where('role_id', $params['id'])->count();
            if($count > 0){
                return $this->error('该角色下有管理员，不能删除');
            }
            RoleModel::where('id', $params['id'])->delete();
            
            //删除角色权限的缓存
            Cache::delete('role_menu_'.$params['id']);
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success();
    }

    //查看详情
    public function info()
    {
        try {
            $params = (new RoleValidate())->goCheck('id');
            $role = RoleModel::where('id', $params['id'])->find();
            if(empty($role)){
                return $this->error('角色不存在');
            }
            //获取角色的菜单
            $role->menu = RoleMenu::where('role_id', $params['id'])->column('menu_id');
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success($role);
    }

}