package com.chushang.system.controller;

import com.chushang.common.core.web.AjaxResult;
import com.chushang.common.log.annotation.SysLog;
import com.chushang.common.log.enums.BusinessType;
import com.chushang.security.annotation.RequiresPermissions;
import com.chushang.security.utils.SecurityUtils;
import com.chushang.system.entity.bo.CancelUserRole;
import com.chushang.system.entity.bo.RoleUser;
import com.chushang.system.entity.dto.ListRoleDTO;
import com.chushang.system.entity.dto.ListUserDTO;
import com.chushang.system.entity.po.SysRole;
import com.chushang.system.service.ISysRoleService;
import com.chushang.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author by zhaowenyuan create 2022/8/22 11:04
 */
@RestController
@RequestMapping(value = "/role")
public class RoleController {

    @Autowired
    ISysRoleService roleService;
    @Autowired
    ISysUserService userService;

    @RequiresPermissions("system:role:list")
    @GetMapping("/list")
    public AjaxResult list(ListRoleDTO listRole)
    {
        return roleService.selectRoleList(listRole);
    }

    /**
     * 根据角色编号获取详细信息
     */
    @RequiresPermissions("system:role:query")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId)
    {
        roleService.checkRoleDataScope(new SysRole(roleId));

        return AjaxResult.success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @RequiresPermissions("system:role:add")
    @SysLog(value = "角色",businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysRole role)
    {
        if (roleService.checkRoleNameUnique(role))
        {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (roleService.checkRoleKeyUnique(role))
        {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(SecurityUtils.getUsername());

        roleService.saveRole(role);

        return AjaxResult.success();

    }

    /**
     * 修改保存角色
     */
    @RequiresPermissions("system:role:edit")
    @SysLog(value = "角色",businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysRole role)
    {
        // 1 为超管
        if (1 == role.getRoleId()){
            return AjaxResult.success();
        }
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(new SysRole(role.getRoleId()));
        if (roleService.checkRoleNameUnique(role))
        {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (roleService.checkRoleKeyUnique(role))
        {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());
        //
        roleService.updateRole(role);

        return AjaxResult.success();
    }

    /**
     * 修改保存数据权限
     */
    @RequiresPermissions("system:role:edit")
    @SysLog(value = "角色权限",businessType = BusinessType.GRANT)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(new SysRole(role.getRoleId()));

        roleService.authDataScope(role);

        return AjaxResult.success();
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("system:role:edit")
    @SysLog(value = "角色状态",businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysRole role)
    {
        if (2 == role.getRoleId()){
            return AjaxResult.success();
        }
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(new SysRole(role.getRoleId()));
        role.setUpdateBy(SecurityUtils.getUsername());
        roleService.updateRoleStatus(role);
        return AjaxResult.success();
    }

    /**
     * 删除角色
     */
    @RequiresPermissions("system:role:remove")
    @SysLog(value = "角色",businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public AjaxResult remove(@PathVariable Long[] roleIds)
    {
        roleService.deleteRoleByIds(roleIds);

        return AjaxResult.success();
    }

    /**
     * 获取角色选择框列表
     */
    @RequiresPermissions("system:role:query")
    @GetMapping("/option/select")
    public AjaxResult optionSelect()
    {
        return AjaxResult.success(roleService.selectRoleAll(new SysRole()));
    }
    /**
     * 查询已分配用户角色列表
     * 可以根据用户名称查询
     */
    @RequiresPermissions("system:role:list")
    @GetMapping("/authUser/allocatedList")
    public AjaxResult allocatedList(@Valid ListUserDTO listUser)
    {
        return userService.selectAllocatedList(listUser);
    }

    /**
     * 查询未分配用户角色列表
     */
    @RequiresPermissions("system:role:list")
    @GetMapping("/authUser/unallocatedList")
    public AjaxResult unallocatedList(@Valid ListUserDTO listUser)
    {
        return userService.selectUnallocatedList(listUser);
    }

    /**
     * 取消授权用户
     */
    @RequiresPermissions("system:role:edit")
    @SysLog(value = "取消授权用户", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public AjaxResult cancelAuthUser(@RequestBody @Valid CancelUserRole cancelUserRole)
    {
        roleService.deleteAuthUser(cancelUserRole);

        return AjaxResult.success();
    }

    /**
     * 批量选择用户授权
     */
    @RequiresPermissions("system:role:edit")
    @SysLog(value = "用户授权", businessType = BusinessType.GRANT)
    @PutMapping("/authUser")
    public AjaxResult selectAuthUserAll(@RequestBody @Valid RoleUser roleUser)
    {
        Long roleId = roleUser.getRoleId();
        Long[] userIds = roleUser.getUserIds();
        // 判断当切登录用户有没有 此角色的权限
        roleService.checkRoleDataScope(new SysRole(roleId));

        roleService.insertAuthUsers(roleId, userIds);

        return AjaxResult.success();
    }

    /**
     * todo 角色导出
     * @return
     */
    @SysLog(value = "角色", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @RequiresPermissions("system:role:export")
    public AjaxResult exportRole(){
        return AjaxResult.error("暂未开放");
    }

    /**
     * todo 角色导入
     */
    @GetMapping("/import")
    @RequiresPermissions("system:role:import")
    @SysLog(value = "角色", businessType = BusinessType.IMPORT)
    public AjaxResult importRole(){
        return AjaxResult.error("暂未开放");
    }

}
