# ScheduleEmailConfigController.java

    package cloud.wconnect.workperformance.controller.schedule;

    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.pojo.dto.UserDTO;
    import cloud.wconnect.commonlib.pojo.dto.UsergroupDTO;
    import cloud.wconnect.commonlib.pojo.dto.group.Edition;
    import cloud.wconnect.commonlib.service.UserInternalService;
    import cloud.wconnect.commonlib.service.UsergroupInternalService;
    import cloud.wconnect.commonlib.util.I18nMessageUtils;
    import cloud.wconnect.workperformance.pojo.dto.schedule.ScheduleEmailConfigDTO;
    import cloud.wconnect.workperformance.pojo.dto.schedule.ScheduleEmailConfigTargetDTO;
    import cloud.wconnect.workperformance.pojo.group.Addition;
    import cloud.wconnect.workperformance.pojo.query.schedule.ScheduleEmailQuery;
    import cloud.wconnect.workperformance.service.schedule.IScheduleEmailConfigService;
    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.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.*;

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

    /**
     * 控制层：Schedule Email Config
     *
     * @author yyt
     * 2023/7/3
     */
    @RestController
    @RequestMapping("/schedule/email")
    public class ScheduleEmailConfigController {

        @Autowired
        private SessionContext sessionContext;
        @Autowired
        private IScheduleEmailConfigService scheduleEmailConfigService;
        @Autowired
        private UsergroupInternalService usergroupInternalService;
        @Autowired
        private UserInternalService userInternalService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        /**
         * 获取邮件配置列表
         *
         * @param property 资产标识
         * @param query    查询条件
         * @return 邮件配置列表
         * @author yyt
         * @date 2023/7/3
         */
        @ApiId(412)
        @GetMapping
        public ScheduleEmailConfigDTO getEmailConfig(String property, @Valid ScheduleEmailQuery query) {
            return scheduleEmailConfigService.getDTO(sessionContext.getPropertyId(property), query);
        }

        /**
         * 新增、修改邮件配置
         *
         * @param property       资产标识
         * @param emailConfigDTO 邮件配置信息
         * @return 通知 id
         * @author yyt
         * @date 2023/7/3
         */
        @ApiId(413)
        @PostMapping()
        public Map<String, Object> saveEmailConfig(String property, @Validated(Addition.class) @RequestBody ScheduleEmailConfigDTO emailConfigDTO) {
            Integer propertyId = sessionContext.getPropertyId(property);

            // 检查目标（用户/用户组）是否存在
            checkTargetExist(propertyId, emailConfigDTO.getToList(), emailConfigDTO.getCcList());

            return ImmutableMap.of("id", scheduleEmailConfigService.saveEmail(propertyId, emailConfigDTO, sessionContext.getLoginUserId()));
        }

        /**
         * 新增、修改 申请部门权限 邮件配置（此接口供角色管理员使用）
         *
         * @param property       资产标识
         * @param emailConfigDTO 邮件配置信息
         * @return 通知 id
         * @author yyt
         * @date 2023/7/3
         */
        @ApiId(414)
        @PostMapping("/permission-config")
        public Map<String, Object> saveDepartmentPermissionEmailConfig(String property, @Validated(Edition.class) @RequestBody ScheduleEmailConfigDTO emailConfigDTO) {
            Integer propertyId = sessionContext.getPropertyId(property);

            // 检查目标（用户/用户组）是否存在
            checkTargetExist(propertyId, emailConfigDTO.getToList(), emailConfigDTO.getCcList());

            return ImmutableMap.of("id", scheduleEmailConfigService.saveEmail(propertyId, emailConfigDTO, sessionContext.getLoginUserId()));
        }

        /**
         * 检查目标（用户/用户组）是否存在
         *
         * @param propertyId 资产 id
         * @param toList     选择目标
         * @param ccList     选择目标
         * @author yyt
         * @date 2024/3/11
         **/
        private void checkTargetExist(Integer propertyId, List<ScheduleEmailConfigTargetDTO> toList, List<ScheduleEmailConfigTargetDTO> 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(ScheduleEmailConfigTargetDTO::getSource,
                        Collectors.collectingAndThen(Collectors.toList(), item -> item.stream().map(ScheduleEmailConfigTargetDTO::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(ScheduleEmailConfigTargetDTO::getSource,
                        Collectors.collectingAndThen(Collectors.toList(), item -> item.stream().map(ScheduleEmailConfigTargetDTO::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");
                }
            }
        }

    }