# HkInventoryEmailConfigServiceImpl.java

    package cloud.wconnect.workperformance.service.hkinventory.impl;

    import cloud.wconnect.commonlib.component.BeanMapper;
    import cloud.wconnect.commonlib.cons.*;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.ForbiddenException;
    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.workperformance.cons.hkinventory.HkInventoryNotifyConfigTypeEnum;
    import cloud.wconnect.workperformance.entity.hkinventory.HkInventoryEmailConfig;
    import cloud.wconnect.workperformance.entity.hkinventory.HkInventoryEmailTarget;
    import cloud.wconnect.workperformance.mapper.hkinventory.HkInventoryEmailConfigMapper;
    import cloud.wconnect.workperformance.pojo.dto.hkinventory.HkInventoryEmailConfigDTO;
    import cloud.wconnect.workperformance.pojo.dto.hkinventory.HkInventoryEmailTargetDTO;
    import cloud.wconnect.workperformance.service.hkinventory.IHkInventoryEmailConfigService;
    import cloud.wconnect.workperformance.service.hkinventory.IHkInventoryEmailTargetService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    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.text.MessageFormat;
    import java.util.*;
    import java.util.stream.Collectors;

    /**
     * <p>
     * Housekeeping Inventory功能的邮件配置表 服务实现类
     * </p>
     *
     * @author lichen
     * @since 2025-04-19
     */
    @Service
    @DS("work_performance")
    public class HkInventoryEmailConfigServiceImpl extends ServiceImpl<HkInventoryEmailConfigMapper, HkInventoryEmailConfig> implements IHkInventoryEmailConfigService {

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

        /**
         * 查询邮件配置
         *
         * @param propertyId 资产id
         * @param category   分类
         * @return cloud.wconnect.workperformance.entity.hkinventory.HkInventoryEmailConfig
         * @author lichen
         * @date 2025/4/25
         */
        @Override
        public HkInventoryEmailConfig getByPropertyIdAndType(Integer propertyId, Integer category) {
            return getOne(new LambdaQueryWrapper<HkInventoryEmailConfig>().eq(HkInventoryEmailConfig::getPropertyId, propertyId)
                    .eq(HkInventoryEmailConfig::getType, category));
        }

        /**
         * 校验邮件配置是否存在
         *
         * @param id 邮件配置id
         * @return cloud.wconnect.workperformance.entity.hkinventory.HkInventoryEmailConfig
         * @author lichen
         * @date 2025/4/26
         */
        @Override
        public HkInventoryEmailConfig checkExist(Integer id) {
            HkInventoryEmailConfig emailConfig = getById(id);
            if (Objects.isNull(emailConfig)) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_FOUND,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "Housekeeping Inventory Email Config not found, id=" + id);
            }
            return emailConfig;
        }

        /**
         * 校验是否归属于资产
         *
         * @param propertyId  资产id
         * @param emailConfig 邮件配置
         * @return void
         * @author lichen
         * @date 2025/4/26
         */
        @Override
        public void checkBelong(Integer propertyId, HkInventoryEmailConfig emailConfig) {
            if (emailConfig.getPropertyId().compareTo(propertyId) != 0) {
                throw new ForbiddenException(BaseErrorCodeEnum.DATA_FORBIDDEN.getI18nCode(),
                        BaseErrorCodeEnum.DATA_FORBIDDEN.getCode(),
                        MessageFormat.format("Housekeeping Inventory email config not belong property, emailConfigId:{0}, belongPropertyId:{1}, currentPropertyId:{2}",
                                emailConfig.getId(), emailConfig.getPropertyId(), propertyId));
            }
        }

        /**
         * 校验重复
         *
         * @param propertyId 资产id
         * @param type       邮件配置类型
         * @return void
         * @author lichen
         * @date 2025/4/26
         */
        @Override
        public void checkRepeat(Integer propertyId, Integer type) {
            long count = count(new LambdaQueryWrapper<HkInventoryEmailConfig>().eq(HkInventoryEmailConfig::getPropertyId, propertyId)
                    .eq(HkInventoryEmailConfig::getType, type));
            if (count > 0) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_EXISTED,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The Housekeeping Inventory email config already exist, propertyId=" + propertyId + ", type=" + type);
            }
        }

        /**
         * 保存邮件配置
         *
         * @param tenantId       租户id
         * @param propertyId     资产id
         * @param emailConfigDTO 邮件配置DTO
         * @return java.lang.Integer
         * @author lichen
         * @date 2025/4/26
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public Integer save(Integer tenantId, int propertyId, HkInventoryEmailConfigDTO emailConfigDTO) {
            HkInventoryEmailConfig emailConfig = beanMapper.map(emailConfigDTO, HkInventoryEmailConfig.class, config -> {
                config.setTenantId(tenantId);
                config.setPropertyId(propertyId);
            });
            saveOrUpdate(emailConfig);

            if (emailConfigDTO.getId() > 0) {
                emailTargetService.remove(new LambdaQueryWrapper<HkInventoryEmailTarget>()
                        .eq(HkInventoryEmailTarget::getConfigId, emailConfigDTO.getId()));
            }

            List<HkInventoryEmailTarget> targets = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(emailConfigDTO.getToList())) {
                targets.addAll(emailConfigDTO.getToList().stream().map(item -> beanMapper.map(item, HkInventoryEmailTarget.class,
                        target -> {
                            target.setTargetType(EmailConfigCons.TARGET_TYPE_TO);
                            target.setPropertyId(propertyId);
                            target.setConfigId(emailConfig.getId());
                            target.setTenantId(tenantId);
                            target.setUsername(item.getIdentityName());
                        })).toList());
            }
            if (CollectionUtils.isNotEmpty(emailConfigDTO.getCcList())) {
                targets.addAll(emailConfigDTO.getCcList().stream().map(item -> beanMapper.map(item, HkInventoryEmailTarget.class,
                        target -> {
                            target.setTargetType(EmailConfigCons.TARGET_TYPE_CC);
                            target.setPropertyId(propertyId);
                            target.setConfigId(emailConfig.getId());
                            target.setTenantId(tenantId);
                            target.setUsername(item.getIdentityName());
                        })).toList());
            }

            emailTargetService.saveBatch(targets);

            return emailConfig.getId();
        }

        /**
         * 查询邮件配置
         *
         * @param propertyDTO 资产DTO
         * @param type        类型
         * @return cloud.wconnect.workperformance.pojo.dto.hkinventory.HkInventoryEmailConfigDTO
         * @author lichen
         * @date 2025/4/26
         */
        @Override
        public HkInventoryEmailConfigDTO getByPropertyIdAndType(PropertyDTO propertyDTO, int type) {
            //当前上下文语言
            Locale currentThreadLocale = LocaleContextHolder.getLocale();
            //功能名称
            String functionName = i18nMessageUtils.message(FunctionCons.HOUSEKEEPING_INVENTORY, currentThreadLocale);
            //默认主题
            String defaultSubjectI18nCode = HkInventoryNotifyConfigTypeEnum.getDefaultSubjectI18nCode(type);
            String defaultSubject = i18nMessageUtils.message(defaultSubjectI18nCode, currentThreadLocale, functionName,
                    BaseConstant.DATE_FORMAT_YYYY_MM, propertyDTO.getName());
            //查询邮件配置
            HkInventoryEmailConfig emailConfig = getByPropertyIdAndType(propertyDTO.getId(), type);
            //邮件配置为空时，返回默认主题
            if (Objects.isNull(emailConfig)) {
                HkInventoryEmailConfigDTO emailConfigDTO = new HkInventoryEmailConfigDTO();
                emailConfigDTO.setDefaultSubject(defaultSubject);
                emailConfigDTO.setType(type);
                return emailConfigDTO;
            }
            //查询通知对象
            List<HkInventoryEmailTarget> emailTargetList = emailTargetService.listByConfigId(emailConfig.getId());
            //按照用户来源分组
            Map<Integer, List<Integer>> source2IdentityIdList = emailTargetList.stream()
                    .collect(Collectors.groupingBy(HkInventoryEmailTarget::getSource, Collectors.mapping(HkInventoryEmailTarget::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<HkInventoryEmailTargetDTO>> targetsByTargetType = beanMapper.mapList(emailTargetList, HkInventoryEmailTargetDTO.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(HkInventoryEmailTargetDTO::getTargetType));

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