<?php

namespace app\controller\admin\system;

use app\BaseController;
use app\entity\SysMenu;
use app\entity\SysRole;
use app\service\CurdService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;

class RoleController extends BaseController
{
    /**
     * 查询角色列表
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list(): Json
    {
        $lists = CurdService::getList($this->request, new SysRole());

        return $this->writeSuccess('ok', $lists);
    }

    /**
     * 查询角色菜单
     * @param $role_id
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getMenu($role_id)
    {
        $role = SysRole::findOrFail($role_id);
        $menuIds = $role->menus->column('menu_id');
        $menus = SysMenu::select()->each(function (SysMenu $menu) use ($menuIds) {
            $menu->checked = in_array($menu['menu_id'], $menuIds);
        });
        return $this->writeSuccess('ok', $menus);
    }

    /**
     * 更新角色菜单
     * @param $role_id
     * @return Json
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function updateMenu($role_id)
    {
        $menus = $this->request->put();
        $role = SysRole::findOrFail($role_id);
        $role->menus()->attach($menus);
        return $this->writeSuccess('操作成功');
    }

    /**
     * 分页查询角色列表
     * @return Json
     * @throws DbException
     */
    public function page(): Json
    {
        $model = SysRole::withSearch(['roleName', 'roleCode'], [
            'roleName' => $this->request->get('roleName/s', ''),
            'roleCode' => $this->request->get('roleCode/s', ''),
        ]);

        $paginate = CurdService::getPaginate($this->request, $model);

        return $this->writeSuccess('ok', $paginate);
    }

    /**
     * 批量删除角色
     * @return Json
     */
    public function removeRoles(): Json
    {
        $data = $this->request->delete();
        SysRole::destroy($data);
        return $this->writeSuccess('删除成功');
    }
}