package com.user.service.web.controller;


import com.base.orbit.constant.UserConstants;
import com.base.orbit.domain.AjaxResult;
import com.base.orbit.domain.enity.SysRole;
import com.base.orbit.page.TableDataInfo;
import com.user.service.token.LoginUser;
import com.user.service.token.TokenService;
import com.base.orbit.utils.DateUtils;
import com.base.orbit.utils.StringUtils;
import com.user.service.service.ISysRoleService;
import com.user.service.service.ISysUserService;
import com.user.service.service.impl.SysPermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

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

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysUserService userService;

    @Resource
    private TokenService tokenService;

    @Resource
    private SysPermissionService permissionService;

    /**
     * 新增角色
     */
    @PostMapping("/add")
    @ApiOperation(value = "新增角色", httpMethod = "POST", notes = "新增角色")
    public AjaxResult add(@Validated @RequestBody SysRole role) {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(getUsername());
        role.setCreateTime(DateUtils.getNowDate());
        role.setDelFlag("0");
        return toAjax(roleService.insertRole(role));
    }

    /**
     * 查询角色
     *
     * @param role
     * @return
     */
    @GetMapping("/list")
    @ApiOperation(value = "查询角色", httpMethod = "GET", notes = "查询角色")
    public TableDataInfo list(SysRole role) {
        startPage();
        List<SysRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/{roleIds}")
    @ApiOperation(value = "刪除角色", httpMethod = "DELETE", notes = "刪除角色")
    public AjaxResult remove(@PathVariable Long[] roleIds) {
        return toAjax(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * 修改保存角色
     */
    @PostMapping("/edit")
    @ApiOperation(value = "修改保存角色", httpMethod = "POST", notes = "修改保存角色")
    public AjaxResult edit(@Validated @RequestBody SysRole role) {
        roleService.checkRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(getUsername());

        if (roleService.updateRole(role) > 0) {
            // 更新缓存用户权限
            LoginUser loginUser = getLoginUser();
            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) {
                //  将set集合转为List
                Set<String> permissions = permissionService.getMenuPermission(loginUser.getUser());
                List<String> list = new ArrayList<>(permissions);
                loginUser.setPermissions(list);
                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
                tokenService.setLoginUser(loginUser);
            }
            return AjaxResult.success();
        }
        return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }

}
