# CompRoomEmailConfigServiceImpl.java

    package cloud.wconnect.frontoffice.service.comproom.impl;

    import cloud.wconnect.commonlib.component.BeanMapper;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.CommonErrorI18nConstant;
    import cloud.wconnect.commonlib.cons.EmailConfigCons;
    import cloud.wconnect.commonlib.cons.FunctionCons;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.pojo.bo.PropertyBO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.UserDTO;
    import cloud.wconnect.commonlib.pojo.dto.UsergroupDTO;
    import cloud.wconnect.commonlib.service.UserInternalService;
    import cloud.wconnect.commonlib.service.UsergroupInternalService;
    import cloud.wconnect.commonlib.util.I18nMessageUtils;
    import cloud.wconnect.frontoffice.cons.comproom.CompRoomNotifyConfigTypeEnum;
    import cloud.wconnect.frontoffice.entity.comproom.CompRoomEmailConfig;
    import cloud.wconnect.frontoffice.entity.comproom.CompRoomEmailTarget;
    import cloud.wconnect.frontoffice.mapper.comproom.CompRoomEmailConfigMapper;
    import cloud.wconnect.frontoffice.pojo.dto.comproom.CrEmailConfigDTO;
    import cloud.wconnect.frontoffice.pojo.dto.comproom.CrEmailTargetDTO;
    import cloud.wconnect.frontoffice.service.comproom.ICompRoomEmailConfigService;
    import cloud.wconnect.frontoffice.service.comproom.ICompRoomEmailTargetService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import com.google.common.collect.Lists;
    import org.apache.commons.collections4.CollectionUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.i18n.LocaleContextHolder;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

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

    /**
     * <p>
     * Comp Room 功能的邮件配置表 服务实现类
     * </p>
     *
     * @author lichen
     * @since 2023-03-28
     */
    @Service
    @DS("logbook")
    public class CompRoomEmailConfigServiceImpl extends ServiceImpl<CompRoomEmailConfigMapper, CompRoomEmailConfig> implements ICompRoomEmailConfigService {

        @Autowired
        private ICompRoomEmailTargetService emailTargetService;
        @Autowired
        private BeanMapper beanMapper;
        @Autowired
        private UserInternalService userInternalService;
        @Autowired
        private UsergroupInternalService usergroupInternalService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        /**
         * 查询邮件配置
         *
         * @param propertyId 资产ID
         * @param type       邮件配置类型
         * @return cloud.wconnect.frontoffice.entity.comproom.CompRoomEmailConfig
         * @author lichen
         * @date 2024/3/13
         */
        @Override
        public CompRoomEmailConfig getByPropertyIdAndType(Integer propertyId, Integer type) {
            return getOne(new LambdaQueryWrapper<CompRoomEmailConfig>()
                    .eq(CompRoomEmailConfig::getPropertyId, propertyId)
                    .eq(CompRoomEmailConfig::getType, type));
        }

        /**
         * 保存邮件配置
         *
         * @param propertyId     资产ID
         * @param emailConfigDTO 邮件配置DTO
         * @return 配置ID
         * @author lichen
         * @date 2024/3/12
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public Integer save(Integer propertyId, CrEmailConfigDTO emailConfigDTO) {
            CompRoomEmailConfig config = new CompRoomEmailConfig()
                    .setId(emailConfigDTO.getId())
                    .setPropertyId(propertyId)
                    .setType(emailConfigDTO.getType())
                    .setSubject(emailConfigDTO.getSubject())
                    .setStatus(emailConfigDTO.getStatus());
            saveOrUpdate(config);

            if (emailConfigDTO.getId() > 0) {
                emailTargetService.removeByConfigId(emailConfigDTO.getId());
            }

            //保存邮件targets表
            List<CompRoomEmailTarget> targets = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(emailConfigDTO.getToList())) {
                targets.addAll(emailConfigDTO.getToList().stream().map(item -> beanMapper.map(item, CompRoomEmailTarget.class,
                        target -> {
                            target.setTargetType(EmailConfigCons.TARGET_TYPE_TO);
                            target.setPropertyId(propertyId);
                            target.setConfigId(config.getId());
                            target.setUsername(item.getIdentityName());
                        })).toList());
            }
            if (CollectionUtils.isNotEmpty(emailConfigDTO.getCcList())) {
                targets.addAll(emailConfigDTO.getCcList().stream().map(item -> beanMapper.map(item, CompRoomEmailTarget.class,
                        target -> {
                            target.setTargetType(EmailConfigCons.TARGET_TYPE_CC);
                            target.setPropertyId(propertyId);
                            target.setConfigId(config.getId());
                            target.setUsername(item.getIdentityName());
                        })).toList());
            }

            emailTargetService.saveBatch(targets);
            return config.getId();
        }

        /**
         * 删除通知配置
         *
         * @param propertyId 资产Id
         * @param type       配置类型
         * @return void
         * @author lichen
         * @date 2024/3/12
         */
        @Override
        public void delete(Integer propertyId, Integer type) {
            CompRoomEmailConfig emailConfig = getByPropertyIdAndType(propertyId, type);
            if (Objects.isNull(emailConfig)) return;

            removeById(emailConfig.getId());

            emailTargetService.removeByConfigId(emailConfig.getId());
        }

        /**
         * 校验唯一
         *
         * @param propertyId 资产Id
         * @param type       邮件配置类型
         * @return void
         * @author lichen
         * @date 2024/3/14
         */
        @Override
        public void checkSole(Integer propertyId, Integer type) {
            long count = count(new LambdaQueryWrapper<CompRoomEmailConfig>()
                    .eq(CompRoomEmailConfig::getPropertyId, propertyId)
                    .eq(CompRoomEmailConfig::getType, type));
            if (count > 0) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_EXISTED,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The comp room email config already exist, propertyId=" + propertyId + ", type=" + type);
            }
        }

        /**
         * 查询邮件配置
         *
         * @param propertyDTO 资产DTO
         * @param type        邮件配置类型
         * @return cloud.wconnect.frontoffice.pojo.dto.comproom.CrEmailConfigDTO
         * @author lichen
         * @date 2024/3/13
         */
        @Override
        public CrEmailConfigDTO getByPropertyIdAndType(PropertyDTO propertyDTO, Integer type) {
            //当前上下文语言
            Locale currentThreadLocale = LocaleContextHolder.getLocale();
            //获取功能名称
            String functionName = i18nMessageUtils.message(FunctionCons.COMP_ROOM, currentThreadLocale);
            //获取默认主题
            String defaultSubjectI18nCode = CompRoomNotifyConfigTypeEnum.getDefaultSubjectI18nCode(type);
            String defaultSubject = i18nMessageUtils.message(defaultSubjectI18nCode, currentThreadLocale, functionName, propertyDTO.getName());

            CompRoomEmailConfig emailConfig = getByPropertyIdAndType(propertyDTO.getId(), type);
            if (Objects.isNull(emailConfig)) {
                CrEmailConfigDTO crEmailConfigDTO = new CrEmailConfigDTO();
                crEmailConfigDTO.setDefaultSubject(defaultSubject);
                crEmailConfigDTO.setType(type);
                return crEmailConfigDTO;
            }

            //查询通知对象
            List<CompRoomEmailTarget> emailTargets = emailTargetService.listByConfigId(Lists.newArrayList(emailConfig.getId()));
            Map<Integer, List<CrEmailTargetDTO>> targetType2EmailTargetDTOS = emailTargetToDTO(propertyDTO, emailTargets);

            return beanMapper.map(emailConfig, CrEmailConfigDTO.class, dto -> {
                dto.setToList(targetType2EmailTargetDTOS.getOrDefault(EmailConfigCons.TARGET_TYPE_TO, Collections.emptyList()));
                dto.setCcList(targetType2EmailTargetDTOS.getOrDefault(EmailConfigCons.TARGET_TYPE_CC, Collections.emptyList()));
                dto.setDefaultSubject(defaultSubject);
            });
        }

        /**
         * 把EmailTarget转化成DTO
         *
         * @param propertyDTO     资产DTO
         * @param emailTargetList 邮件通知对象集合
         * @return java.util.Map<java.lang.Integer, java.util.List < cloud.wconnect.frontoffice.pojo.dto.comproom.CrEmailTargetDTO>>
         * @author lichen
         * @date 2024/3/14
         */
        private Map<Integer, List<CrEmailTargetDTO>> emailTargetToDTO(PropertyDTO propertyDTO, List<CompRoomEmailTarget> emailTargetList) {
            if (CollectionUtils.isEmpty(emailTargetList)) return Collections.emptyMap();
            //按照用户来源分组
            Map<Integer, List<Integer>> source2IdentityIdList = emailTargetList.stream()
                    .collect(Collectors.groupingBy(CompRoomEmailTarget::getSource, Collectors.mapping(CompRoomEmailTarget::getIdentityId, Collectors.toList())));

            //用户集合
            Map<Integer, UserDTO> userId2UserDTO = userInternalService.getUserMapByIds(propertyDTO.getTenantId(),
                    source2IdentityIdList.getOrDefault(EmailConfigCons.SOURCE_USER, Collections.emptyList()));
            //用户组集合
            Map<Integer, String> usergroupId2Name = usergroupInternalService.getUsergroups(propertyDTO.getTenantId(), propertyDTO.getId(),
                            source2IdentityIdList.getOrDefault(EmailConfigCons.SOURCE_USERGROUP, Collections.emptyList()))
                    .stream().collect(Collectors.toMap(UsergroupDTO::getId, UsergroupDTO::getName));

            //通知对象按照通知类型分组
            return beanMapper.mapList(emailTargetList, CrEmailTargetDTO.class, (entity, dto) -> {
                Integer source = dto.getSource();
                Integer identityId = dto.getIdentityId();
                switch (source) {
                    case EmailConfigCons.SOURCE_USER:
                        UserDTO userDTO = userId2UserDTO.get(identityId);
                        if (Objects.nonNull(userDTO)) {
                            dto.setIdentityName(userDTO.getName());
                            dto.setEmail(userDTO.getEmail());
                        }
                        break;
                    case EmailConfigCons.SOURCE_USERGROUP:
                        dto.setIdentityName(usergroupId2Name.get(identityId));
                        break;
                    case EmailConfigCons.SOURCE_MANUAL:
                        dto.setIdentityName(entity.getUsername());
                        break;
                    default:
                        break;
                }
            }).stream().collect(Collectors.groupingBy(CrEmailTargetDTO::getTargetType));
        }
    }