package com.haha.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haha.common.enums.DeviceAlertType;
import com.haha.admin.annotation.RequirePermission;
import com.haha.common.vo.PageResult;
import com.haha.common.vo.Result;
import com.haha.entity.DeviceAlertRecord;
import com.haha.service.DeviceAlertService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备告警记录控制器
 */
@Slf4j
@RestController
@RequestMapping("/device-alerts")
@RequiredArgsConstructor
public class DeviceAlertController {

    private final DeviceAlertService deviceAlertService;

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 分页查询告警记录
     * 支持按 deviceId、alertType、时间范围筛选
     *
     * @param deviceId  设备编号
     * @param alertType 告警类型
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param pageNo    页码
     * @param pageSize  每页数量
     * @return 分页结果
     */
    @RequirePermission("device-alert:read")
    @GetMapping("/list")
    public Result<PageResult<DeviceAlertRecord>> list(
            @RequestParam(required = false) String deviceId,
            @RequestParam(required = false) Integer alertType,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "20") Integer pageSize) {

        LambdaQueryWrapper<DeviceAlertRecord> wrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(deviceId)) {
            wrapper.eq(DeviceAlertRecord::getDeviceId, deviceId);
        }
        if (alertType != null) {
            wrapper.eq(DeviceAlertRecord::getAlertType, alertType);
        }
        if (StringUtils.hasText(startTime)) {
            wrapper.ge(DeviceAlertRecord::getAlertTime, LocalDateTime.parse(startTime, DATE_TIME_FORMATTER));
        }
        if (StringUtils.hasText(endTime)) {
            wrapper.le(DeviceAlertRecord::getAlertTime, LocalDateTime.parse(endTime, DATE_TIME_FORMATTER));
        }

        wrapper.orderByDesc(DeviceAlertRecord::getAlertTime);

        IPage<DeviceAlertRecord> page = deviceAlertService.page(new Page<>(pageNo, pageSize), wrapper);

        return Result.success("查询成功", PageResult.of(page));
    }

    /**
     * 告警统计
     * 返回：今日告警数、各类型分布
     *
     * @return 统计数据
     */
    @RequirePermission("device-alert:read")
    @GetMapping("/statistics")
    public Result<Map<String, Object>> statistics() {
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();

        LambdaQueryWrapper<DeviceAlertRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.ge(DeviceAlertRecord::getAlertTime, todayStart);

        List<DeviceAlertRecord> todayAlerts = deviceAlertService.list(wrapper);

        // 按告警类型分组统计
        Map<String, Long> typeDistribution = todayAlerts.stream()
                .collect(Collectors.groupingBy(record -> {
                    DeviceAlertType type = DeviceAlertType.fromCode(record.getAlertType());
                    return type != null ? type.getDescription() : "未知类型";
                }, Collectors.counting()));

        Map<String, Object> result = new HashMap<>();
        result.put("todayTotal", todayAlerts.size());
        result.put("typeDistribution", typeDistribution);

        return Result.success("查询成功", result);
    }
}
