# CompRoomWidgetController.java

    package cloud.wconnect.frontoffice.controller.comproom;

    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.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.ForbiddenException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.I18nMessageUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.frontoffice.cons.ApproveStatusEnum;
    import cloud.wconnect.frontoffice.cons.comproom.CompRoomNotifyConfigTypeEnum;
    import cloud.wconnect.frontoffice.entity.comproom.CompRoomNotifyRule;
    import cloud.wconnect.frontoffice.pojo.query.comproom.PropertyCheckInNumQuery;
    import cloud.wconnect.frontoffice.pojo.query.comproom.PropertyCheckInNumTrendQuery;
    import cloud.wconnect.frontoffice.pojo.vo.comproom.CompRoomToDoVO;
    import cloud.wconnect.frontoffice.pojo.vo.comproom.PropertyCheckInNumTrendVO;
    import cloud.wconnect.frontoffice.pojo.vo.comproom.PropertyCheckInNumVO;
    import cloud.wconnect.frontoffice.service.comproom.ICompRoomNotifyRuleService;
    import cloud.wconnect.frontoffice.service.comproom.IRqCompRoomFormService;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.ImmutableMap;
    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.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;

    import jakarta.validation.Valid;

    import java.text.MessageFormat;
    import java.time.LocalDate;
    import java.time.temporal.ChronoUnit;
    import java.util.Collections;
    import java.util.List;
    import java.util.Map;

    /**
     * 组件控制层
     *
     * @author lichen
     * @date 2023/12/12
     */
    @RestController
    @RequestMapping("comp-room/widget")
    public class CompRoomWidgetController {

        @Autowired
        private SessionContext sessionContext;
        @Autowired
        private IRqCompRoomFormService compRoomService;
        @Autowired
        private ICompRoomNotifyRuleService notifyRuleService;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        /**
         * 统计代办
         *
         * @param property 资产标识
         * @return cloud.wconnect.frontoffice.pojo.vo.comproom.CompRoomToDoVO
         * @author lichen
         * @date 2023/12/12
         */
        @ApiId(990)
        @GetMapping("/statistics/to-do")
        public CompRoomToDoVO statisticsToDo(String property) {
            int propertyId = sessionContext.getPropertyId(property);
            int loginUserId = sessionContext.getLoginUserId();

            CompRoomToDoVO toDoVO = new CompRoomToDoVO();

            //查询待当前登录人审批的数量
            Long waitApprovalTotal = compRoomService.getWaitApprovalTotalByApprover(propertyId, loginUserId);
            toDoVO.setWaitApprovalTotal(waitApprovalTotal);

            //查询创建人等于当前登录人 且 状态等于审批中的数量
            Long approvingTotal = compRoomService.getCountByCreatedByAndApproveStatus(propertyId, loginUserId, ApproveStatusEnum.APPROVEING.getStatus());
            toDoVO.setApprovingTotal(approvingTotal);

            return toDoVO;
        }

        /**
         * 统计当前在住的免费房数量
         *
         * @param property 资产标识
         * @return java.util.Map
         * @author lichen
         * @date 2023/12/12
         */
        @ApiId(991)
        @GetMapping("/statistics/in-live")
        public Map<String, Long> statisticsInLive(String property) {
            int propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            //查询通知规则
            CompRoomNotifyRule notifyRule = notifyRuleService.getByPropertyIdAndTypeOrDefault(propertyDTO.getId(),
                    CompRoomNotifyConfigTypeEnum.COMP_ROOM_CHECK_IN.getType());
            //查询在住的免费房
            List<Integer> approveStatusList = JsonUtils.convertStringToList(objectMapper, notifyRule.getRule(), Integer.class);

            // 查询在住的免费房数量
            long count = compRoomService.countInHouse(propertyDTO, approveStatusList);
            return ImmutableMap.of("total", count);
        }

        /**
         * 统计多资产免费房入住的数量
         *
         * @param query 查询对象
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.vo.comproom.PropertyCheckInNumVO>
         * @author lichen
         * @date 2023/12/12
         */
        @ApiId(992)
        @GetMapping("/statistics/property")
        public List<PropertyCheckInNumVO> statisticsProperty(@Valid PropertyCheckInNumQuery query) {
            List<Integer> hasPermissionPropertyIds = sessionContext.getPropertyIds();
            //校验用户是否有权限查询这些资产的数据
            List<Integer> propertyIds = query.getPropertyIds();
            if (propertyIds.stream().anyMatch(propertyId -> !hasPermissionPropertyIds.contains(propertyId))) {
                propertyIds.removeAll(hasPermissionPropertyIds);
                throw new ForbiddenException(BaseErrorCodeEnum.DATA_FORBIDDEN.getI18nCode(), BaseErrorCodeEnum.DATA_FORBIDDEN.getCode(),
                        MessageFormat.format("Users do not have permission to query data on these property, not have permission propertyIds:{0}",
                                propertyIds.toString()));
            }

            if (query.getPropertyIds().size() != Sets.newHashSet(query.getPropertyIds()).size()) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_CANNOT_REPEAT,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate("propertyIds"),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The propertyIds cannot repeat");
            }

            if (query.getEndDate() < query.getStartDate()) {
                throw new BadRequestException(CommonErrorI18nConstant.START_DATE_CANNOT_GREATER_THAN_END_DATE,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The endDate must be greater than or equal to the startDate");
            }

            LocalDate startDate = DateTimeUtils.strToLocalDate(query.getStartDate().toString(), BaseConstant.DATE_FORMAT_YYYYMMDD);
            LocalDate endDate = DateTimeUtils.strToLocalDate(query.getEndDate().toString(), BaseConstant.DATE_FORMAT_YYYYMMDD);
            if (ChronoUnit.DAYS.between(startDate, endDate) > 366) {
                throw new BadRequestException(CommonErrorI18nConstant.SELECT_DATE_LIMIT,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate("366"),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The time span cannot exceed 1 year");
            }

            //有效的资产
            List<PropertyDTO> propertyDTOList = propertyI18nRedisService.list(propertyIds);

            //查询资产激活的免费房
            return compRoomService.listPropertyActiveCompRoom(query.getStartDate(), query.getEndDate(), propertyDTOList);
        }

        /**
         * 统计多资产免费房入住的数量趋势
         *
         * @param query 查询对象
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.vo.comproom.PropertyCheckInNumTrendVO>
         * @author lichen
         * @date 2023/12/12
         */
        @ApiId(993)
        @GetMapping("/statistics/property/trend")
        public List<PropertyCheckInNumTrendVO> statisticsPropertyTrend(@Valid PropertyCheckInNumTrendQuery query) {
            List<Integer> hasPermissionPropertyIds = sessionContext.getPropertyIds();
            //校验用户是否有权限查询这些资产的数据
            List<Integer> propertyIds = query.getPropertyIds();
            if (propertyIds.stream().anyMatch(propertyId -> !hasPermissionPropertyIds.contains(propertyId))) {
                propertyIds.removeAll(hasPermissionPropertyIds);
                throw new ForbiddenException(BaseErrorCodeEnum.DATA_FORBIDDEN.getI18nCode(), BaseErrorCodeEnum.DATA_FORBIDDEN.getCode(),
                        MessageFormat.format("Users do not have permission to query data on these property, not have permission propertyIds:{0}",
                                propertyIds.toString()));
            }

            if (query.getPropertyIds().size() != Sets.newHashSet(query.getPropertyIds()).size()) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_CANNOT_REPEAT,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate("propertyIds"),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The propertyIds cannot repeat");
            }

            //校验时间跨度
            checkSpan(query.getUnit(),query.getSpan());

            //有效的资产
            List<PropertyDTO> propertyDTOList = propertyI18nRedisService.list(propertyIds);

            if(CollectionUtils.isEmpty(propertyDTOList)) return Collections.emptyList();

            //查询多资产【免费房入住数量】的趋势
            return compRoomService.listPropertyCheckInNumTrend(query, propertyDTOList);
        }

        /**
         * 校验时间跨度的大小
         *
         * @param unit 单位
         * @param span 跨度
         * @return void
         * @author lichen
         * @date 2023/12/9
         */
        public void checkSpan(Integer unit, Integer span) {
            if(PropertyCheckInNumTrendQuery.MONTH == unit){
                if (span > 12) {
                    throw new BadRequestException(CommonErrorI18nConstant.CANNOT_GREATER_THAN,
                            i18nMessageUtils.getErrorParamMapNotNeedTranslate("month", 12),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The span must be less than 13 when unit is month");
                }
            }else {
                if (span > 4) {
                    throw new BadRequestException(CommonErrorI18nConstant.CANNOT_GREATER_THAN,
                            i18nMessageUtils.getErrorParamMapNotNeedTranslate("quarter", 4),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The span must be less than 5 when unit is quarter");
                }
            }
        }
    }