# EosEmailConfigServiceImpl.java

    package cloud.wconnect.frontoffice.service.endofshift.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.pojo.dto.internationalization.InternationalizationDateTimeDTO;
    import cloud.wconnect.commonlib.service.UserInternalService;
    import cloud.wconnect.commonlib.service.UsergroupInternalService;
    import cloud.wconnect.commonlib.util.I18nMessageUtils;
    import cloud.wconnect.frontoffice.cons.endofshift.EndOfShiftNotifyConfigTypeEnum;
    import cloud.wconnect.frontoffice.entity.endofshift.EosEmailConfig;
    import cloud.wconnect.frontoffice.entity.endofshift.EosEmailTarget;
    import cloud.wconnect.frontoffice.mapper.endofshift.EosEmailConfigMapper;
    import cloud.wconnect.frontoffice.pojo.dto.endofshift.EosEmailConfigDTO;
    import cloud.wconnect.frontoffice.pojo.dto.endofshift.EosEmailTargetDTO;
    import cloud.wconnect.frontoffice.service.endofshift.IEosEmailConfigService;
    import cloud.wconnect.frontoffice.service.endofshift.IEosEmailTargetService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    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>
     * 服务实现类
     * </p>
     *
     * @author lichen
     * @since 2023-03-13
     */
    @Service
    @DS("ratelog_manage")
    public class EosEmailConfigServiceImpl extends ServiceImpl<EosEmailConfigMapper, EosEmailConfig> implements IEosEmailConfigService {

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

        /**
         * 获取邮件配置
         *
         * @param propertyDTO 资产DTO
         * @param type        类型
         * @return cloud.wconnect.frontoffice.pojo.dto.endofshiftreport.EosEmailConfigDTO
         * @author lichen
         * @date 2024/3/8
         */
        @Override
        public EosEmailConfigDTO get(PropertyDTO propertyDTO, int type) {
            //当前上下文语言
            Locale currentThreadLocale = LocaleContextHolder.getLocale();
            //获取功能名称
            String functionName = i18nMessageUtils.message(FunctionCons.END_OF_SHIFT, currentThreadLocale);

            //获取国际化配置的日期格式
            InternationalizationDateTimeDTO dateTime = propertyDTO.getInternationalization().getDateTime();
            String longDate = dateTime.getLongDate();

            //获取预览主题的国际化code
            String previewSubjectI18nCode = EndOfShiftNotifyConfigTypeEnum.getPreviewSubjectI18nCode(type);
            //获取预览的主题
            String previewSubject = i18nMessageUtils.message(previewSubjectI18nCode, currentThreadLocale, functionName, longDate, propertyDTO.getName());

            //查询EmailConfig
            LambdaQueryWrapper<EosEmailConfig> eosEmailConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
            eosEmailConfigLambdaQueryWrapper.eq(EosEmailConfig::getPropertyId, propertyDTO.getId());
            eosEmailConfigLambdaQueryWrapper.eq(EosEmailConfig::getType, type);
            EosEmailConfig emailConfig = getOne(eosEmailConfigLambdaQueryWrapper);
            if (Objects.isNull(emailConfig)) {
                EosEmailConfigDTO eosEmailConfigDTO = new EosEmailConfigDTO();
                eosEmailConfigDTO.setDefaultSubject(previewSubject);
                eosEmailConfigDTO.setType(type);
                return eosEmailConfigDTO;
            }

            //查询通知对象
            List<EosEmailTarget> emailTargetList = emailTargetService.list(new QueryWrapper<EosEmailTarget>()
                    .lambda().eq(EosEmailTarget::getConfigId, emailConfig.getId()));

            //按照用户来源分组
            Map<Integer, List<Integer>> source2IdentityIdList = emailTargetList.stream()
                    .collect(Collectors.groupingBy(EosEmailTarget::getSource, Collectors.mapping(EosEmailTarget::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));

            //通知对象按照通知类型分组
            Map<Integer, List<EosEmailTargetDTO>> targetsByTargetType = beanMapper.mapList(emailTargetList, EosEmailTargetDTO.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(EosEmailTargetDTO::getTargetType));

            EosEmailConfigDTO configDTO = beanMapper.map(emailConfig, EosEmailConfigDTO.class);
            configDTO.setToList(targetsByTargetType.get(EmailConfigCons.TARGET_TYPE_TO));
            configDTO.setCcList(targetsByTargetType.get(EmailConfigCons.TARGET_TYPE_CC));
            configDTO.setDefaultSubject(previewSubject);
            return configDTO;
        }

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

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

            if (configDTO.getId() > 0) {
                emailTargetService.remove(new QueryWrapper<EosEmailTarget>().lambda().eq(EosEmailTarget::getConfigId,
                        configDTO.getId()));
            }

            List<EosEmailTarget> targets = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(configDTO.getToList())) {
                targets.addAll(configDTO.getToList().stream().map(item -> beanMapper.map(item, EosEmailTarget.class,
                        target -> {
                            target.setTargetType(EmailConfigCons.TARGET_TYPE_TO);
                            target.setPropertyId(propertyDTO.getId());
                            target.setConfigId(config.getId());
                            target.setUsername(item.getIdentityName());
                        })).toList());
            }
            if (CollectionUtils.isNotEmpty(configDTO.getCcList())) {
                targets.addAll(configDTO.getCcList().stream().map(item -> beanMapper.map(item, EosEmailTarget.class,
                        target -> {
                            target.setTargetType(EmailConfigCons.TARGET_TYPE_CC);
                            target.setPropertyId(propertyDTO.getId());
                            target.setConfigId(config.getId());
                            target.setUsername(item.getIdentityName());
                        })).toList());
            }

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

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