package com.fdage.controller;

import com.fdage.aop.WebControllerLog;
import com.fdage.pojo.TbRole;
import com.fdage.pojo.TbUser;
import com.fdage.request.RequestBase;
import com.fdage.request.RequestRole;
import com.fdage.respon.ResponRole;
import com.fdage.service.IResourceService;
import com.fdage.service.IRoleService;
import com.fdage.service.IUserService;
import com.fdage.util.AjaxJson;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by Hb_zzZ on 2020/7/28.
 */
@Controller
@RequestMapping("/zhoushan/role")
@Slf4j
@Api(tags = "sys-角色管理模块")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IResourceService resourceService;

    @Autowired
    private IUserService userService;



    @PostMapping("save")
    @ResponseBody
    @WebControllerLog(description = "角色管理-新增/修改角色")
    @ApiOperation("新增/修改角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleName", value = "角色名称", dataType = "String"),
            @ApiImplicitParam(name = "resources", value = "资源id集合", dataType = "String"),
            @ApiImplicitParam(name = "id", value = "id", dataType = "String"),
            @ApiImplicitParam(name = "description", value = "角色描述", dataType = "String"),
            @ApiImplicitParam(name = "state", value = "状态,0：启用，1：禁用", dataType = "String"),
            @ApiImplicitParam(name = "roleKey", value = "角色key", dataType = "String")})
    public AjaxJson save(@RequestBody RequestRole param){

        if (StringUtils.isBlank(param.getRoleName())){
            log.error("角色名称不能为空");
            return AjaxJson.failure("角色名称不能为空");
        }

        if (param.getResources() == null){
            log.error("权限不能为空");
            return AjaxJson.failure("权限不能为空");
        }


        TbRole roleEntity = null;
        int n = 0;

        if (param.getId() == null) {
            roleEntity = new TbRole();
            BeanUtils.copyProperties(param, roleEntity);
            n = roleService.save(roleEntity);
        } else {
            roleEntity = roleService.findById(param.getId());
            if (roleEntity == null) {
                return AjaxJson.failure("该角色不存在");

            }
            BeanUtils.copyProperties(param, roleEntity);

            // 2021-8-16 检查该角色是否被用户使用
            if (roleEntity.getState() == 1){
                if (checkUseRole(roleEntity.getId())) {
                    return AjaxJson.failure("当前角色还有关联用户，请先处理用户角色");
                }
            }


            n = roleService.update(roleEntity);

            // 每次修改，删除角色资源表信息，重新添加
            roleService.deleteRoleResource(param.getId());
        }

        // 添加权限
        if (n >= 0){
            if (param.getResources() != null){
                for (long i : param.getResources()) {
                    roleService.saveRoleResource(roleEntity.getId(), i);
                }
                return AjaxJson.success();
            }
        }

        return AjaxJson.failure("新增角色失败");
    }


    private Boolean checkUseRole(Long id){
        List<String> list = roleService.findUserNameByRoleId(id);
        if(list != null && list.size() > 0){
            return true;
//            return AjaxJson.failure("当前角色还有关联用户，请先处理用户角色");
        }
        return false;
    }

    @PostMapping("list")
    @ResponseBody
    @WebControllerLog(description = "角色管理-获取角色列表")
    @ApiOperation("获取角色列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", dataType = "String"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量", dataType = "String")})
    public AjaxJson list(@RequestBody RequestBase bo){
        List<ResponRole> list = roleService.findRoleList(bo);
        PageInfo<ResponRole> pageInfo = new PageInfo<>(list);
        return AjaxJson.success(pageInfo);
    }

    @PostMapping("findUserListByRoleId")
    @ResponseBody
    @ApiOperation("获取角色关联的用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色id", dataType = "String")})
    public AjaxJson findUserListByRoleId(@RequestBody RequestRole bo){
        return AjaxJson.success(roleService.findUserListByRoleId(bo.getId()));
    }

    @PostMapping("updateState")
    @ResponseBody
    @ApiOperation("角色启用/停用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色id", dataType = "String"),
            @ApiImplicitParam(name = "state", value = "状态,0：启用，1：禁用", dataType = "String")})
    public AjaxJson updateState(@RequestBody RequestRole bo){
        if(bo.getId() == null || bo.getState() == null){
            return AjaxJson.failure("id或者状态不能为空");
        }

        List<String> list = roleService.findUserNameByRoleId(bo.getId());
        if(list != null && list.size() > 0){
            return AjaxJson.failure("当前角色还有关联用户，请先处理用户角色");
        }
        TbRole role = new TbRole();
        role.setId(bo.getId());
        role.setState(bo.getState());
        roleService.update(role);
        return AjaxJson.success();
    }

    @PostMapping("findRoleById")
    @ResponseBody
    @ApiOperation("根据id获取角色详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "角色id", dataType = "String")})
    public AjaxJson findRoleById(@RequestBody RequestRole bo){
        if(bo.getId() == null){
            return AjaxJson.failure("id不能为空");
        }
        ResponRole responRole = roleService.findRoleById(bo.getId());
        responRole.setResources(resourceService.getResourcesAllByRolePermission(bo.getId()));
        return AjaxJson.success(responRole);
    }
}
