# CompRoomEmailConfigController.java

    package cloud.wconnect.frontoffice.controller.comproom;

    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.CommonFieldI18nConstant;
    import cloud.wconnect.commonlib.cons.EmailConfigCons;
    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.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.service.UserInternalService;
    import cloud.wconnect.commonlib.service.UsergroupInternalService;
    import cloud.wconnect.commonlib.util.I18nMessageUtils;
    import cloud.wconnect.frontoffice.cons.comproom.CompRoomNotifyConfigTypeEnum;
    import cloud.wconnect.frontoffice.entity.comproom.CompRoomEmailConfig;
    import cloud.wconnect.frontoffice.pojo.dto.comproom.CrEmailConfigDTO;
    import cloud.wconnect.frontoffice.pojo.dto.comproom.CrEmailTargetDTO;
    import cloud.wconnect.frontoffice.service.comproom.ICompRoomEmailConfigService;
    import com.google.common.collect.ImmutableMap;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Sets;
    import org.apache.commons.collections4.CollectionUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;

    import jakarta.validation.Valid;

    import java.text.MessageFormat;
    import java.util.*;
    import java.util.stream.Collectors;

    /**
     * <p>
     * Comp Room 功能的邮件配置表 前端控制器
     * </p>
     *
     * @author lichen
     * @since 2023-03-28
     */
    @RestController
    @RequestMapping("/comp-room/email-config")
    public class CompRoomEmailConfigController {

        @Autowired
        private ICompRoomEmailConfigService 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
         * @author lichen
         * @date 2024/3/14
         */
        @ApiId(206)
        @PostMapping
        public Map save(String property, @RequestBody @Valid CrEmailConfigDTO emailConfigDTO) {
            int propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);

            //校验审批类型的邮件配置开关必须是开启
            if (CompRoomNotifyConfigTypeEnum.WAIT_FOR_APPROVING.getType() == emailConfigDTO.getType()
                    && !emailConfigDTO.getStatus()) {
                throw new BadRequestException(CommonErrorI18nConstant.MUST_IN_LIST,
                        i18nMessageUtils.getErrorParamMapNeedTranslate(CommonFieldI18nConstant.STATUS, CommonFieldI18nConstant.OPEN),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The status of the approval type must be Enabled");
            }

            //校验通知对象是否重复以及存在
            checkEmailTarget(propertyDTO, emailConfigDTO);

            if (emailConfigDTO.getId() > 0) {
                //校验是否存在以及是否归属于当前资产
                CompRoomEmailConfig emailConfig = checkExistAndBelong(emailConfigDTO.getId(), propertyDTO.getId());
                //校验type不能修改
                if (!emailConfig.getType().equals(emailConfigDTO.getType())) {
                    throw new BadRequestException(CommonErrorI18nConstant.CANNOT_MODIFIED,
                            i18nMessageUtils.getErrorParamMapNeedTranslate("emailConfigType"),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The comp room email config type cannot be modified");
                }
            } else {
                //校验资产是否已经配置邮件
                emailConfigService.checkSole(propertyDTO.getId(), emailConfigDTO.getType());
            }
            //保存邮件配置
            Integer configId = emailConfigService.save(propertyDTO.getId(), emailConfigDTO);
            return ImmutableMap.of("id", configId);
        }

        /**
         * 查询邮件配置
         *
         * @param property 资产标识
         * @param type     类型 1：send Comp Room 2：Report Missed
         * @return cloud.wconnect.frontoffice.pojo.dto.comproom.CrEmailConfigDTO
         * @author lichen
         * @date 2024/3/14
         */
        @ApiId(205)
        @GetMapping
        public CrEmailConfigDTO get(String property, @RequestParam(name = "type") Integer type) {
            List<Integer> typeList = Arrays.stream(CompRoomNotifyConfigTypeEnum.values()).map(CompRoomNotifyConfigTypeEnum::getType).toList();
            if (!typeList.contains(type)) {
                throw new BadRequestException(CommonErrorI18nConstant.MUST_IN_LIST,
                        i18nMessageUtils.getErrorParamMapNeedTranslate("type", typeList),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The type must be 1:send Comp Room 2:Report Missed");
            }
            int propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            return emailConfigService.getByPropertyIdAndType(propertyDTO, type);
        }

        /**
         * 校验是否存在以及是否归属于当前资产
         *
         * @param id         邮件配置主键ID
         * @param propertyId 资产Id
         * @return cloud.wconnect.frontoffice.entity.comproom.CompRoomEmailConfig
         * @author lichen
         * @date 2024/3/14
         */
        private CompRoomEmailConfig checkExistAndBelong(Integer id, Integer propertyId) {
            CompRoomEmailConfig emailConfig = emailConfigService.getById(id);
            if (Objects.isNull(emailConfig)) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_FOUND,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "Comp Room Email Config not found, id=" + id);
            }
            if (emailConfig.getPropertyId().compareTo(propertyId) != 0) {
                throw new ForbiddenException(BaseErrorCodeEnum.DATA_FORBIDDEN.getI18nCode(),
                        BaseErrorCodeEnum.DATA_FORBIDDEN.getCode(),
                        MessageFormat.format("comp room email config not belong property,emailConfigId:{0}, belongPropertyId:{1}, currentPropertyId:{2}",
                                id, emailConfig.getPropertyId(), propertyId));
            }
            return emailConfig;
        }

        /**
         * 校验通知对象是否重复、是否存在
         *
         * @param propertyDTO    资产DTO
         * @param emailConfigDTO 邮件配置DTO
         * @return void
         * @author lichen
         * @date 2024/3/14
         */
        private void checkEmailTarget(PropertyDTO propertyDTO, CrEmailConfigDTO emailConfigDTO) {
            List<CrEmailTargetDTO> toList = emailConfigDTO.getToList();
            List<CrEmailTargetDTO> ccList = emailConfigDTO.getCcList();

            List<CrEmailTargetDTO> 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(CrEmailTargetDTO::getSource, Collectors.mapping(CrEmailTargetDTO::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(CrEmailTargetDTO::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(propertyDTO.getTenantId(), 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(propertyDTO.getTenantId(), propertyDTO.getId(), 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");
                }
            }
        }
    }