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


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.user.admin.request.RoleAuthorityReq;
import com.seer.teach.user.admin.response.AuthorityResp;
import com.seer.teach.user.admin.service.AdminRoleAuthorityService;
import com.seer.teach.user.entity.AuthorityEntity;
import com.seer.teach.user.entity.RoleAuthorityEntity;
import com.seer.teach.user.entity.RoleEntity;
import com.seer.teach.user.service.IAuthorityService;
import com.seer.teach.user.service.IRoleAuthorityService;
import com.seer.teach.user.service.IRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
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 AdminRoleAuthorityServiceImpl  implements AdminRoleAuthorityService {

    private final IRoleAuthorityService roleAuthorityService;

    private final IRoleService roleService;

    private final IAuthorityService IAuthorityService;

    @Override
    public void deleteRoleAuthority(RoleAuthorityReq params) {
        Integer loginId = StpUtil.getLoginIdAsInt();
        RoleEntity roleEntity = roleService.getById(params.getRoleId());
        if (RoleEnum.ADMIN.getCode().equalsIgnoreCase(roleEntity.getRoleName())){
            throw new CommonException(ResultCodeEnum.DO_NOT_OPERATE_SUPER_ADMIN_ROLE);
        }
        boolean remove = roleAuthorityService.remove(new LambdaQueryWrapper<RoleAuthorityEntity>()
                .eq(RoleAuthorityEntity::getRoleId, params.getRoleId())
                .in(RoleAuthorityEntity::getAuthorityId, params.getAuthorityIds()));
        log.info("用户[{}]删除角色权限:{},RoleAuthorityReq:{}",loginId,remove,params);
    }

    @Override
    @Transactional
    public void addRoleAuthority(RoleAuthorityReq params) {

        RoleEntity roleEntity = roleService.getById(params.getRoleId());
        AssertUtils.notNull(roleEntity,ResultCodeEnum.USER_ROLE_NOT_FOUND);

        List<Integer> authorityIds = params.getAuthorityIds();
        List<RoleAuthorityEntity> addList = new ArrayList<>();
        for (Integer authorityId : authorityIds){
            RoleAuthorityEntity roleAuthorityEntity = new RoleAuthorityEntity();
            roleAuthorityEntity.setRoleId(params.getRoleId());
            roleAuthorityEntity.setAuthorityId(authorityId);
            addList.add(roleAuthorityEntity);
        }
        List<RoleAuthorityEntity> roleAuthorityEntities = roleAuthorityService.list(new LambdaQueryWrapper<RoleAuthorityEntity>().eq(RoleAuthorityEntity::getRoleId, params.getRoleId()).in(RoleAuthorityEntity::getAuthorityId, authorityIds));
        if(CollectionUtils.isNotEmpty(roleAuthorityEntities)){
            List<Integer> authorityIdList = roleAuthorityEntities.stream().map(RoleAuthorityEntity::getAuthorityId).collect(Collectors.toList());
            addList = addList.stream().filter(i -> !authorityIdList.contains(i.getAuthorityId())).collect(Collectors.toList());
        }
        roleAuthorityService.saveBatch(addList);
        log.info("用户[{}]添加角色权限:{}",StpUtil.getLoginIdAsInt(),addList);
    }

    /**
     * 根据角色Id查询权限列表
     *
     * @param roleId
     */
    @Override
    public List<AuthorityResp> getAuthorityListByRoleId(Integer roleId) {
        List<RoleAuthorityEntity> roleAuthList = roleAuthorityService.list(new LambdaQueryWrapper<RoleAuthorityEntity>()
                .eq(RoleAuthorityEntity::getRoleId, roleId));
        if(CollectionUtils.isEmpty(roleAuthList)){
            return Collections.emptyList();
        }
        List<Integer> authorityIds = roleAuthList.stream()
                .map(RoleAuthorityEntity::getAuthorityId)
                .collect(Collectors.toList());
        List<AuthorityEntity> authorityList = IAuthorityService.list(
                new LambdaQueryWrapper<AuthorityEntity>()
                        .in(AuthorityEntity::getId, authorityIds)
                        .orderByAsc(AuthorityEntity::getSort)
        );
        log.info("根据角色Id查询权限列表:{}",roleId);
        List<AuthorityResp> respList = new ArrayList<>();
        for(AuthorityEntity authorityEntity : authorityList){
            AuthorityResp authorityResp= new AuthorityResp();
            authorityResp.setId(authorityEntity.getId());
            authorityResp.setAuthorityCode(authorityEntity.getAuthorityCode());
            authorityResp.setTitle(authorityEntity.getTitle());
            respList.add(authorityResp);
        }
        log.info("用户[{}]根据角色Id查询权限列表:{}",StpUtil.getLoginIdAsInt(),respList);
        return respList;
    }

}
