package com.vctgo.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vctgo.common.core.constant.CacheConstants;
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.mybatisplus.aop.TemporaryIgnoreTables;
import com.vctgo.common.redis.service.RedisService;
import com.vctgo.common.security.annotation.Logical;
import com.vctgo.common.security.annotation.RequiresPermissions;
import com.vctgo.common.security.utils.SecurityUtils;
import com.vctgo.system.api.domain.SysDept;
import com.vctgo.system.api.domain.SysRole;
import com.vctgo.system.api.domain.SysUser;
import com.vctgo.system.api.model.LoginUser;
import com.vctgo.system.domain.SysUserRole;
import com.vctgo.system.service.ISysDeptService;
import com.vctgo.system.service.ISysRoleService;
import com.vctgo.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * 角色信息
 *
 * @author vctgo
 */
@Api(tags = "角色信息")
@RestController
@RequestMapping("/role")
public class SysRoleController extends BaseController {

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private RedisService redisService;

    /**
     * 分页查询角色列表
     *
     * @param role
     * @return
     */
    @ApiOperation(value = "分页查询角色列表")
    @RequiresPermissions("system:role:page")
    @GetMapping("/page")
    public AjaxResult list(SysRole role) {
        return AjaxResult.success(roleService.selectRolePage(role));
    }

    /**
     * 根据租户类型查询角色列表
     *
     * @param role
     * @return
     */
    @ApiOperation(value = "根据租户类型查询角色列表")
    @RequiresPermissions(value = {"system:role:list", "system:account:add"}, logical = Logical.OR)
    @GetMapping("/list/tenant")
    public AjaxResult listByTanantType(SysRole role) {
        return AjaxResult.success(roleService.selectRoleListByTenantType(role));
    }

    /**
     * 导出角色管理
     *
     * @param response
     * @param role
     */
    @ApiOperation(value = "导出角色管理")
    @RequiresPermissions("system:role:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysRole role) {
        List<SysRole> list = roleService.selectRoleList(role);
        ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
        util.exportExcel(response, list, "角色数据");
    }

