# CbCaseEmailConfigController.java

    package cloud.wconnect.finance.controller.chargeback;

    import cloud.wconnect.commonlib.annotation.ApiId;
    import cloud.wconnect.commonlib.component.BeanMapper;
    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.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.finance.cons.chargeback.StageEnum;
    import cloud.wconnect.finance.pojo.dto.chargeback.CbCaseEmailConfigDTO;
    import cloud.wconnect.finance.pojo.dto.chargeback.CbCaseEmailTargetDTO;
    import cloud.wconnect.finance.service.chargeback.ICbCaseEmailConfigService;
    import cloud.wconnect.finance.service.chargeback.ICbCaseEmailTargetService;
    import com.google.common.collect.ImmutableMap;
    import com.google.common.collect.Lists;
    import jakarta.validation.Valid;
    import org.apache.commons.collections.CollectionUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;

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

    /**
     * <p>
     * case 邮件配置表 前端控制器
     * </p>
     *
     * @author yyt
     * @since 2023-08-22
     */
    @RestController
    @RequestMapping("/charge-back/email-config")
    public class CbCaseEmailConfigController {

        @Autowired
        private SessionContext sessionContext;
        @Autowired
        private ICbCaseEmailConfigService cbCaseEmailConfigService;
        @Autowired
        private UsergroupInternalService usergroupInternalService;
        @Autowired
        private UserInternalService userInternalService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        /**
         * 获取邮件配置
         *
         * @param property 资产标识
         * @param type     邮件配置类型 (1：报告缺失，2：超期 replay by 通知，3：初始阶段审批通知主题配置，4：酒店表态阶段审批通知主题配置，
         *                 5：overdue 阶段审批通知主题配置，6：portal 阶段审批通知主题配置，7：loss-adj 阶段审批通知主题配置，8：last 阶段审批通知主题配置)
         * @return 邮件配置
         * @author yyt
         * @date 2023/8/24
         */
        @ApiId(594)
        @GetMapping
        public CbCaseEmailConfigDTO getEmailConfigDTO(String property, @RequestParam int type) {
            return cbCaseEmailConfigService.getEmailConfigDTO(sessionContext.getTenantSymbolBO().getId(), sessionContext.getPropertyId(property), type);
        }

        /**
         * 保存邮件配置
         *
         * @param property  资产标识
         * @param configDTO 邮件配置
         * @return 配置 id
         * @author yyt
         * @date 2023/8/24
         */
        @ApiId(595)
        @PostMapping
        public Map save(String property, @Valid @RequestBody CbCaseEmailConfigDTO configDTO) {
            if (Arrays.stream(StageEnum.values()).map(item -> cbCaseEmailConfigService.getTypeForStage(item.getCode())).toList()
                    .contains(configDTO.getType()) && !configDTO.getStatus()) {
                throw new BadRequestException(CommonErrorI18nConstant.STATUS_MUST_BE,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate("true"),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "the status must be true");
            }

            Integer propertyId = sessionContext.getPropertyId(property);
            // 检查目标（用户/用户组）是否存在
            checkTargetExist(propertyId, configDTO.getToList(), configDTO.getCcList());

            return ImmutableMap.of("id", cbCaseEmailConfigService.save(propertyId, configDTO));
        }

        /**
         * 检查目标（用户/用户组）是否存在
         *
         * @param propertyId 资产 id
         * @param toList     to
         * @param ccList     cc
         * @author yyt
         * @date 2024/3/12
         **/
        private void checkTargetExist(Integer propertyId, List<CbCaseEmailTargetDTO> toList, List<CbCaseEmailTargetDTO> ccList) {
            List<Integer> userIds = Lists.newArrayList();
            List<Integer> userGroupIds = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(toList)) {
                Map<Integer, List<Integer>> targetIdByUserSource = toList.stream().collect(Collectors.groupingBy(CbCaseEmailTargetDTO::getSource,
                        Collectors.collectingAndThen(Collectors.toList(), item -> item.stream().map(CbCaseEmailTargetDTO::getIdentityId).toList())));
                userIds.addAll(targetIdByUserSource.getOrDefault(EmailConfigCons.SOURCE_USER, Collections.emptyList()));
                userGroupIds.addAll(targetIdByUserSource.getOrDefault(EmailConfigCons.SOURCE_USERGROUP, Collections.emptyList()));
            }
            if (CollectionUtils.isNotEmpty(ccList)) {
                Map<Integer, List<Integer>> targetIdByUserSource = ccList.stream().collect(Collectors.groupingBy(CbCaseEmailTargetDTO::getSource,
                        Collectors.collectingAndThen(Collectors.toList(), item -> item.stream().map(CbCaseEmailTargetDTO::getIdentityId).toList())));
                userIds.addAll(targetIdByUserSource.getOrDefault(EmailConfigCons.SOURCE_USER, Collections.emptyList()));
                userGroupIds.addAll(targetIdByUserSource.getOrDefault(EmailConfigCons.SOURCE_USERGROUP, Collections.emptyList()));
            }
            Integer tenantId = sessionContext.getTenantSymbolBO().getId();
            if (CollectionUtils.isNotEmpty(userIds)) {
                List<UserDTO> users = userInternalService.getUsers(tenantId, userIds);
                if (users.size() != userIds.size()) {
                    throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_EXIST,
                            i18nMessageUtils.getErrorParamMapNeedTranslate(CommonFieldI18nConstant.USER),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "the user is not found");
                }
            }
            if (CollectionUtils.isNotEmpty(userGroupIds)) {
                List<UsergroupDTO> usergroups = usergroupInternalService.getUsergroups(tenantId, propertyId, userGroupIds);
                if (usergroups.size() != userGroupIds.size()) {
                    throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_EXIST,
                            i18nMessageUtils.getErrorParamMapNeedTranslate(CommonFieldI18nConstant.USER_GROUP),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "the userGroup is not found");
                }
            }
        }

    }