# BgEmailConfigServiceImpl.java

    package cloud.wconnect.frontoffice.service.badguest.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.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.badguest.BlacklistNotifyConfigTypeEnum;
    import cloud.wconnect.frontoffice.entity.badguest.BgEmailConfig;
    import cloud.wconnect.frontoffice.entity.badguest.BgEmailTarget;
    import cloud.wconnect.frontoffice.mapper.badguest.BgEmailConfigMapper;
    import cloud.wconnect.frontoffice.pojo.dto.badguest.BgEmailConfigDTO;
    import cloud.wconnect.frontoffice.pojo.dto.badguest.BgEmailTargetDTO;
    import cloud.wconnect.frontoffice.service.badguest.IBgEmailConfigService;
    import cloud.wconnect.frontoffice.service.badguest.IBgEmailTargetService;
    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.collections.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>
     * Guests Blacklist 功能的邮件配置表 服务实现类
     * </p>
     *
     * @author lichen
     * @since 2023-03-20
     */
    @Service
    @DS("logbook")
    public class BgEmailConfigServiceImpl extends ServiceImpl<BgEmailConfigMapper, BgEmailConfig> implements IBgEmailConfigService {

        @Autowired
        private IBgEmailTargetService 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.badguest.BgEmailConfig
         * @author lichen
         * @date 2024/3/14
         */
        @Override
        public BgEmailConfig getByPropertyIdAndType(int propertyId, int type) {
            //查询EmailConfig
            LambdaQueryWrapper<BgEmailConfig> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(BgEmailConfig::getPropertyId, propertyId);
            queryWrapper.eq(BgEmailConfig::getType, type);
            return getOne(queryWrapper);
        }

        /**
         * 保存邮件配置
         *
         * @param propertyId     资产ID
         * @param emailConfigDTO 邮件配置DTO
         * @return 配置 id
         * @author lichen
         * @date 2024/3/14
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public Integer save(Integer propertyId, BgEmailConfigDTO emailConfigDTO) {
            BgEmailConfig config = new BgEmailConfig()
                    .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<BgEmailTarget> targets = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(emailConfigDTO.getToList())) {
                targets.addAll(emailConfigDTO.getToList().stream().map(item -> beanMapper.map(item, BgEmailTarget.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, BgEmailTarget.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/14
         */
        @Override
        public void checkSole(Integer propertyId, Integer type) {
            long count = count(new LambdaQueryWrapper<BgEmailConfig>()
                    .eq(BgEmailConfig::getPropertyId, propertyId)
                    .eq(BgEmailConfig::getType, type));
            if (count > 0) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_EXISTED,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The black list email config already exist, propertyId=" + propertyId + ", type=" + type);
            }
        }

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

            BgEmailConfig emailConfig = getByPropertyIdAndType(propertyDTO.getId(), type);
            if (Objects.isNull(emailConfig)) {
                BgEmailConfigDTO bgEmailConfigDTO = new BgEmailConfigDTO();
                bgEmailConfigDTO.setDefaultSubject(defaultSubject);
                bgEmailConfigDTO.setType(type);
                return bgEmailConfigDTO;
            }

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

            return beanMapper.map(emailConfig, BgEmailConfigDTO.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.badguest.BgEmailTargetDTO>>
         * @author lichen
         * @date 2024/3/14
         */
        private Map<Integer, List<BgEmailTargetDTO>> emailTargetToDTO(PropertyDTO propertyDTO, List<BgEmailTarget> emailTargetList) {
            if (CollectionUtils.isEmpty(emailTargetList)) return Collections.emptyMap();
            //按照用户来源分组
            Map<Integer, List<Integer>> source2IdentityIdList = emailTargetList.stream()
                    .collect(Collectors.groupingBy(BgEmailTarget::getSource, Collectors.mapping(BgEmailTarget::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, BgEmailTargetDTO.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(BgEmailTargetDTO::getTargetType));
        }

    }