# WalkRoomApproveConfigController.java

    package cloud.wconnect.frontoffice.controller.walkroomrequest;

    import cloud.wconnect.commonlib.annotation.ApiId;
    import cloud.wconnect.commonlib.component.SessionContext;
    import cloud.wconnect.commonlib.cons.BaseConstant;
    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.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.RoleInternalService;
    import cloud.wconnect.commonlib.service.UserInternalService;
    import cloud.wconnect.commonlib.service.UsergroupInternalService;
    import cloud.wconnect.commonlib.util.I18nMessageUtils;
    import cloud.wconnect.frontoffice.entity.walkroomrequest.WalkRoomApproveLevel;
    import cloud.wconnect.frontoffice.pojo.dto.walkroomrequest.WalkRoomApproveCCDTO;
    import cloud.wconnect.frontoffice.pojo.dto.walkroomrequest.WalkRoomApproveLevelDTO;
    import cloud.wconnect.frontoffice.pojo.dto.walkroomrequest.WalkRoomApproveUserDTO;
    import cloud.wconnect.frontoffice.service.walkroomrequest.IWalkRoomApproveConfigService;
    import cloud.wconnect.frontoffice.service.walkroomrequest.IWalkRoomApproveLevelService;
    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>
     * Walk Room Requests 功能的审批配置 前端控制器
     * </p>
     *
     * @author lichen
     * @date 2023/7/11
     */
    @RestController
    @RequestMapping("/walk-room-request/approve-config")
    public class WalkRoomApproveConfigController {

        @Autowired
        private IWalkRoomApproveLevelService approveLevelService;
        @Autowired
        private IWalkRoomApproveConfigService approveConfigService;
        @Autowired
        private RoleInternalService roleInternalService;
        @Autowired
        private SessionContext sessionContext;
        @Autowired
        private UserInternalService userInternalService;
        @Autowired
        private UsergroupInternalService usergroupInternalService;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        /**
         * 查询审批级别
         *
         * @param property 资产标识
         * @param type     审批层级类型 1:Sent 2:Receive
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.dto.walkroom.WalkRoomApproveLevelDTO>
         * @author lichen
         * @date 2023/7/11
         */
        @ApiId(458)
        @GetMapping
        public List<WalkRoomApproveLevelDTO> list(String property, @RequestParam(name = "type") Integer type) {
            if (!Lists.newArrayList(1, 2).contains(type)) {
                throw new BadRequestException(CommonErrorI18nConstant.MUST_IN_LIST,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate("type", List.of(1, 2)),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The type must be 1:Sent 2: Receive");
            }
            int propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            return approveLevelService.list(propertyDTO, type);
        }

        /**
         * 查询审批角色用户
         *
         * @param property 资产标识
         * @return java.util.List<cloud.wconnect.commonlib.pojo.dto.UserDTO>
         * @author lichen
         * @date 2023/7/11
         */
        @ApiId(459)
        @GetMapping("/approveUser")
        public List<UserDTO> approveUser(String property) {
            int propertyId = sessionContext.getPropertyId(property);
            Integer tenantId = sessionContext.getTenantSymbolBO().getId();
            return roleInternalService.getUsers(tenantId, propertyId, BaseConstant.WALK_ROOM_APPROVE_ROLE);
        }

        /**
         * 保存审批级别
         *
         * @param property        资产标识
         * @param approveLevelDTO 审批级别dto
         * @return java.util.Map
         * @author lichen
         * @date 2023/7/11
         */
        @ApiId(460)
        @PostMapping
        public Map save(String property, @Valid @RequestBody WalkRoomApproveLevelDTO approveLevelDTO) {
            int propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);

            //获取当前保存的审核用户集合
            List<Integer> userIds = approveLevelDTO.getUsers().stream().map(WalkRoomApproveUserDTO::getId).collect(Collectors.toList());
            //校验用户不能重复
            if (Sets.newHashSet(userIds).size() != userIds.size()) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_CANNOT_REPEAT,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate("userIds"),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "approve user cannot repeat");
            }

            //校验抄送人是否重复 且 是否存在
            checkApproverAndCC(propertyDTO, userIds, approveLevelDTO.getCcList());

            //审批级别id
            Long id = approveLevelDTO.getId();
            if (id > BaseConstant.LONG_ZERO) {
                // 校验审批级别是否存在 且 归属于当前资产
                WalkRoomApproveLevel oriApprove = checkIsExistAndAffiliation(id, propertyId);
                // 校验用户是否重复
                approveConfigService.checkUserRepeat(propertyId, oriApprove.getType(), userIds, id);

                approveLevelDTO.setApproveIndex(oriApprove.getApproveIndex());
                approveLevelDTO.setType(oriApprove.getType());
                approveLevelDTO.setPropertyId(propertyId);
                //修改
                return approveLevelService.update(oriApprove, approveLevelDTO);
            } else {
                // 校验用户是否重复
                approveConfigService.checkUserRepeat(propertyId, approveLevelDTO.getType(), userIds, id);
                approveLevelDTO.setPropertyId(propertyId);
                return approveLevelService.insert(approveLevelDTO);
            }
        }

        /**
         * 删除审批级别
         *
         * @param property 资产标识
         * @param id       审批级别id
         * @return java.util.Map
         * @author lichen
         * @date 2023/7/11
         */
        @ApiId(461)
        @DeleteMapping
        public Map remove(String property, @RequestParam(name = "id") Long id) {
            int propertyId = sessionContext.getPropertyId(property);
            //校验审批级别是否存在 且 归属于当前资产
            WalkRoomApproveLevel walkRoomApproveLevel = checkIsExistAndAffiliation(id, propertyId);
            //删除审批级别
            approveLevelService.remove(walkRoomApproveLevel);
            return Collections.emptyMap();
        }

        /**
         * 校验审批级别是否存在 且 归属于当前资产
         *
         * @param id         审批级别id
         * @param propertyId 资产id
         * @return cloud.wconnect.frontoffice.entity.walkroom.WalkRoomApproveLevel
         * @author lichen
         * @date 2023/7/11
         */
        private WalkRoomApproveLevel checkIsExistAndAffiliation(Long id, Integer propertyId) {
            WalkRoomApproveLevel byId = approveLevelService.getById(id);
            if (Objects.isNull(byId)) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_FOUND,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "Walk Room Requests Approve Config not found");
            }
            if (byId.getPropertyId().compareTo(propertyId) != 0) {
                throw new ForbiddenException(BaseErrorCodeEnum.DATA_FORBIDDEN.getI18nCode(),
                        BaseErrorCodeEnum.DATA_FORBIDDEN.getCode(),
                        MessageFormat.format("WalkRoomApproveLevel not belong current property, approveLevelId:{0}, belongPropertyId:{1}, currentPropertyId:{2}",
                                id, byId.getPropertyId(), propertyId));
            }
            return byId;
        }

        /**
         * 校验审批人和抄送对象是否存在
         *
         * @param propertyDTO  资产DTO
         * @param approverList 审批人集合
         * @param ccList       抄送人集合
         * @return void
         * @author lichen
         * @date 2024/3/11
         */
        private void checkApproverAndCC(PropertyDTO propertyDTO, List<Integer> approverList, List<WalkRoomApproveCCDTO> ccList) {
            //按照用户来源分组
            Map<Integer, List<Integer>> source2IdentityIdList = ccList.stream()
                    .collect(Collectors.groupingBy(WalkRoomApproveCCDTO::getSource, Collectors.mapping(WalkRoomApproveCCDTO::getIdentityId, Collectors.toList())));
            List<Integer> userIdsByCC = source2IdentityIdList.getOrDefault(EmailConfigCons.SOURCE_USER, Collections.emptyList());
            List<Integer> usergroupIds = source2IdentityIdList.getOrDefault(EmailConfigCons.SOURCE_USERGROUP, Collections.emptyList());

            //校验是否重复
            if (userIdsByCC.size() != Sets.newHashSet(userIdsByCC).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 = ccList.stream().filter(cc -> cc.getSource() == EmailConfigCons.SOURCE_MANUAL)
                    .map(WalkRoomApproveCCDTO::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");
            }

            //用户集合
            Set<Integer> allUserIds = new HashSet<>();
            allUserIds.addAll(approverList);
            allUserIds.addAll(userIdsByCC);
            List<UserDTO> allUsers = userInternalService.getUsers(propertyDTO.getTenantId(), allUserIds);
            //校验是否存在
            if (allUserIds.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 (usergroups.size() != usergroupIds.size()) {
                    throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_EXIST,
                            i18nMessageUtils.getErrorParamMapNotNeedTranslate("userGroupId"),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The user group not exist");
                }
            }
        }

    }