package com.seer.teach.user.admin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.constants.CommonConstant;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.enums.RoleEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.user.admin.convert.RoleConvert;
import com.seer.teach.user.admin.request.AddRole;
import com.seer.teach.user.admin.request.UpdateRoleRequest;
import com.seer.teach.user.admin.response.RoleResp;
import com.seer.teach.user.admin.service.AdminRoleService;
import com.seer.teach.user.entity.RoleEntity;
import com.seer.teach.user.entity.UserRoleEntity;
import com.seer.teach.user.service.IRoleService;
import com.seer.teach.user.service.IUserRoleService;
import com.seer.teach.user.service.IUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Captain
 * @since 2024-01-19
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminRoleServiceImpl  implements AdminRoleService {

    private final IUserService userService;

    private final IRoleService roleService;

    private final IUserRoleService userRoleService;

    @Override
    @Transactional
    public void deleteRoleByRoleId(Integer id) {
        Integer loginId = StpUtil.getLoginIdAsInt();
        RoleEntity roleEntity = roleService.getById(id);
        AssertUtils.notNull(roleEntity, ResultCodeEnum.USER_ROLE_NOT_FOUND);
        long count = userRoleService.count(new LambdaQueryWrapper<UserRoleEntity>()
                .eq(UserRoleEntity::getRoleId, id));
        if(count > 0){
            throw new CommonException(ResultCodeEnum.ROLE_CAN_NOT_BE_DELETED);
        }
        Arrays.stream(RoleEnum.values()).forEach(role -> {
            if(role.getCode().equals(roleEntity.getRoleCode())){
                throw new CommonException(ResultCodeEnum.THE_ROLE_IS_SYSTEM_ROLE);
            }
        });
        boolean remove = roleService.remove(new LambdaQueryWrapper<RoleEntity>().eq(RoleEntity::getId, id));
        log.info("管理员[{}]删除角色[{}] result:{}",loginId, id, remove);
    }

    @Override
    @Transactional
    public void addRole(AddRole addRole) {
        String roleName = addRole.getRoleName();
        long count = roleService.count(new LambdaQueryWrapper<RoleEntity>()
                .eq(RoleEntity::getRoleName, roleName));
        if(count > 0){
            throw new CommonException(ResultCodeEnum.THE_ROLE_NAME_IS_REPEATED);
        }
        RoleEntity roleEntity = RoleConvert.INSTANCE.toEntity(addRole);
        boolean save = roleService.save(roleEntity);
        log.info("添加角色[{}] result:{}", roleEntity, save);
    }

    @Override
    public void updateRole(UpdateRoleRequest params, Integer id) {
        RoleEntity one = roleService.getOne(new LambdaQueryWrapper<RoleEntity>()
                .eq(RoleEntity::getRoleName, params.getRoleName())
                .ne(RoleEntity::getId,id));
        AssertUtils.isNull(one, ResultCodeEnum.THE_ROLE_NAME_IS_REPEATED);
        Arrays.stream(RoleEnum.values()).forEach(role -> {
            if(role.getCode().equals(one.getRoleCode())){
                throw new CommonException(ResultCodeEnum.THE_ROLE_IS_SYSTEM_ROLE);
            }
        });
        RoleEntity roleEntity = roleService.getById(id);
        roleEntity.setRoleName(params.getRoleName());
        roleEntity.setRoleCode(params.getRoleCode());
        boolean updated = roleService.updateById(roleEntity);
        log.info("更新角色[{}] result:{}", roleEntity, updated);
    }

    /**
     * 获取管理员角色列表
     *
     * @param page
     * @param size
     * @param roleName
     * @return
     */
    @Override
    public PageListBean<RoleResp> listPage(Integer page, Integer size, String roleName) {
        Page<RoleEntity> pageParm = new Page<>(page, size);
        LambdaQueryWrapper<RoleEntity> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(roleName)){
            wrapper.like(RoleEntity::getRoleName,roleName);
        }
        Page<RoleEntity> resultPage = roleService.page(pageParm, wrapper);
        return PageConverterUtils.convertPageListBean(resultPage, RoleConvert.INSTANCE::toRoleRespList);
    }

    /**
     * 查询所有角色名称
     *
     * @return
     */
    @Override
    public List<RoleResp> getAllRoles() {
        List<RoleEntity> roleList = roleService.list();
        return roleList.stream().map(role -> {
            RoleResp resp = new RoleResp();
            resp.setId(role.getId());
            resp.setRoleName(role.getRoleName());
            return resp;
        }).collect(Collectors.toList());
    }

    /**
     * 根据用户ID查询角色信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<RoleResp> getRoleByUserId(Integer userId) {
        // 查询用户所有角色关系
        List<UserRoleEntity> userRoles = userRoleService.list(new LambdaQueryWrapper<UserRoleEntity>()
                .eq(UserRoleEntity::getUserId, userId));

        if(CollectionUtil.isEmpty(userRoles)){
            return Collections.emptyList();
        }
        // 提取角色ID列表
        List<Integer> roleIds = userRoles.stream()
                .map(UserRoleEntity::getRoleId)
                .distinct()
                .collect(Collectors.toList());
        // 查询角色信息
        List<RoleEntity> roles = roleService.listByIds(roleIds);
        // 转换为响应对象
        return RoleConvert.INSTANCE.toRoleRespList(roles);
    }
}