package com.yfd.platform.modules.auxcontrol.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.modules.auxcontrol.domain.DeviceSignal;
import com.yfd.platform.modules.auxcontrol.domain.DeviceWorkData;
import com.yfd.platform.modules.auxcontrol.domain.TimeConfig;
import com.yfd.platform.modules.auxcontrol.service.IDeviceSignalService;
import com.yfd.platform.modules.auxcontrol.service.IDeviceWorkDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * <p>
 * 变电站-设备-运行数据 前端控制器
 * </p>
 *
 * @author zhengsl
 * @since 2025-04-23
 */
@RestController
@RequestMapping("/auxcontrol/device-work-data")
@Api(value = "DeviceWorkDataController", tags = "变电站设备运行数据")
public class DeviceWorkDataController {

    @Resource
    private IDeviceWorkDataService deviceWorkDataService;
    @Resource
    private IDeviceSignalService deviceSignalService;

    @GetMapping("/page")
    @ApiOperation("分页查询变电站设备运行记录")
    public ResponseResult getDeviceWorkDataPage(Page<DeviceWorkData> page, String signalId, String startDate,
                                                String endDate) {
        if(StrUtil.isBlank(signalId)){
            return ResponseResult.successData(page);
        }
        Page<DeviceWorkData> deviceWorkDataPage = deviceWorkDataService.getDeviceWorkDataPage(page, signalId,
                startDate, endDate);
        return ResponseResult.successData(deviceWorkDataPage);
    }

    @GetMapping("/getDeviceWorkData")
    @ApiOperation("查询变电站设备运行数据")
    public ResponseResult getDeviceWorkData(String stationId) {
        List<Map<String, Object>> map = deviceWorkDataService.getDeviceWorkData(stationId);
        return ResponseResult.successData(map);
    }

    //    public Map<String, Object> processDeviceData(List<DeviceWorkData> deviceWorkDataList, String signalId) {
    //        // 生成过去60分钟的分钟时间槽
    //        LocalDateTime now = LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES);
    //        LocalDateTime startTime = now.minusMinutes(59);
    //        List<LocalDateTime> minuteSlots = new ArrayList<>();
    //        for (int i = 0; i < 60; i++) {
    //            minuteSlots.add(startTime.plusMinutes(i));
    //        }
    //
    //        // 按分钟分组数据
    //        Map<LocalDateTime, String> minuteDataMap = new HashMap<>();
    //        for (DeviceWorkData data : deviceWorkDataList) {
    //            LocalDateTime minuteKey = data.getStartTime().truncatedTo(ChronoUnit.MINUTES);
    //            minuteDataMap.put(minuteKey, data.getValue());
    //        }
    //
    //        // 构建xAxis和series数据
    //        List<String> xAxisData = new ArrayList<>();
    //        List<Double> seriesData = new ArrayList<>();
    //        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH时mm分");
    //        for (LocalDateTime slot : minuteSlots) {
    //            xAxisData.add(slot.format(formatter));
    //            String value = minuteDataMap.getOrDefault(slot, "0");
    //            if (!NumberUtil.isNumber(value)) {
    //                value="0";
    //            }
    //            seriesData.add(NumberUtil.parseDouble(value));
    //        }
    //
    //        // 构建ECharts数据结构
    //        Map<String, Object> result = new HashMap<>();
    //
    //        Map<String, Object> xAxis = new HashMap<>();
    //        xAxis.put("type", "category");
    //        xAxis.put("data", xAxisData);
    //        result.put("xAxis", xAxis);
    //
    //        Map<String, Object> yAxis = new HashMap<>();
    //        yAxis.put("type", "value");
    //        result.put("yAxis", yAxis);
    //        DeviceSignal deviceSignal = deviceSignalService.getById(signalId);
    //        String name = deviceSignal == null ? "" : deviceSignal.getSignalName();
    //        List<Map<String, Object>> seriesList = new ArrayList<>();
    //        Map<String, Object> series = new HashMap<>();
    //        series.put("name", name);
    //        series.put("type", "line");
    //        series.put("step", "start");
    //        series.put("data", seriesData);
    //        seriesList.add(series);
    //
    //        // 如果需要多个系列，可以继续添加
    //        // 例如复制series并修改name和step
    //
    //        result.put("series", seriesList);
    //
    //        return result;
    //    }

