# GlcEmailConfigServiceImpl.java

    package cloud.wconnect.frontoffice.service.guestledgercheck.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.guestledgercheck.GuestLedgerCheckNotifyConfigEnum;
    import cloud.wconnect.frontoffice.entity.guestledgercheck.GlcEmailConfig;
    import cloud.wconnect.frontoffice.entity.guestledgercheck.GlcEmailTarget;
    import cloud.wconnect.frontoffice.mapper.guestledgercheck.GlcEmailConfigMapper;
    import cloud.wconnect.frontoffice.pojo.dto.guestledgercheck.GlcEmailConfigDTO;
    import cloud.wconnect.frontoffice.pojo.dto.guestledgercheck.GlcEmailTargetDTO;
    import cloud.wconnect.frontoffice.service.guestledgercheck.IGlcEmailConfigService;
    import cloud.wconnect.frontoffice.service.guestledgercheck.IGlcEmailTargetService;
    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>
     * Guest Ledger Check 功能的邮件配置表 服务实现类
     * </p>
     *
     * @author lichen
     * @since 2023-03-20
     */
    @Service
    @DS("logbook")
    public class GlcEmailConfigServiceImpl extends ServiceImpl<GlcEmailConfigMapper, GlcEmailConfig> implements IGlcEmailConfigService {

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

        /**
         * 根据资产id获取邮件配置
         *
         * @param propertyDTO 资产DTO
         * @param type        邮件配置类型
         * @return cloud.wconnect.frontoffice.pojo.dto.guestledger.GlcEmailConfigDTO
         * @author lichen
         * @date 2024/3/8
         */
        @Override
        public GlcEmailConfigDTO getByPropertyAndType(PropertyDTO propertyDTO, Integer type) {
            //当前上下文语言
            Locale currentThreadLocale = LocaleContextHolder.getLocale();
            //获取功能名称
            String functionName = i18nMessageUtils.message(FunctionCons.GUEST_LEDGER_CHECK, currentThreadLocale);
            //获取默认主题
            String defaultSubjectI18nCode = GuestLedgerCheckNotifyConfigEnum.getDefaultSubjectI18nCode(type);
            String defaultSubject = i18nMessageUtils.message(defaultSubjectI18nCode, currentThreadLocale, functionName, propertyDTO.getName());

            //查询EmailConfig
            GlcEmailConfig emailConfig = getOne(new LambdaQueryWrapper<GlcEmailConfig>()
                    .eq(GlcEmailConfig::getPropertyId, propertyDTO.getId())
                    .eq(GlcEmailConfig::getType, type));
            if (Objects.isNull(emailConfig)) {
                GlcEmailConfigDTO glcEmailConfigDTO = new GlcEmailConfigDTO();
                glcEmailConfigDTO.setDefaultSubject(defaultSubject);
                glcEmailConfigDTO.setType(type);
                return glcEmailConfigDTO;
            }
            //查询通知对象
            List<GlcEmailTarget> emailTargetList = emailTargetService.list(new QueryWrapper<GlcEmailTarget>()
                    .lambda().eq(GlcEmailTarget::getConfigId, emailConfig.getId()));

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

            GlcEmailConfigDTO configDTO = beanMapper.map(emailConfig, GlcEmailConfigDTO.class);
            configDTO.setToList(targetsByTargetType.get(EmailConfigCons.TARGET_TYPE_TO));
            configDTO.setCcList(targetsByTargetType.get(EmailConfigCons.TARGET_TYPE_CC));
            configDTO.setDefaultSubject(defaultSubject);
            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<GlcEmailConfig>()
                    .eq(GlcEmailConfig::getPropertyId, propertyId)
                    .eq(GlcEmailConfig::getType, type));
            if (count > 0) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_EXISTED,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The propertyId Guest Ledger check email config already exist, propertyId = " + propertyId);
            }
        }

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

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

            List<GlcEmailTarget> targets = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(configDTO.getToList())) {
                targets.addAll(configDTO.getToList().stream().map(item -> beanMapper.map(item, GlcEmailTarget.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, GlcEmailTarget.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();
        }

    }