package com.backendsys.modules.system.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.collection.CollUtil;
import com.backendsys.exception.CustException;
import com.backendsys.modules.system.dao.SysUserRoleDao;
import com.backendsys.modules.system.dao.SysUserRolePermissionRelationDao;
import com.backendsys.modules.system.dao.SysUserRoleRelationDao;
import com.backendsys.modules.system.entity.SysUserRole;
import com.backendsys.modules.system.entity.SysUserRolePermission;
import com.backendsys.modules.system.entity.SysUserRolePermissionRelation;
import com.backendsys.modules.system.entity.SysUserRoleRelation;
import com.backendsys.modules.system.service.SysUserRoleService;
import com.backendsys.utils.response.PageEntity;
import com.backendsys.utils.response.PageInfoResult;
import com.backendsys.utils.v2.PageUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleDao, SysUserRole> implements SysUserRoleService {

    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Autowired
    private SysUserRoleRelationDao sysUserRoleRelationDao;
    @Autowired
    private SysUserRolePermissionRelationDao sysUserRolePermissionRelationDao;

    @Override
    public PageEntity selectUserRoleList(SysUserRole sysUserRole) {
        PageUtils.startPage();  // 分页
        List<SysUserRole> list = sysUserRoleDao.selectUserRoleList(sysUserRole);
        return new PageInfoResult(list).toEntity();
    }

    @Override
    public SysUserRole selectUserRoleDetail(SysUserRole sysUserRole) {

        Long role_id = sysUserRole.getRole_id();
        SysUserRole roleDetail = sysUserRoleDao.selectById(role_id);
        if (roleDetail == null) throw new CustException("系统用户角色不存在");

        // 查询绑定人数
        LambdaQueryWrapper<SysUserRoleRelation> queryWrapper = new LambdaQueryWrapper<SysUserRoleRelation>().eq(SysUserRoleRelation::getRole_id, role_id);
        Long count = sysUserRoleRelationDao.selectCount(queryWrapper);
        roleDetail.setUser_count(Convert.toInt(count));

        // 查询角色对应的权限
        List<SysUserRolePermission> permissions = sysUserRolePermissionRelationDao.selectUserRolePermissionByRoleId(role_id);
        roleDetail.setPermissions(permissions);

        List<String> permission_ids = permissions.stream().filter(permission -> permission != null).map(p -> p.getId()).collect(Collectors.toList());
        roleDetail.setPermission_ids(permission_ids);

        return roleDetail;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> insertUserRole(SysUserRole sysUserRole) {

        // 判断 modules 是否重复
        List<String> permissionIds = sysUserRole.getPermission_ids();
        if (CollUtil.isNotEmpty(permissionIds) && permissionIds.size() != CollUtil.distinct(permissionIds).size()) {
            throw new CustException("权限ID出现重复值");
        }

        // 创建角色
        sysUserRoleDao.insertUserRole(sysUserRole);
        // 创建角色与权限关系
        sysUserRoleDao.insertUserRolePermissionRelation(sysUserRole);

        return Map.of("role_id", sysUserRole.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> updateUserRole(SysUserRole sysUserRole) {

        // 判断 modules 是否重复
        List<String> permissionIds = sysUserRole.getPermission_ids();
        if (CollUtil.isNotEmpty(permissionIds) && permissionIds.size() != CollUtil.distinct(permissionIds).size()) {
            // 筛选出重复值
            Map<String, Integer> countMap = CollUtil.countMap(permissionIds);
            // 筛选出出现次数大于1的元素
            List<String> duplicates = new ArrayList<>();
            for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
                if (entry.getValue() > 1) duplicates.add(entry.getKey());
            }
            throw new CustException("权限ID出现重复值: " + duplicates);
        }

        SysUserRole detail = sysUserRoleDao.selectById(sysUserRole.getRole_id());
        if (detail == null) throw new CustException("系统用户角色不存在");

        // 更新角色
        sysUserRoleDao.updateUserRole(sysUserRole);
        // 更新角色与权限关系 (需要先删除全部，再重新插入)
        sysUserRoleDao.updateUserRolePermissionRelation(sysUserRole);

        return Map.of("role_id", sysUserRole.getRole_id());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> deleteUserRole(SysUserRole sysUserRole) {

        Long role_id = sysUserRole.getRole_id();

        SysUserRole roleDetail = selectUserRoleDetail(sysUserRole);
        if (roleDetail == null) throw new CustException("系统用户角色不存在");

        Integer user_count = roleDetail.getUser_count();
        if (user_count > 0) throw new CustException("角色已关联 " + user_count + " 个用户，请解除关联后再删除");

        // 删除角色
        sysUserRoleDao.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getRole_id, role_id));
        // 删除角色与权限关系
        sysUserRolePermissionRelationDao.delete(new LambdaQueryWrapper<SysUserRolePermissionRelation>().eq(SysUserRolePermissionRelation::getRole_id, role_id));

        return Map.of("role_id", sysUserRole.getRole_id());
    }

    /**
     * 根据用户ID获取用户角色集合
     */
    @Override
    public List<SysUserRole> selectUserRoleByUserId(Long user_id) {
        List<Long> role_ids = sysUserRoleRelationDao.selectUserRoleIds(user_id);
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<SysUserRole>().in(SysUserRole::getRole_id, role_ids);
        return sysUserRoleDao.selectList(wrapper);
    }

}