    public Map<String, Object> processDeviceData(List<DeviceWorkData> deviceWorkDataList, String signalId,
                                                 String type) {
        // 根据类型生成时间槽和配置参数
        TimeConfig config = generateTimeConfig(type);

        // 按时间单位分组数据
        Map<LocalDateTime, String> timeDataMap = groupDataByTimeUnit(deviceWorkDataList, config.getTruncateUnit());

        // 构建xAxis和series数据
        List<String> xAxisData = new ArrayList<>();
        List<Double> seriesData = new ArrayList<>();
        for (LocalDateTime slot : config.getTimeSlots()) {
            xAxisData.add(slot.format(config.getFormatter()));
            String value = timeDataMap.getOrDefault(slot, "0");
            seriesData.add(NumberUtil.parseDouble(NumberUtil.isNumber(value) ? value : "0"));
        }

        // 构建ECharts数据结构
        return buildEChartsResult(xAxisData, seriesData, signalId);
    }

    /**
     * 生成时间配置
     */
    private TimeConfig generateTimeConfig(String type) {
        List<LocalDateTime> timeSlots = new ArrayList<>();
        DateTimeFormatter formatter;
        ChronoUnit truncateUnit;

        if ("2".equals(type)) {
            // 类型2：过去24小时（每小时一个点）
            LocalDateTime now = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS);
            LocalDateTime startTime = now.minusHours(23);
            for (int i = 0; i < 24; i++) {
                timeSlots.add(startTime.plusHours(i));
            }
            formatter = DateTimeFormatter.ofPattern("HH时");
            truncateUnit = ChronoUnit.HOURS;
        } else {
            // 默认类型1：过去60分钟（每分钟一个点）
            LocalDateTime now = LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES);
            LocalDateTime startTime = now.minusMinutes(59);
            for (int i = 0; i < 60; i++) {
                timeSlots.add(startTime.plusMinutes(i));
            }
            formatter = DateTimeFormatter.ofPattern("HH时mm分");
            truncateUnit = ChronoUnit.MINUTES;
        }

        return new TimeConfig(timeSlots, formatter, truncateUnit);
    }

    /**
     * 按时间单位分组数据
     */
    private Map<LocalDateTime, String> groupDataByTimeUnit(List<DeviceWorkData> dataList, ChronoUnit unit) {
        Map<LocalDateTime, String> map = new HashMap<>();
        for (DeviceWorkData data : dataList) {
            LocalDateTime key = data.getStartTime().truncatedTo(unit);
            map.put(key, data.getValue());
        }
        return map;
    }

    /**
     * 构建ECharts结果
     */
    private Map<String, Object> buildEChartsResult(List<String> xAxisData, List<Double> seriesData, String signalId) {
        Map<String, Object> result = new HashMap<>();

        // xAxis配置
        Map<String, Object> xAxis = new HashMap<>();
        xAxis.put("type", "category");
        xAxis.put("data", xAxisData);
        result.put("xAxis", xAxis);

        // yAxis配置
        Map<String, Object> yAxis = new HashMap<>();
        yAxis.put("type", "value");
        result.put("yAxis", yAxis);

        // 系列数据配置
        DeviceSignal deviceSignal = deviceSignalService.getById(signalId);
        String seriesName = deviceSignal != null ? deviceSignal.getSignalName() : "";

        List<Map<String, Object>> seriesList = new ArrayList<>();
        Map<String, Object> series = new HashMap<>();
        series.put("name", seriesName);
        series.put("type", "line");
        series.put("step", "start");
        series.put("data", seriesData);
        seriesList.add(series);

        result.put("series", seriesList);

        return result;
    }

    @GetMapping("/getHistoricalCurve")
    @ApiOperation("查询历史曲线")
    public ResponseResult getHistoricalCurve(String signalId, String type) {
        List<DeviceWorkData> deviceWorkDataList = deviceWorkDataService.getHistoricalCurve(signalId);
        type = StrUtil.isBlank(type) ? "1" : type;
        Map<String, Object> map = processDeviceData(deviceWorkDataList, signalId, type);
        return ResponseResult.successData(map);
    }

    @GetMapping("/insertData")
    @ApiOperation("生成遥测数据")
    public ResponseResult insertData(String from, String type, String slaveIp, String address, String value) {
        deviceWorkDataService.insertData(from, type, slaveIp, address, value);
        return ResponseResult.success();
    }

    @GetMapping("/exportDeviceWorkData")
    @ApiOperation("导出环境历史数据")
    public void exportDeviceWorkData(String stationId, String signalId,String startDate,String endDate, HttpServletResponse response) throws IOException {
        deviceWorkDataService.exportDeviceWorkData(stationId,signalId,startDate,endDate, response);
    }

}
