package com.taais.system.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.taais.common.core.core.domain.CommonResult;
import com.taais.common.core.core.page.PageResult;
import com.taais.common.excel.utils.ExcelUtil;
import com.taais.common.log.annotation.Log;
import com.taais.common.log.enums.BusinessType;
import com.taais.common.web.core.BaseController;
import com.taais.system.domain.SysUserRole;
import com.taais.system.domain.bo.SysDeptBo;
import com.taais.system.domain.bo.SysRoleBo;
import com.taais.system.domain.bo.SysUserBo;
import com.taais.system.domain.vo.DeptTreeSelectVo;
import com.taais.system.domain.vo.SysRoleVo;
import com.taais.system.domain.vo.SysUserVo;
import com.taais.system.service.ISysDeptService;
import com.taais.system.service.ISysRoleService;
import com.taais.system.service.ISysUserRoleService;
import com.taais.system.service.ISysUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 角色信息
 *
 * @author wgk
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {
    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysUserService userService;

    @Resource
    private ISysUserRoleService userRoleService;

    @Resource
    private ISysDeptService deptService;

    @SaCheckPermission("system:role:list")
    @GetMapping("/list")
    public CommonResult<PageResult<SysRoleVo>> list(SysRoleBo roleBo) {
        return CommonResult.success(roleService.selectPage(roleBo));
    }

    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @SaCheckPermission("system:role:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysRoleBo roleBo) {
        List<SysRoleVo> list = roleService.selectRoleList(roleBo);
        ExcelUtil.exportExcel(list, "角色数据", SysRoleVo.class, response);
    }

    /**
     * 根据角色编号获取详细信息
     */
    @SaCheckPermission("system:role:query")
    @GetMapping(value = "/{roleId}")
    public CommonResult<SysRoleVo> getInfo(@PathVariable Long roleId) {
        roleService.checkRoleDataScope(roleId);
        return CommonResult.success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @SaCheckPermission("system:role:add")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public CommonResult<Void> add(@Validated @RequestBody SysRoleBo roleBo) {
        roleService.checkRoleAllowed(roleBo);
        if (!roleService.checkRoleNameUnique(roleBo)) {
            return CommonResult.fail("新增角色'" + roleBo.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(roleBo)) {
            return CommonResult.fail("新增角色'" + roleBo.getRoleName() + "'失败，角色权限已存在");
        }
        boolean inserted = roleService.insertRole(roleBo);
        if (!inserted) {
            return CommonResult.fail("新增角色记录失败！");
        }
        return CommonResult.success();
    }

    /**
     * 修改保存角色
     */
    @SaCheckPermission("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public CommonResult<Void> edit(@Validated @RequestBody SysRoleBo roleBo) {
        roleService.checkRoleAllowed(roleBo);
        roleService.checkRoleDataScope(roleBo.getRoleId());
        if (!roleService.checkRoleNameUnique(roleBo)) {
            return CommonResult.fail("修改角色'" + roleBo.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(roleBo)) {
            return CommonResult.fail("修改角色'" + roleBo.getRoleName() + "'失败，角色权限已存在");
        }
        boolean updated = roleService.updateRole(roleBo);
        if (updated) {
            roleService.cleanOnlineUserByRole(roleBo.getRoleId());
            return CommonResult.success();
        }
        return CommonResult.fail("修改角色'" + roleBo.getRoleName() + "'失败，请联系管理员");
    }

    /**
     * 修改保存数据权限
     */
    @SaCheckPermission("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public CommonResult<Void> dataScope(@RequestBody SysRoleBo roleBo) {
        roleService.checkRoleAllowed(roleBo);
        roleService.checkRoleDataScope(roleBo.getRoleId());
        boolean updated = roleService.authDataScope(roleBo);
        if (!updated) {
            return CommonResult.fail("修改角色'" + roleBo.getRoleName() + "'数据权限失败，请联系管理员");
        }

        return CommonResult.success();
    }

    /**
     * 状态修改
     */
    @SaCheckPermission("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public CommonResult<Void> changeStatus(@RequestBody SysRoleBo roleBo) {
        roleService.checkRoleAllowed(roleBo);
        roleService.checkRoleDataScope(roleBo.getRoleId());
        boolean updated = roleService.updateRoleStatus(roleBo);
        if (!updated) {
            return CommonResult.fail("修改角色'" + roleBo.getRoleName() + "'的状态失败，请联系管理员");
        }
        return CommonResult.success();
    }

    /**
     * 删除角色
     */
    @SaCheckPermission("system:role:remove")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public CommonResult<Void> remove(@PathVariable Long[] roleIds) {
        boolean deleted = roleService.deleteRoleByIds(roleIds);
        if (!deleted) {
            return CommonResult.fail("批量删除角色失败，请联系管理员");
        }
        return CommonResult.success();
    }

    /**
     * 获取角色选择框列表
     */
    @SaCheckPermission("system:role:query")
    @GetMapping("/optionselect")
    public CommonResult<List<SysRoleVo>> optionSelect() {
        return CommonResult.success(roleService.selectRoleAll());
    }

    /**
     * 查询已分配用户角色分页列表
     */
    @SaCheckPermission("system:role:list")
    @GetMapping("/authUser/allocatedList")
    public CommonResult<PageResult<SysUserVo>> allocatedList(SysUserBo userBo) {
        return CommonResult.success(userService.selectAllocatedPage(userBo));
    }

    /**
     * 查询未分配用户角色分页列表
     */
    @SaCheckPermission("system:role:list")
    @GetMapping("/authUser/unallocatedList")
    public CommonResult<PageResult<SysUserVo>> unallocatedList(SysUserBo userBo) {
        return CommonResult.success(userService.selectUnallocatedPage(userBo));
    }

    /**
     * 取消授权用户
     */
    @SaCheckPermission("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public CommonResult<Void> cancelAuthUser(@RequestBody SysUserRole userRole) {
        boolean deleted = userRoleService.deleteUserRoleInfo(userRole);
        if (!deleted) {
            return CommonResult.fail("取消授权用户角色失败，请联系管理员");
        }
        return CommonResult.success();
    }

    /**
     * 批量取消授权用户
     */
    @SaCheckPermission("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public CommonResult<Void> cancelAuthUserAll(Long roleId, Long[] userIds) {
        boolean deleted = userRoleService.deleteUserRoleInfos(roleId, userIds);
        if (!deleted) {
            return CommonResult.fail("批量取消授权用户角色失败，请联系管理员");
        }
        return CommonResult.success();
    }

    /**
     * 批量选择用户授权
     */
    @SaCheckPermission("system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public CommonResult<Void> selectAuthUserAll(Long roleId, Long[] userIds) {
        roleService.checkRoleDataScope(roleId);
        boolean inserted = userRoleService.insertAuthUsers(roleId, userIds);
        if (!inserted) {
            return CommonResult.fail("批量选择用户授权失败，请联系管理员");
        }
        return CommonResult.success();
    }

    /**
     * 获取对应角色部门树列表
     */
    @SaCheckPermission("system:role:query")
    @GetMapping(value = "/deptTree/{roleId}")
    public CommonResult<DeptTreeSelectVo> deptTree(@PathVariable("roleId") Long roleId) {
        DeptTreeSelectVo selectVo = new DeptTreeSelectVo();
        selectVo.setCheckedKeys(deptService.selectDeptListByRoleId(roleId));
        selectVo.setDepts(deptService.selectDeptTreeList(new SysDeptBo()));
        return CommonResult.success(selectVo);
    }
}
