package com.sy.coinage.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sy.coinage.core.annotation.CurrentUser;
import com.sy.coinage.core.aop.annotation.Operation;
import com.sy.coinage.core.aop.annotation.Permission;
import com.sy.coinage.core.constants.Constants;
import com.sy.coinage.core.controller.BaseController;
import com.sy.coinage.core.exception.RetException;
import com.sy.coinage.core.interceptor.Create;
import com.sy.coinage.core.interceptor.Update;
import com.sy.coinage.core.req.IdReq;
import com.sy.coinage.core.vo.CacheUserVO;
import com.sy.coinage.core.vo.OptVO;
import com.sy.coinage.sys.model.Role;
import com.sy.coinage.sys.req.AdminCopyRoleReq;
import com.sy.coinage.sys.req.AdminRoleReq;
import com.sy.coinage.sys.req.DeleteUserReq;
import com.sy.coinage.sys.req.RoleListReq;
import com.sy.coinage.sys.req.RoleMenuAddReq;
import com.sy.coinage.sys.req.RoleReq;
import com.sy.coinage.sys.req.TenantIdReq;
import com.sy.coinage.sys.service.IRoleService;
import com.sy.coinage.sys.service.IUserRoleService;
import com.sy.coinage.sys.vo.PermissionVO;
import com.sy.coinage.sys.vo.RoleVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
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.RestController;

