# WalkRoomEmailConfigServiceImpl.java

    package cloud.wconnect.frontoffice.service.walkroomrequest.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.walkroomrequest.WalkRoomRequestNotifyConfigTypeEnum;
    import cloud.wconnect.frontoffice.entity.walkroomrequest.WalkRoomEmailConfig;
    import cloud.wconnect.frontoffice.entity.walkroomrequest.WalkRoomEmailTarget;
    import cloud.wconnect.frontoffice.mapper.walkroomrequest.WalkRoomEmailConfigMapper;
    import cloud.wconnect.frontoffice.pojo.dto.walkroomrequest.WalkRoomEmailConfigDTO;
    import cloud.wconnect.frontoffice.pojo.dto.walkroomrequest.WalkRoomEmailTargetDTO;
    import cloud.wconnect.frontoffice.service.walkroomrequest.IWalkRoomEmailConfigService;
    import cloud.wconnect.frontoffice.service.walkroomrequest.IWalkRoomEmailTargetService;
    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 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>
     * walk room功能的邮件配置表 服务实现类
     * </p>
     *
     * @author lichen
     * @since 2023-07-08
     */
    @Service
    @DS("logbook")
    public class WalkRoomEmailConfigServiceImpl extends ServiceImpl<WalkRoomEmailConfigMapper, WalkRoomEmailConfig> implements IWalkRoomEmailConfigService {

        @Autowired
        private IWalkRoomEmailTargetService 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.guestledger.GlcEmailConfigDTO
         * @author lichen
         * @date 2024/3/15
         */
        @Override
        public WalkRoomEmailConfigDTO getByPropertyAndType(PropertyDTO propertyDTO, Integer type) {
            //当前上下文语言
            Locale currentThreadLocale = LocaleContextHolder.getLocale();
            //获取功能名称
            String functionName = i18nMessageUtils.message(FunctionCons.WALK_ROOM_REQUESTS, currentThreadLocale);
            //获取默认主题
            String defaultSubjectI18nCode = WalkRoomRequestNotifyConfigTypeEnum.getDefaultSubjectI18nCode(type);
            String defaultSubject = i18nMessageUtils.message(defaultSubjectI18nCode, currentThreadLocale, functionName, propertyDTO.getName());

            //查询EmailConfig
            WalkRoomEmailConfig emailConfig = getOne(new LambdaQueryWrapper<WalkRoomEmailConfig>()
                    .eq(WalkRoomEmailConfig::getPropertyId, propertyDTO.getId())
                    .eq(WalkRoomEmailConfig::getType, type));
            if (Objects.isNull(emailConfig)) {
                WalkRoomEmailConfigDTO walkRoomEmailConfigDTO = new WalkRoomEmailConfigDTO();
                walkRoomEmailConfigDTO.setDefaultSubject(defaultSubject);
                walkRoomEmailConfigDTO.setType(type);
                return walkRoomEmailConfigDTO;
            }
            //查询通知对象
            List<WalkRoomEmailTarget> emailTargetList = emailTargetService.listByConfigId(Lists.newArrayList(emailConfig.getId()));

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

            WalkRoomEmailConfigDTO configDTO = beanMapper.map(emailConfig, WalkRoomEmailConfigDTO.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/15
         */
        @Override
        public void checkSole(Integer propertyId, Integer type) {
            long count = count(new LambdaQueryWrapper<WalkRoomEmailConfig>()
                    .eq(WalkRoomEmailConfig::getPropertyId, propertyId)
                    .eq(WalkRoomEmailConfig::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/15
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public Integer save(PropertyDTO propertyDTO, WalkRoomEmailConfigDTO configDTO) {
            WalkRoomEmailConfig config = new WalkRoomEmailConfig()
                    .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<WalkRoomEmailTarget>().lambda().eq(WalkRoomEmailTarget::getConfigId,
                        configDTO.getId()));
            }

            List<WalkRoomEmailTarget> targets = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(configDTO.getToList())) {
                targets.addAll(configDTO.getToList().stream().map(item -> beanMapper.map(item, WalkRoomEmailTarget.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, WalkRoomEmailTarget.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.walkroom.WalkRoomEmailConfig
         * @author lichen
         * @date 2024/3/15
         */
        @Override
        public WalkRoomEmailConfig getByPropertyIdAndType(Integer propertyId, int type) {
            return getOne(new LambdaQueryWrapper<WalkRoomEmailConfig>()
                    .eq(WalkRoomEmailConfig::getPropertyId, propertyId)
                    .eq(WalkRoomEmailConfig::getType, type));
        }

    }