# HkInventoryEmailConfigController.java

    package cloud.wconnect.workperformance.controller.hkinventory;

    import cloud.wconnect.commonlib.annotation.ApiId;
    import cloud.wconnect.commonlib.component.SessionContext;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.CommonErrorI18nConstant;
    import cloud.wconnect.commonlib.cons.EmailConfigCons;
    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.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.service.UserInternalService;
    import cloud.wconnect.commonlib.service.UsergroupInternalService;
    import cloud.wconnect.commonlib.util.I18nMessageUtils;
    import cloud.wconnect.workperformance.entity.hkinventory.HkInventoryEmailConfig;
    import cloud.wconnect.workperformance.pojo.dto.hkinventory.HkInventoryEmailConfigDTO;
    import cloud.wconnect.workperformance.pojo.dto.hkinventory.HkInventoryEmailTargetDTO;
    import cloud.wconnect.workperformance.service.hkinventory.IHkInventoryEmailConfigService;
    import com.google.common.collect.ImmutableMap;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Sets;
    import jakarta.validation.Valid;
    import org.apache.commons.collections4.CollectionUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;

    import java.util.Collections;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;

    /**
     * Housekeeping Inventory邮件配置控制层
     *
     * @author lichen
     * @date 2025/4/26
     */
    @RestController
    @RequestMapping("/hk-inventory/email-config")
    public class HkInventoryEmailConfigController {

        @Autowired
        private IHkInventoryEmailConfigService emailConfigService;
        @Autowired
        private SessionContext sessionContext;
        @Autowired
        private UserInternalService userInternalService;
        @Autowired
        private UsergroupInternalService usergroupInternalService;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        /**
         * 保存邮件配置
         *
         * @param property       资产标识
         * @param emailConfigDTO 邮件配置DTO
         * @return java.util.Map<java.lang.String, java.lang.Integer>
         * @author lichen
         * @date 2025/4/26
         */
        @ApiId(1410)
        @PostMapping
        public Map<String, Integer> save(String property, @RequestBody @Valid HkInventoryEmailConfigDTO emailConfigDTO) {
            int propertyId = sessionContext.getPropertyId(property);
            Integer tenantId = sessionContext.getTenantSymbolBO().getId();
            //校验通知对象是否重复以及存在
            checkEmailTarget(tenantId, propertyId, emailConfigDTO);
            if (emailConfigDTO.getId() > 0) {
                //校验是否存在
                HkInventoryEmailConfig oriEmailConfig = emailConfigService.checkExist(emailConfigDTO.getId());
                //校验是否归属于当前资产
                emailConfigService.checkBelong(propertyId, oriEmailConfig);
                //校验type不能修改
                if (!oriEmailConfig.getType().equals(emailConfigDTO.getType())) {
                    throw new BadRequestException(CommonErrorI18nConstant.CANNOT_MODIFIED,
                            i18nMessageUtils.getErrorParamMapNotNeedTranslate("emailConfigType"),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The Housekeeping Inventory email config type cannot be modified");
                }
            } else {
                //校验资产是否已经配置邮件
                emailConfigService.checkRepeat(propertyId, emailConfigDTO.getType());
            }
            //保存邮件配置
            return ImmutableMap.of("id", emailConfigService.save(tenantId, propertyId, emailConfigDTO));
        }

        /**
         * 查询邮件配置
         *
         * @param property 资产
         * @param type     邮件配置类型
         * @return cloud.wconnect.workperformance.pojo.dto.hkinventory.HkInventoryEmailConfigDTO
         * @author lichen
         * @date 2025/4/26
         */
        @ApiId(1409)
        @GetMapping
        public HkInventoryEmailConfigDTO get(String property, @RequestParam(name = "type") Integer type) {
            int propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            return emailConfigService.getByPropertyIdAndType(propertyDTO, type);
        }

        /**
         * 校验通知对象是否合法
         *
         * @param tenantId       租户id
         * @param propertyId     资产id
         * @param emailConfigDTO 邮件配置DTO
         * @return void
         * @author lichen
         * @date 2025/4/26
         */
        private void checkEmailTarget(Integer tenantId, int propertyId, HkInventoryEmailConfigDTO emailConfigDTO) {
            List<HkInventoryEmailTargetDTO> toList = emailConfigDTO.getToList();
            List<HkInventoryEmailTargetDTO> ccList = emailConfigDTO.getCcList();

            List<HkInventoryEmailTargetDTO> allNotifyList = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(toList)) {
                allNotifyList.addAll(toList);
            }
            if (CollectionUtils.isNotEmpty(ccList)) {
                allNotifyList.addAll(ccList);
            }
            if (CollectionUtils.isEmpty(allNotifyList)) return;

            //按照用户来源分组
            Map<Integer, List<Integer>> source2IdentityIdList = allNotifyList.stream()
                    .collect(Collectors.groupingBy(HkInventoryEmailTargetDTO::getSource, Collectors.mapping(HkInventoryEmailTargetDTO::getIdentityId, Collectors.toList())));
            List<Integer> userIds = source2IdentityIdList.getOrDefault(EmailConfigCons.SOURCE_USER, Collections.emptyList());
            List<Integer> usergroupIds = source2IdentityIdList.getOrDefault(EmailConfigCons.SOURCE_USERGROUP, Collections.emptyList());

            //校验是否重复
            if (userIds.size() != Sets.newHashSet(userIds).size()) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_CANNOT_REPEAT,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate("userIds"),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "user cannot repeat");
            }
            if (usergroupIds.size() != Sets.newHashSet(usergroupIds).size()) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_CANNOT_REPEAT,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate("userGroupIds"),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "usergroup cannot repeat");
            }
            List<String> manualEmails = allNotifyList.stream().filter(item -> item.getSource() == EmailConfigCons.SOURCE_MANUAL)
                    .map(HkInventoryEmailTargetDTO::getEmail).collect(Collectors.toList());
            if (manualEmails.size() != Sets.newHashSet(manualEmails).size()) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_CANNOT_REPEAT,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate("manualEmails"),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "manual email cannot repeat");
            }

            //用户集合
            if (CollectionUtils.isNotEmpty(userIds)) {
                List<UserDTO> allUsers = userInternalService.getUsers(tenantId, userIds);
                //校验是否存在
                if (userIds.size() != allUsers.size()) {
                    throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_EXIST,
                            i18nMessageUtils.getErrorParamMapNotNeedTranslate("userId"),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The user not exist");
                }
            }

            //校验用户组是否存在
            if (CollectionUtils.isNotEmpty(usergroupIds)) {
                List<UsergroupDTO> usergroups = usergroupInternalService.getUsergroups(tenantId, propertyId, usergroupIds);
                if (usergroupIds.size() != usergroups.size()) {
                    throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_EXIST,
                            i18nMessageUtils.getErrorParamMapNotNeedTranslate("userGroupId"),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The user group not exist");
                }
            }
        }

    }