# AdjEmailConfigServiceImpl.java

    package cloud.wconnect.frontoffice.service.adjustment.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.adjustment.AdjNotifyConfigTypeEnum;
    import cloud.wconnect.frontoffice.entity.adjustment.AdjEmailConfig;
    import cloud.wconnect.frontoffice.entity.adjustment.AdjEmailTarget;
    import cloud.wconnect.frontoffice.mapper.adjustment.AdjEmailConfigMapper;
    import cloud.wconnect.frontoffice.pojo.dto.adjustment.AdjEmailConfigDTO;
    import cloud.wconnect.frontoffice.pojo.dto.adjustment.AdjEmailTargetDTO;
    import cloud.wconnect.frontoffice.service.adjustment.IAdjEmailConfigService;
    import cloud.wconnect.frontoffice.service.adjustment.IAdjEmailTargetService;
    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>
     * Adjustment Requests 功能的邮件配置表 服务实现类
     * </p>
     *
     * @author lichen
     * @since 2023-03-30
     */
    @Service
    @DS("logbook")
    public class AdjEmailConfigServiceImpl extends ServiceImpl<AdjEmailConfigMapper, AdjEmailConfig> implements IAdjEmailConfigService {

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

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

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

            AdjEmailConfig emailConfig = getByPropertyIdAndType(propertyDTO.getId(), type);
            if (Objects.isNull(emailConfig)) {
                AdjEmailConfigDTO adjEmailConfigDTO = new AdjEmailConfigDTO();
                adjEmailConfigDTO.setDefaultSubject(defaultSubject);
                adjEmailConfigDTO.setType(type);
                return adjEmailConfigDTO;
            }

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

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