@Api(value = "角色接口", tags = "013_角色")
@RestController
@RequestMapping(value = "/role")
public class RoleController extends BaseController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IUserRoleService iUserRoleService;

    @ApiOperation(value = "角色分页列表")
    @PostMapping("/page")
    public IPage<Role> page(@RequestBody RoleListReq req, @CurrentUser CacheUserVO user) {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getTenantId, user.getTenantId());
        queryWrapper.orderByAsc(Role::getSorted);
        Page<Role> page = new Page<>(req.getPage(), req.getRows());
        IPage<Role> data = this.roleService.page(page, queryWrapper);
        return data;
    }

    @ApiOperation(value = "角色详情")
    @PostMapping("/get")
    public RoleVO get(@RequestBody @Valid IdReq req) {
        RoleVO data = null;
        Role model = this.roleService.getById(req.getId());
        data = new RoleVO();
        BeanUtils.copyProperties(model, data);
        return data;
    }

    @ApiOperation(value = "新增角色")
    @Operation(value = "新增角色")
    @Permission("role:add")
    @PostMapping("/add")
    public Object add(@RequestBody @Validated({Create.class}) RoleReq req,
                      @CurrentUser CacheUserVO user) {
        // 验证角色名称是否重复
        this.roleService.validName(null, req.getName(), user.getTenantId());
        Role model = new Role();
        BeanUtils.copyProperties(req, model);
        model.setTenantId(user.getTenantId());
        model.setCreateBy(user.getRealName());
        model.setStatus(Constants.STATUS_USABLE);
        this.roleService.save(model);
        return "";
    }

    @ApiOperation(value = "修改角色")
    @Operation(value = "修改角色")
    @Permission("role:update")
    @PostMapping("/update")
    public Object update(@RequestBody @Validated({Update.class}) RoleReq req,
                         @CurrentUser CacheUserVO user) {
        Role model = this.roleService.getById(req.getId());
        // 验证是否相同租户
        this.validTenant(user, model.getTenantId());
        // 验证角色名称是否重复
        this.roleService.validName(req.getId(), req.getName(), model.getTenantId());
        BeanUtils.copyProperties(req, model);
        this.roleService.updateById(model);
        return "";
    }

    @ApiOperation(value = "修改角色状态")
    @Operation(value = "修改角色状态")
    @Permission("role:update")
    @PostMapping("/status")
    public Integer status(@RequestBody @Valid IdReq req, @CurrentUser CacheUserVO user) {
        Role model = this.roleService.getById(req.getId());
        // 验证是否相同租户
        this.validTenant(user, model.getTenantId());
        if (null != model.getStatus()
                && model.getStatus().intValue() == Constants.STATUS_FORBIDDEN) {
            model.setStatus(Constants.STATUS_USABLE);
        } else {
            model.setStatus(Constants.STATUS_FORBIDDEN);
        }
        this.roleService.updateById(model);
        return model.getStatus();
    }

    @ApiOperation(value = "角色选项")
    @GetMapping("/opt")
    public List<OptVO> listOpt(@CurrentUser CacheUserVO user) {
        List<OptVO> data = this.roleService.opt(user.getTenantId());
        return data;
    }

    @ApiOperation(value = "角色包含所有userId")
    @PostMapping("/user/opt")
    public List<OptVO> userOpt(@RequestBody @Valid IdReq req) {
        List<OptVO> data = this.iUserRoleService.userOpt(req.getId());
        return data;
    }

    @ApiOperation(value = "角色已配置的菜单id")
    @PostMapping("/menuIds")
    public List<Integer> menuIds(@RequestBody @Valid IdReq req) {
        List<Integer> data = this.roleService.menuIds(req.getId());
        return data;
    }

    @ApiOperation(value = "角色配置菜单")
    @Operation(value = "角色配置菜单")
    @PostMapping("/addMenu")
    public Object addMenu(@RequestBody @Valid RoleMenuAddReq req, @CurrentUser CacheUserVO user) {
        Role model = this.roleService.getById(req.getRoleId());
        // 验证是否相同租户
        this.validTenant(user, model.getTenantId());
        this.roleService.addMenu(req);
        return "";
    }

    @ApiOperation(value = "获取用户按钮操作权限")
    @PostMapping("/permission")
    public Object permission(@RequestBody @Valid IdReq req) {
        List<PermissionVO> data = this.roleService.permission(req.getId());
        return data;
    }

    @ApiOperation(value = "删除角色中的用户")
    @Permission("role:delete")
    @PostMapping("/deleteUser")
    public Object deleteUser(@RequestBody @Valid DeleteUserReq req, @CurrentUser CacheUserVO user) {
        Role model = this.roleService.getById(req.getRoleId());
        // 验证是否相同租户
        this.validTenant(user, model.getTenantId());
        if (user.getId().intValue() == req.getUserId().intValue()) {
            throw new RetException("不能删除当前用户");
        }
        this.roleService.deleteUser(req.getUserId(), req.getRoleId());
        return "";
    }

    // ========================租户管理员========================
    @ApiOperation(value = "租户管理员-角色分页列表")
    @PostMapping("/admin/page")
    public IPage<Role> adminPage(@RequestBody RoleListReq req) {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq((req.getTenantId() != null && req.getTenantId() > 0), Role::getTenantId,
                req.getTenantId());
        queryWrapper.orderByAsc(Role::getSorted);
        Page<Role> page = new Page<>(req.getPage(), req.getRows());
        IPage<Role> data = this.roleService.page(page, queryWrapper);
        return data;
    }

    @ApiOperation(value = "租户管理员-新增角色")
    @Operation(value = "租户管理员-新增角色")
    @PostMapping("/admin/add")
    public Object adminAdd(@RequestBody @Validated({Create.class}) AdminRoleReq req,
                           @CurrentUser CacheUserVO user) {
        // 验证是否租户管理员
        this.validAdmin(user);
        this.roleService.validName(null, req.getName(), req.getTenantId());
        Role model = new Role();
        BeanUtils.copyProperties(req, model);
        model.setCreateBy(user.getRealName());
        model.setStatus(Constants.STATUS_USABLE);
        this.roleService.save(model);
        return "";
    }

    @ApiOperation(value = "租户管理员-获取角色选项")
    @PostMapping("/admin/opt")
    public List<OptVO> adminOpt(@RequestBody @Valid TenantIdReq req) {
        List<OptVO> data = this.roleService.opt(req.getTenantId());
        return data;
    }

    @ApiOperation(value = "租户管理员-复制角色")
    @Operation(value = "租户管理员-复制角色")
    @PostMapping("/admin/copy")
    public Object adminCopy(@RequestBody @Validated({Create.class}) AdminCopyRoleReq req,
                            @CurrentUser CacheUserVO user) {
        // 验证是否租户管理员
        this.validAdmin(user);
        this.roleService.validName(null, req.getName(), req.getTenantId());
        this.roleService.copy(req, user);
        return "";
    }

}