    /**
     * 根据角色编号获取详细信息
     */
    @TemporaryIgnoreTables
    @ApiOperation(value = "根据角色编号获取详细信息")
    @RequiresPermissions("system:role:query:id")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId) {
        if("1".equals(SecurityUtils.getTenantType().toString())){
            SecurityUtils.setTemporaryIgnoreTables(Arrays.asList("d", "r", "ur", "u", "uu", "sur", "sys_role",
                    "sys_user_role", "sys_user", "sys_dept"));
        }
        roleService.checkRoleDataScope(roleId);
        return success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @Transactional
    @RequiresPermissions("system:role:add")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysRole role) {
        if (1 == SecurityUtils.getTenantType()
                && Objects.nonNull(role.getTenantId())
                && SecurityUtils.getTenantId().longValue() != role.getTenantId().longValue()) {
            SecurityUtils.setTenantId(role.getTenantId().toString());
        }
        if (!roleService.checkRoleNameUnique(role)) {
            return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (!roleService.checkRoleKeyUnique(role)) {
            return error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(SecurityUtils.getUsername());
        role.setCreateById(SecurityUtils.getUserId());
        return toAjax(roleService.insertRole(role));
    }

    /**
     * 修改保存角色
     */
    @Transactional(rollbackFor = Exception.class)
    @RequiresPermissions("system:role:edit")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysRole role) {
        // 获取当前角色基本信息
        SecurityUtils.setTemporaryIgnoreTables(Collections.singletonList("sys_role"));
        SysRole sysRole = roleService.selectRoleById(role.getRoleId());
        SecurityUtils.removeTemporaryIgnoreTables(Collections.singletonList("sys_role"));
        if (1 == SecurityUtils.getTenantType()
                && Objects.nonNull(role.getTenantId())) {
            SecurityUtils.setTenantId(role.getTenantId().toString());
            if (role.getTenantId().longValue() != sysRole.getTenantId().longValue()) {
                SecurityUtils.setTemporaryIgnoreTables(Arrays.asList("sys_role", "sys_role_menu", "sys_role_dept"));
                roleService.deleteRoleById(role.getRoleId());
                SecurityUtils.removeTemporaryIgnoreTables(Arrays.asList("sys_role", "sys_role_menu", "sys_role_dept"));
                role.setRoleId(null);
                return add(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());
        role.setUpdateById(SecurityUtils.getUserId());
        int result = roleService.updateRole(role);

        // 获取使用该角色的用户id
        List<Long> userIdList = roleService.selectUserIdListByRoleId(role.getRoleId());

        // 凡是涉及到该角色的人员都推出登录
        List<String> keyList = new ArrayList<>();
        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys) {
            LoginUser onlineUser = redisService.getCacheObject(key);
            if (Objects.nonNull(onlineUser)
                    && Objects.nonNull(onlineUser.getSysUser())
                    && userIdList.contains(onlineUser.getUserid())) {
                keyList.add(key);
            }
        }
        redisService.deleteObject(keyList);
        return toAjax(result);
    }

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

    /**
     * 状态修改
     */
    @Transactional
    @RequiresPermissions("system:role:change_status")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysRole 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(SysUser user) {
        IPage<SysUser> list = userService.selectAllocatedList(user);
        return AjaxResult.success(list);
    }

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

    /**
     * 取消授权用户
     */
    @Transactional
    @RequiresPermissions("system:role:cancel")
    @PutMapping("/authUser/cancel")
    public AjaxResult cancelAuthUser(@RequestBody SysUserRole userRole) {
        SecurityUtils.setTenantId((1 == SecurityUtils.getTenantType()) ? userRole.getTenantId().toString() : SecurityUtils.getTenantId().toString());
        int result = roleService.deleteAuthUser(userRole);

        // 凡是涉及到该角色的人员都推出登录
        List<String> keyList = new ArrayList<>();
        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys) {
            LoginUser onlineUser = redisService.getCacheObject(key);
            if (Objects.nonNull(onlineUser)
                    && Objects.nonNull(onlineUser.getSysUser())
                    && onlineUser.getUserid().longValue() == userRole.getUserId()) {
                keyList.add(key);
            }
        }
        redisService.deleteObject(keyList);
        return toAjax(result);
    }

    /**
     * 批量取消授权用户
     */
    @Transactional
    @RequiresPermissions("system:role:batch_cancel")
    @PutMapping("/authUser/cancelAll")
    public AjaxResult cancelAuthUserAll(Long roleId, Long tenantId, Long[] userIds) {
        SecurityUtils.setTenantId((1 == SecurityUtils.getTenantType()) ? tenantId.toString() : SecurityUtils.getTenantId().toString());
        int result = roleService.deleteAuthUsersByTenantId(roleId, userIds);
        // 凡是涉及到该角色的人员都推出登录
        List<Long> userIdList = new ArrayList<>(Arrays.asList(userIds));
        List<String> keyList = new ArrayList<>();
        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys) {
            LoginUser onlineUser = redisService.getCacheObject(key);
            if (Objects.nonNull(onlineUser)
                    && Objects.nonNull(onlineUser.getSysUser())
                    && userIdList.contains(onlineUser.getUserid())) {
                keyList.add(key);
            }
        }
        redisService.deleteObject(keyList);
        return toAjax(result);
    }

    /**
     * 批量选择用户授权
     */
    @Transactional
    @RequiresPermissions("system:auth_user:edit")
    @PutMapping("/authUser/selectAll")
    public AjaxResult selectAuthUserAll(Long roleId, Long tenantId, Long[] userIds) {
        SecurityUtils.setTenantId((1 == SecurityUtils.getTenantType()) ? tenantId.toString() : SecurityUtils.getTenantId().toString());
        roleService.checkRoleDataScope(roleId);
        int result = roleService.insertAuthUsersByTenantId(roleId, userIds);

        // 凡是涉及到该角色的人员都推出登录
        List<Long> userIdList = new ArrayList<>(Arrays.asList(userIds));
        List<String> keyList = new ArrayList<>();
        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys) {
            LoginUser onlineUser = redisService.getCacheObject(key);
            if (Objects.nonNull(onlineUser)
                    && Objects.nonNull(onlineUser.getSysUser())
                    && userIdList.contains(onlineUser.getUserid())) {
                keyList.add(key);
            }
        }
        redisService.deleteObject(keyList);
        return toAjax(result);
    }

    /**
     * 获取对应角色部门树列表
     */
    @RequiresPermissions("system:role_tree:query")
    @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 SysDept()));
        return ajax;
    }
}
