package com.storlead.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.common.result.Result;
import com.storlead.system.pojo.entity.RoleEntity;
import com.storlead.system.pojo.entity.RoleMenuEntity;
import com.storlead.system.pojo.entity.UserRoleEntity;
import com.storlead.system.pojo.vo.RoleMenuDTO;
import com.storlead.system.service.DeptRoleService;
import com.storlead.system.service.IRoleMenuService;
import com.storlead.system.service.IRoleService;
import com.storlead.system.service.IUserRoleService;
import com.storlead.user.pojo.dto.RoleParam;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import org.springframework.util.CollectionUtils;
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;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: sp-cloud
 * @description:
 * @author: chenkq
 * @create: 2022-05-20 10:11
 */
@Api(tags = "平台中心 - 系统: 角色管理")
@RestController
@RequestMapping("/sys/role/manage")
public class RoleApiController {
    @Resource
    private IRoleService roleService;

    @Resource
    private IUserService userService;

    @Resource
    private IUserRoleService userRoleService;

    @Resource
    private IRoleMenuService roleMenuService;

    @Resource
    private DeptRoleService deptRoleService;
//    @Resource
//    private SysRoleResourceEngineService roleResourceEngineService;


    @ApiOperation("角色分页")
    @PostMapping("/pagelist")
    public Result<?> list(@RequestBody RoleParam param) {
        IPage<RoleEntity> page = new Page<>(param.getPageIndex(),param.getPageSize());
        LambdaQueryWrapper<RoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(param.getName())) {
            queryWrapper.likeRight(RoleEntity::getName, param.getName());
        }
        if (param.getAppId() != null) {
            queryWrapper.eq(RoleEntity::getAppId, param.getAppId());
        }
        IPage<RoleEntity> roles = roleService.page(page,queryWrapper);
        if (!CollectionUtils.isEmpty(roles.getRecords())) {
            setRoleUserNname(roles.getRecords());
        }
        return Result.result(roles);
    }

    @ApiOperation("保存角色")
    @PostMapping("/save")
    public Result create(@RequestBody RoleParam param) {

        RoleEntity info = new RoleEntity();
        BeanUtils.copyProperties(param, info);

        if (Objects.isNull(info) || StrUtil.isBlank(info.getName())) {
            return Result.error("参数错误");
        }
        LambdaQueryWrapper<RoleEntity> nameWrapper = new LambdaQueryWrapper<RoleEntity>().eq(RoleEntity::getName, info.getName());
        if (info.getAppId() != null) {
            nameWrapper.eq(RoleEntity::getAppId, info.getAppId());
        }
        if (Objects.isNull(info.getId())) {
            Integer exit = roleService.count(nameWrapper);
            if (exit > 0) {
                return Result.error("角色'"+ info.getName() +"'已存在!");
            }
        } else {
            RoleEntity oldAccount = roleService.getOne(nameWrapper);
            if (Objects.nonNull(oldAccount)) {
                if (!oldAccount.getId().equals(info.getId())) {
                    return Result.error("角色'"+ info.getName() +"'已存在,无法修改!");
                }
            }
        }

        Boolean b = roleService.saveOrUpdate(info);
        if (b) {
            roleMenuService.updateRoleMenu(info.getId(),param.getMenus(),param.getIsApp());
            deptRoleService.updateDeptRole(info.getId(),param.getDepts());
        }
        return Result.ok();
    }
    @ApiOperation("启用禁用员工")
    @PostMapping("enable")
    public Result setEnable(Long id,Boolean enable) {
        LambdaUpdateWrapper<RoleEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(RoleEntity::getEnabled,enable);
        updateWrapper.eq(RoleEntity::getId,id);
        roleService.update(updateWrapper);
        return Result.ok();
    }

    @ApiOperation("删除角色")
    @PostMapping("/delete")
    public Result<?> remove(Long [] ids) {
        if (Objects.isNull(ids) || ids.length == 0) {
            return Result.error("参数错误");
        }
        Boolean result = roleService.removeByIds(Arrays.asList(ids));
        if(result) {
            userRoleService.remove(new LambdaQueryWrapper<UserRoleEntity>().in(UserRoleEntity::getRoleId, Arrays.asList(ids)));
        }
        return Result.ok();
    }

    @ApiOperation("关联角色用户")
    @PostMapping("/bindRoleUser")
    public Result<?> bindRoleUser(Long rid,Long [] uids) {
        if (Objects.isNull(rid)) {
            return Result.error("参数错误");
        }
        LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<UserRoleEntity>().eq(UserRoleEntity::getRoleId,rid);
        userRoleService.remove(lambdaQueryWrapper);
        if (Objects.nonNull(uids)) {
            List<UserRoleEntity> urs = new ArrayList<>();
            for (Long uid : Arrays.asList(uids)) {
                UserRoleEntity userRole = new UserRoleEntity();
                userRole.setUserId(uid);
                userRole.setRoleId(rid);
                urs.add(userRole);
                if (Long.valueOf(1).equals(rid)) {
                    UserRoleEntity adminRole = new UserRoleEntity();
                    adminRole.setUserId(1L);
                    adminRole.setRoleId(rid);
                    urs.add(adminRole);
                }
            }
            if (!CollectionUtils.isEmpty(urs)) {
                userRoleService.saveBatch(urs);
            }
        }
        return Result.ok();
    }


    @ApiOperation("关联角色菜单")
    @PostMapping("/bind_role_menu")
    public Result<?> bindRoleMenu(RoleMenuDTO dto) {
        if (Objects.isNull(dto.getRoleId())) {
            return Result.error("参数错误");
        }
        if (Objects.isNull(dto.getIsApp())) {
            dto.setIsApp(0);
        }
        LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<RoleMenuEntity>().eq(RoleMenuEntity::getRoleId,dto.getRoleId()).eq(RoleMenuEntity::getIsApp,dto.getIsApp());
        roleMenuService.remove(lambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(dto.getMenuls())) {
            List<RoleMenuEntity> urs = new ArrayList<>();
            for (Long menuId : dto.getMenuls()) {
                RoleMenuEntity roleMenu = new RoleMenuEntity();
                roleMenu.setRoleId(dto.getRoleId());
                roleMenu.setMenuId(menuId);
                roleMenu.setIsApp(dto.getIsApp());
                urs.add(roleMenu);
            }
            if (!CollectionUtils.isEmpty(urs)) {
                roleMenuService.saveBatch(urs);
            }
        }
        return Result.ok();
    }

    @ApiOperation("设置用户角色")
    @PostMapping("/setUserRole")
    public Result<?> bindUserRole(Long uid,Long [] rids) {
        if (Objects.isNull(rids) || Objects.isNull(uid)) {
            return Result.error("参数错误");
        }
        LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<UserRoleEntity>().eq(UserRoleEntity::getUserId,uid);
        userRoleService.remove(lambdaQueryWrapper);

        List<UserRoleEntity> urs = new ArrayList<>();
        Arrays.asList(rids).forEach(rid -> {
            UserRoleEntity userRole = new UserRoleEntity();
            userRole.setUserId(uid);
            userRole.setRoleId(rid);
            urs.add(userRole);
        });

        if (!CollectionUtils.isEmpty(urs)) {
            userRoleService.saveBatch(urs);
        }
        return Result.ok();
    }


    @ApiOperation("绑定部门")
    @PostMapping("/bindDeptRole")
    public Result<?> bindDeptRole(@RequestBody RoleParam param) {
        deptRoleService.updateDeptRole(param.getId(),param.getDepts());
        return Result.ok();
    }


    @ApiOperation("关联角色菜单")
    @PostMapping("/bindMenuRole")
    public Result<?> bindMenuRole(Long [] rids,Long [] menus) {
        if (Objects.isNull(rids)) {
            return Result.error("参数错误");
        }
        LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<RoleMenuEntity>().in(RoleMenuEntity::getRoleId,Arrays.asList(rids));
        roleMenuService.remove(lambdaQueryWrapper);
        if (Objects.nonNull(rids) && rids.length > 0) {
            List<RoleMenuEntity> rms = new ArrayList<>();
            for (Long rid : Arrays.asList(rids)) {
                Arrays.asList(menus).forEach(m -> {
                    RoleMenuEntity roleMenu = new RoleMenuEntity();
                    roleMenu.setRoleId(rid);
                    roleMenu.setMenuId(m);
                    rms.add(roleMenu);
                });
            }
            if (!CollectionUtils.isEmpty(rms)) {
               roleMenuService.saveBatch(rms);
            }
        }
        return Result.ok();
    }

    @ApiOperation("根据角色查询菜单id")
    @PostMapping("/getRoleMenuId")
    public Result<?> getRoleMenuId(Long roleId) {
        return Result.result(roleService.getMenuIdsByRoleId(roleId,0));
    }

    @ApiOperation("根据角色查询菜单id")
    @PostMapping("/getH5RoleMenuId")
    public Result<?> getH5RoleMenuId(Long roleId) {
        return Result.result(roleService.getMenuIdsByRoleId(roleId,1));
    }

    /**
     * 根据角色id查询部门id*
     * @param roleId
     */
    @ApiOperation("根据角色查询组织id")
    @PostMapping("/getRoleDeptId")
    public Result<?> getRoleDeptId(Long roleId) {
        return Result.result(roleService.getdeptIdsByRoleId(roleId));
    }

    private void setRoleUserNname(List<RoleEntity> roles){
        if (!CollectionUtils.isEmpty(roles)) {
            List<Long> roleIds = new ArrayList<>();
            roles.forEach(user -> {
                roleIds.add(user.getId());
            });
            Map<Long,List<UserRoleEntity>> userRoles = userRoleService.list(new LambdaQueryWrapper<UserRoleEntity>().in(UserRoleEntity::getRoleId,roleIds)).stream().collect(Collectors.groupingBy(UserRoleEntity::getRoleId));
            Map<Long,List<Long>> usMap = new HashMap<>();
            for (Map.Entry<Long,List<UserRoleEntity>> entry : userRoles.entrySet()) {
                usMap.put(entry.getKey(),entry.getValue().stream().map(UserRoleEntity::getUserId).collect(Collectors.toList()));
            }
            List<UserEntity> users = userService.list();
            if (!CollectionUtils.isEmpty(roles) && Objects.nonNull(usMap)) {
                roles.forEach(user -> {
                    List<Long> userIds = usMap.get(user.getId());
                    if (!CollectionUtils.isEmpty(userIds)) {
                        List<String> unames = users.stream().filter(s -> userIds.contains(s.getId())).map(UserEntity::getRealName).collect(Collectors.toList());
                        user.setUserNames(StringUtils.join(unames,","));
                        user.setUserIds(userIds);
                    }
                });
            }

        }
    }

}
