package com.vctgo.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vctgo.common.core.utils.poi.ExcelUtil;
import com.vctgo.common.core.web.controller.BaseController;
import com.vctgo.common.core.web.domain.AjaxResult;
import com.vctgo.common.log.annotation.Log;
import com.vctgo.common.log.enums.BusinessType;
import com.vctgo.common.security.annotation.RequiresPermissions;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.domain.SysPlatformDept;
import com.vctgo.system.api.domain.SysPlatformRole;
import com.vctgo.system.api.domain.SysPlatformUser;
import com.vctgo.system.domain.SysPlatformUserRole;
import com.vctgo.system.service.ISysPlatformDeptService;
import com.vctgo.system.service.ISysPlatformRoleService;
import com.vctgo.system.service.ISysPlatformUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 角色信息
 *
 * @author vctgo
 */
@RestController
@RequestMapping("/plat/role")
public class SysPlatformRoleController extends BaseController
{
    @Autowired
    private ISysPlatformRoleService roleService;

    @Autowired
    private ISysPlatformUserService userService;

    @Autowired
    private ISysPlatformDeptService deptService;

    @RequiresPermissions("system:role:list")
    @GetMapping("/list")
    public AjaxResult list(SysPlatformRole role)
    {
        IPage<SysPlatformRole> list = roleService.selectRolePage(role);
        return AjaxResult.success(list);
    }

    @RequiresPermissions("system:role:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysPlatformRole role)
    {
        List<SysPlatformRole> list = roleService.selectRoleList(role);
        ExcelUtil<SysPlatformRole> util = new ExcelUtil<SysPlatformRole>(SysPlatformRole.class);
        util.exportExcel(response, list, "角色数据");
    }

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

    /**
     * 新增角色
     */
    @RequiresPermissions("system:role:add")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysPlatformRole role)
    {
        if (!roleService.checkRoleNameUnique(role))
        {
            return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (!roleService.checkRoleKeyUnique(role))
        {
            return error("新增角色'" + role.getRoleName() + "'失败，权限字符已存在");
        }
        role.setCreateBy(SecurityUtils.getUsername());
        return toAjax(roleService.insertRole(role));

    }

    /**
     * 修改保存角色
     */
    @RequiresPermissions("system:role:edit")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysPlatformRole role)
    {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        if (!roleService.checkRoleNameUnique(role))
        {
            return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (!roleService.checkRoleKeyUnique(role))
        {
            return error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRole(role));
    }

    /**
     * 修改保存数据权限
     */
    @RequiresPermissions("system:data_scope:edit")
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysPlatformRole role)
    {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        return toAjax(roleService.authDataScope(role));
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("system:role:change_status")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysPlatformRole role)
    {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRoleStatus(role));
    }

    /**
     * 删除角色
     */
    @RequiresPermissions("system:role:remove")
    @DeleteMapping("/{roleIds}")
    public AjaxResult remove(@PathVariable Long[] roleIds)
    {
        return toAjax(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 获取角色选择框列表
     */
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {
        return success(roleService.selectRoleAll());
    }
    /**
     * 查询已分配用户角色列表
     */
    @RequiresPermissions("system:allocated_role:list")
    @GetMapping("/authUser/allocatedList")
    public AjaxResult allocatedList(SysPlatformUser user)
    {
        IPage<SysPlatformUser> list = userService.selectAllocatedList(user);
        return AjaxResult.success(list);
    }

    /**
     * 查询未分配用户角色列表
     */
    @RequiresPermissions("system:unallocated_role:list")
    @GetMapping("/authUser/unallocatedList")
    public AjaxResult unallocatedList(SysPlatformUser user)
    {
        IPage<SysPlatformUser> list = userService.selectUnallocatedList(user);
        return AjaxResult.success(list);
    }

    /**
     * 取消授权用户
     */
    @RequiresPermissions("system:role:cancel")
    @PutMapping("/authUser/cancel")
    public AjaxResult cancelAuthUser(@RequestBody SysPlatformUserRole userRole)
    {
        return toAjax(roleService.deleteAuthUser(userRole));
    }

    /**
     * 批量取消授权用户
     */
    @RequiresPermissions("system:role:batch_cancel")
    @PutMapping("/authUser/cancelAll")
    public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds)
    {
        return toAjax(roleService.deleteAuthUsers(roleId, userIds));
    }

    /**
     * 批量选择用户授权
     */
    @RequiresPermissions("system:auth_user:edit")
    @PutMapping("/authUser/selectAll")
    public AjaxResult selectAuthUserAll(Long roleId, Long[] userIds)
    {
        roleService.checkRoleDataScope(roleId);
        return toAjax(roleService.insertAuthUsers(roleId, userIds));
    }

    /**
     * 获取对应角色部门树列表
     */
    @RequiresPermissions("system:role:query:deptTree")
    @GetMapping(value = "/deptTree/{roleId}")
    public AjaxResult deptTree(@PathVariable("roleId") Long roleId)
    {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.selectDeptTreeList(new SysPlatformDept()));
        return ajax;
    }
}
