package com.tuoheng.admin.service.role;


import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuoheng.admin.dto.MenuVo;
import com.tuoheng.admin.dto.OpPermissionsVo;
import com.tuoheng.admin.dto.RoleMenuDto;
import com.tuoheng.admin.dto.RoleMenuPermissionDto;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.code.role.RoleDeleteEnum;
import com.tuoheng.admin.mapper.*;
import com.tuoheng.admin.query.RoleClientQuery;
import com.tuoheng.admin.query.RoleQuery;
import com.tuoheng.admin.service.menu.IMenuService;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.admin.vo.RoleListVo;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author ChengWang
 * @Date 2022/12/16
 */
@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private OpRolePermissionMapper opRolePermissionMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private IRoleMenuService roleMenuService;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private OpPermissionsMapper opPermissionsMapper;

    @Autowired
    private OpRolePermissionService opRolePermissionService;


    /**
     * 2023-01-11 此处角色先不区分租户的概念，整个系统就3个角色，后期调整
     *
     * @param roleQuery
     * @return
     */
    @Override
    public JsonResult getRoleList(RoleQuery roleQuery) {
        IPage<Role> page = new Page<>(roleQuery.getPage(), roleQuery.getLimit());
        // 查询条件
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        // 角色名称
        if (StringUtils.isNotEmpty(roleQuery.getRoleName())) {
            queryWrapper.like("role_name", roleQuery.getRoleName());
        }
        queryWrapper.eq("tenant_id", CurrentUserUtil.getTenantId());
        queryWrapper.eq("mark", MarkEnum.VALID.getCode());
        //queryWrapper.orderByAsc("sort");
        queryWrapper.orderByAsc("create_time");
        //queryWrapper.ne("id", "1");
        // 查询分页数据
        IPage<Role> pageData = roleMapper.selectPage(page, queryWrapper);
        pageData.convert(x -> {
            RoleListVo roleListVo = Convert.convert(RoleListVo.class, x);
            return roleListVo;
        });
        return JsonResult.success(pageData);
    }

    @Override
    public JsonResult editRole(Role entity) {
        if (StringUtils.isNotNull(entity.getId()) && entity.getId() > 0) {
            // 更新
            Integer count = roleMapper.selectCount(new LambdaQueryWrapper<Role>()
                    .ne(Role::getId, entity.getId())
                    .eq(Role::getTenantId, CurrentUserUtil.getTenantId())
                    .eq(Role::getCode, entity.getCode())
                    .eq(Role::getMark, MarkEnum.VALID.getCode()));
            //当前用户
            entity.setUpdateUser(CurrentUserUtil.getUserId());
            entity.setUpdateTime(DateUtils.now());
            if (count > 0) {
                return JsonResult.error("系统中已存在相同的角色编码");
            }
        } else {
            // 添加
            Integer count = roleMapper.selectCount(new LambdaQueryWrapper<Role>()
                    .eq(Role::getTenantId, CurrentUserUtil.getTenantId())
                    .eq(Role::getCode, entity.getCode())
                    .eq(Role::getMark, MarkEnum.VALID.getCode()));
            if (count > 0) {
                return JsonResult.error("系统中已存在相同的角色编码");
            }
            entity.setCreateUser(CurrentUserUtil.getUserId());
            entity.setCreateTime(DateUtils.now());
            entity.setTenantId(CurrentUserUtil.getTenantId());
        }
        if (entity == null) {
            return JsonResult.error("实体对象不存在");
        }
        if (entity.getId() != null && entity.getId() > 0) {
            //修改记录
            int i = roleMapper.updateById(entity);
            if (i <= 0) {
                return JsonResult.error();
            }
        } else {
            //新增记录
            int count = roleMapper.insert(entity);
            if (count <= 0) {
                return JsonResult.error();
            }
        }
        return JsonResult.success();
    }

    @Override
    public JsonResult deleteByList(Integer[] roleIds) {
        //校验
        if (null == roleIds) {
            return JsonResult.error(RoleDeleteEnum.ROLE_ID_IS_NULL.getCode(), RoleDeleteEnum.ROLE_ID_IS_NULL.getMsg());
        }
        //根据roleId查询是否关联的有用户
        for (Integer roleId : roleIds) {
            List<User> userList = userMapper.selectList(Wrappers.<User>lambdaQuery()
                    .eq(User::getMark, MarkEnum.VALID.getCode()).eq(User::getRoleId, roleId));
            if (userList.size() > 0 && StringUtils.isNotEmpty(userList)) {
                return JsonResult.error("该角色已经绑定用户,不能删除");
            }
            Role role = roleMapper.selectById(roleId);
            role.setMark(MarkEnum.NOTVALID.getCode());
            int result = roleMapper.updateById(role);
            if (result <= 0) {
                return JsonResult.error();
            }
        }
//        List<Role> roles = roleMapper.selectList(Wrappers.<Role>lambdaQuery().eq(Role::getStatus, 1).eq(Role::getMark, 1).eq(Role::getTenantId, CurrentUserUtil.getTenantId()));
//        //
//        List<Integer> collect = roles.stream().filter(t -> !t.getCode().equals("001"))
//                .filter(t -> t.getCode().equals("002"))
//                .filter(t -> t.getCode().equals("003")).map(t -> t.getId()).collect(Collectors.toList());
//        if (collect.contains(roleIds)) {
//            return JsonResult.error("初始化配置角色不能删除");
//        }
//        for (Integer roleId : roleIds) {
//            List<RoleMenu> roleMenus = roleMenuMapper.selectList(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getRoleId, roleId).eq(RoleMenu::getMark, 1));
//            if (roleMenus.size() > 0 && StringUtils.isNotEmpty(roleMenus)) {
//                return JsonResult.error("该角色已配置菜单不能删除!");
//            }
//            List<OpRolePermission> opRolePermissionList = opRolePermissionMapper.selectList(Wrappers.<OpRolePermission>lambdaQuery().eq(OpRolePermission::getRoleId,roleId).eq(OpRolePermission::getMark, 1));
//            if (opRolePermissionList.size() > 0 && StringUtils.isNotEmpty(opRolePermissionList)) {
//                return JsonResult.error("该角色已配置权限不能删除!");
//            }
//            List<UserRoleDto> userRoles = userRoleMapper.getListByRoleId(roleId, CurrentUserUtil.getTenantId());
//            if (userRoles.size() > 0 && StringUtils.isNotEmpty(userRoles)) {
//                return JsonResult.error("该角色已经分配用户不能删除!");
//            }
//            Role role = roleMapper.selectById(roleId);
//            role.setMark(0);
//            roleMapper.updateById(role);
//        }
        return JsonResult.success();
    }

    @Override
    public JsonResult getRoleLists() {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("code", "001");     // 不展示超管
        queryWrapper.eq("tenant_id", CurrentUserUtil.getTenantId());
        queryWrapper.eq("status", 1);
        queryWrapper.eq("mark", MarkEnum.VALID.getCode());
        queryWrapper.orderByAsc("create_time");
        List<Role> rolesLists = roleMapper.selectList(queryWrapper);
        return JsonResult.success(rolesLists);
    }

    /**
     * 获取菜单列表
     *
     * @param query
     * @return
     */
    @Override
    public JsonResult getMenuList(RoleClientQuery query) {
        RoleMenuPermissionDto dto = new RoleMenuPermissionDto();
        Integer roleId = query.getRoleId();
        List<Menu> menuList = menuMapper.selectList(Wrappers.<Menu>lambdaQuery()
                .eq(Menu::getMark, MarkEnum.VALID.getCode())
                .eq(Menu::getStatus, 1)
                .eq(StringUtils.isNotEmpty(query.getClientId()), Menu::getClientId, query.getClientId())
                .orderByAsc(Menu::getSort));
        if (!menuList.isEmpty()) {
            // 获取角色菜单列表
            QueryWrapper<RoleMenu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role_id", roleId);
            queryWrapper.select("menu_id");
            List<RoleMenu> roleMenus = roleMenuMapper.selectList(queryWrapper);
            List<Integer> menuIds = roleMenus.stream().map(p -> p.getMenuId()).collect(Collectors.toList());
            menuList.forEach(item -> {
                if (menuIds.contains(item.getId())) {
                    item.setChecked(true);
                    item.setOpen(true);
                }
            });
        }
        List<MenuVo> collect = menuList.stream().map(t -> {
            MenuVo vo = new MenuVo();
            BeanUtils.copyProperties(t, vo);
            vo.setIdentificationId(t.getId().toString());
            return vo;
        }).collect(Collectors.toList());

        dto.setOpMenusList(collect);
        //根基小程序或者pc标识
        List<OpPermissions> permissions = opPermissionsMapper.selectList(Wrappers.<OpPermissions>lambdaQuery()
                .eq(OpPermissions::getMark, MarkEnum.VALID.getCode())
                .eq(StringUtils.isNotEmpty(query.getClientId()), OpPermissions::getClientId, query.getClientId()));
        if (!permissions.isEmpty()) {
            //获取角色菜单列表
            QueryWrapper<OpRolePermission> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role_id", roleId);
            queryWrapper.select("permission_id");
            List<OpRolePermission> roleMenuList = opRolePermissionMapper.selectList(queryWrapper);
            List<Integer> permissionIds = roleMenuList.stream().map(p -> p.getPermissionId()).collect(Collectors.toList());
            permissions.forEach(item -> {
                if (permissionIds.contains(item.getId())) {
                    item.setChecked(true);
                    item.setOpen(true);
                }
            });
        }
        List<OpPermissionsVo> collect1 = permissions.stream().map(t -> {
            OpPermissionsVo vo = new OpPermissionsVo();
            BeanUtils.copyProperties(t, vo);
            //用"_"进行区分
            vo.setIdentificationId(t.getMenuId() + "_" + t.getId());
            return vo;
        }).collect(Collectors.toList());
        dto.setPermissionsList(collect1);
        dto.setRoleId(roleId);

        return JsonResult.success(dto);
    }

    @Override
    public JsonResult updateStatus(Role entity) {
        Role role = roleMapper.selectById(entity.getId());
        if (null == role) {
            return JsonResult.error("该角色不存在");
        }
        role.setStatus(entity.getStatus());
        roleMapper.updateById(role);
        return JsonResult.success();
    }

    @Override
    public JsonResult savePermission(RoleMenuDto roleMenuDto) {
        // 角色ID校验
        if (StringUtils.isNull(roleMenuDto.getRoleId())) {
            return JsonResult.error("角色ID不能位空");
        }
        // 同步删除角色菜单,权限关系数据
        roleMenuService.deleteRoleMenus(roleMenuDto.getRoleId());
        opRolePermissionService.deleteRolePermissions(roleMenuDto.getRoleId());

        // 插入新的角色菜单关系数据and权限
        List<RoleMenu> roleMenuList = new ArrayList<>();
        List<OpRolePermission> permissions = new ArrayList<>();
        if (roleMenuDto.getIds().length > 0) {
            for (String id : roleMenuDto.getIds()) {
                if (id.contains("_")) {
                    id = id.split("_")[1];
                    OpRolePermission opRolePermission = new OpRolePermission();
                    opRolePermission.setRoleId(roleMenuDto.getRoleId());
                    opRolePermission.setPermissionId(Integer.parseInt(id));
                    permissions.add(opRolePermission);
                } else {
                    RoleMenu roleMenu = new RoleMenu();
                    //roleMenu.setTenantId(ShiroUtils.getTenantId());
                    roleMenu.setRoleId(roleMenuDto.getRoleId());
                    roleMenu.setMenuId(Integer.parseInt(id));
                    roleMenuList.add(roleMenu);
                }
            }
        }
        // 批量插入角色菜单关系数据
        roleMenuList.forEach(item -> {
            roleMenuMapper.insert(item);
        });
        permissions.forEach(item -> {
            opRolePermissionMapper.insert(item);
        });
        return JsonResult.success("权限保存成功");
    }

    /**
     * 初始化租户固定角色
     *
     * @param ids
     * @return
     */
    @Override
    public JsonResult roleToTenant(Integer[] ids) {
        for (Integer id : ids) {
            //批量初始化租户对应角色配置
            List<Role> roles = roleMapper.selectList(Wrappers.<Role>lambdaQuery()
                    .eq(Role::getMark, MarkEnum.VALID.getCode()).eq(Role::getStatus, 1)
                    .eq(Role::getTenantId, 1)
                    .ne(Role::getCode, "super"));
            for (Role role : roles) {
                role.setTenantId(id.toString());
                roleMapper.insert(role);
            }
        }
        return JsonResult.success();
    }

    @Override
    public JsonResult getRoles() {

        //超管
        User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, "superAdmin").eq(User::getMark, 1));
        if (StringUtils.isNull(user)) {
            List<Role> roles = roleMapper.selectList(Wrappers.<Role>lambdaQuery()
                    .eq(Role::getCode, "superAdmin")
                    .eq(Role::getMark, 1)
                    .eq(Role::getStatus, 1));
            return JsonResult.success(roles);
        }
        //对应的租户角色
        List<Role> roles = roleMapper.selectList(Wrappers.<Role>lambdaQuery()
                .eq(Role::getTenantId, user.getTenantId())
                .eq(Role::getMark, 1)
                .eq(Role::getStatus, 1));
        return JsonResult.success(roles);
    }


}
