# AlertController.java

    package cloud.wconnect.rateshop.controller.rateshop;

    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.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.rateshop.cons.rateshop.AlertRuleEnum;
    import cloud.wconnect.rateshop.cons.rateshop.RateShopErrorI18nConstant;
    import cloud.wconnect.rateshop.cons.rateshop.RateShopFieldI18nConstant;
    import cloud.wconnect.rateshop.entity.rateshop.Setting;
    import cloud.wconnect.rateshop.pojo.dto.rateshop.alertmessage.alertrule.AlertRuleDTO;
    import cloud.wconnect.rateshop.pojo.dto.rateshop.alertmessage.alertrule.IwcRuleDTO;
    import cloud.wconnect.rateshop.pojo.dto.rateshop.alertmessage.alertrule.RateRuleDTO;
    import cloud.wconnect.rateshop.pojo.query.rateshop.AlertMsgQuery;
    import cloud.wconnect.rateshop.pojo.query.rateshop.DailyAlertMsgQuery;
    import cloud.wconnect.rateshop.pojo.vo.rateshop.AlertMsgVO;
    import cloud.wconnect.rateshop.pojo.vo.rateshop.DailyAlertMsgVO;
    import cloud.wconnect.rateshop.service.rateshop.IAlertMessageService;
    import cloud.wconnect.rateshop.service.rateshop.ISettingService;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Sets;
    import jakarta.validation.Valid;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;

    import java.time.LocalDate;
    import java.util.Collections;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;

    /**
     * 警报 控制层
     *
     * @author lichen
     * @date 2023/6/20
     */
    @RestController
    @RequestMapping("/rate-shop")
    public class AlertController {

        @Autowired
        private SessionContext sessionContext;
        @Autowired
        private IAlertMessageService alertMessageService;
        @Autowired
        private ISettingService settingService;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        /**
         * 查询警报
         *
         * @param property      资产标识
         * @param alertMsgQuery 查询条件
         * @return java.util.List<cloud.wconnect.rateshop.pojo.vo.rateshop.AlertMsgVO>
         * @author lichen
         * @date 2023/6/20
         */
        @ApiId(349)
        @GetMapping("/alert")
        public List<AlertMsgVO> listAlertMsg(String property, @Valid AlertMsgQuery alertMsgQuery) {
            int propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);

            //alert的规则等于需求趋势时，数据源必须等于空
            if (Objects.nonNull(alertMsgQuery.getRule()) && alertMsgQuery.getRule() == AlertRuleEnum.MARKET_DEMAND.getCode()) {
                if (Objects.nonNull(alertMsgQuery.getDatasourceId())) {
                    throw new BadRequestException(CommonErrorI18nConstant.MUST_EMPTY,
                            i18nMessageUtils.getErrorParamMapNeedTranslate(RateShopFieldI18nConstant.DATASOURCE),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The datasourceId must be null when rule is market demand");
                }
            }
            return alertMessageService.listAlertMsg(propertyDTO, alertMsgQuery);
        }

        /**
         * 查询警报设置
         *
         * @param property 资产标识
         * @return cloud.wconnect.rateshop.pojo.dto.rateshop.alertmessage.alertrule.AlertRuleDTO
         * @author lichen
         * @date 2023/6/20
         */
        @ApiId(350)
        @GetMapping("/alert/setting")
        public AlertRuleDTO listAlertSetting(String property) {
            int propertyId = sessionContext.getPropertyId(property);
            //查询资产rateShop功能的设置
            Setting setting = settingService.getByPropertyId(propertyId);
            if (Objects.isNull(setting)) {
                throw new BadRequestException(RateShopErrorI18nConstant.PROPERTY_NOT_CONFIG_RATE_SHOP_SETTING,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The property has no rateShop set, propertyId = " + propertyId);
            }

            AlertRuleDTO alertRuleDTO = JsonUtils.convertStringToObject(objectMapper, setting.getAlertRules(), AlertRuleDTO.class);
            if (Objects.isNull(alertRuleDTO.getIwcRule())) {
                alertRuleDTO.setIwcRule(new IwcRuleDTO(AlertRuleDTO.DISABLE));
            }
            return alertRuleDTO;
        }

        /**
         * 保存警报规则
         *
         * @param property     资产标识
         * @param alertRuleDTO 警报设置对象
         * @return java.util.Map
         * @author lichen
         * @date 2023/6/20
         */
        @ApiId(351)
        @PutMapping("/alert/rules")
        public Map saveAlertRules(String property, @RequestBody @Valid AlertRuleDTO alertRuleDTO) {
            int propertyId = sessionContext.getPropertyId(property);
            //查询资产rateShop功能的设置
            Setting setting = settingService.getByPropertyId(propertyId);
            if (Objects.isNull(setting)) {
                throw new BadRequestException(RateShopErrorI18nConstant.PROPERTY_NOT_CONFIG_RATE_SHOP_SETTING,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The property has no rateShop set, propertyId = " + propertyId);
            }
            //校验rateRule
            List<Integer> rateTypeList = alertRuleDTO.getRateRule().stream().map(RateRuleDTO::getRateType).toList();
            if (rateTypeList.size() != Sets.newHashSet(rateTypeList).size()) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_CANNOT_REPEAT,
                        i18nMessageUtils.getErrorParamMapNeedTranslate(RateShopFieldI18nConstant.RATE_TYPE),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The rate type cannot repeat");
            }

            //转成json字符串
            String alertRuleJson = JsonUtils.convertObjToString(objectMapper, alertRuleDTO);
            //更新警报规则
            Setting update = new Setting();
            update.setId(setting.getId());
            update.setAlertRules(alertRuleJson);
            settingService.updateById(update);
            return Collections.emptyMap();
        }

        /**
         * 查询每日警报
         *
         * @param property           资产
         * @param dailyAlertMsgQuery 查询参数
         * @return java.util.List<cloud.wconnect.rateshop.pojo.vo.rateshop.DailyAlertMsgVO>
         * @author lichen
         * @date 2025/9/5
         */
        @ApiId(1585)
        @GetMapping("/daily-alert")
        public List<DailyAlertMsgVO> listDailyAlert(String property, @Valid DailyAlertMsgQuery dailyAlertMsgQuery) {
            int propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            //把yyyy-MM-dd的日期转化成localDate
            LocalDate startLocalDate = DateTimeUtils.strToLocalDate(dailyAlertMsgQuery.getFromDate(), BaseConstant.DATE_FORMAT_YYYY_MM_DD);
            LocalDate endLocalDate = DateTimeUtils.strToLocalDate(dailyAlertMsgQuery.getToDate(), BaseConstant.DATE_FORMAT_YYYY_MM_DD);
            //开始时间不能大于结束时间
            if (startLocalDate.isAfter(endLocalDate)) {
                throw new BadRequestException(CommonErrorI18nConstant.START_DATE_CANNOT_GREATER_THAN_END_DATE,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The toDate must be greater than or equal to the fromDate");
            }
            //判断时间间隔必须小于70天
            long diffDay = DateTimeUtils.numberOfDays(startLocalDate, endLocalDate);
            //此处限制最大区间70天
            if (Math.abs(diffDay) > 70) {
                throw new BadRequestException(CommonErrorI18nConstant.SELECT_DATE_LIMIT,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate(70),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The interval between fromDate and toDate must be less than or equal to 70 days");
            }
            //查询事件信息
            return alertMessageService.listDailyAlert(propertyDTO, dailyAlertMsgQuery);
        }
    }