package com.evobms.project.VehicleData.controller;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.evobms.project.VehicleData.service.IVehicleDataService;
import com.evobms.project.VehicleData.service.IVehicleLocationService;
import com.evobms.project.VehicleData.domain.VehicleData;
import com.evobms.project.VehicleData.domain.VehicleLocation;
import com.evobms.project.VehicleData.dto.ChartDataPoint;
import com.evobms.project.Battery.service.ISubsystemVoltageService;
import com.evobms.project.Battery.service.ISubsystemTemperatureService;
import com.evobms.project.Battery.domain.SubsystemVoltage;
import com.evobms.project.Battery.domain.SubsystemTemperature;
import com.evobms.project.Battery.service.IExtremeValuesService;
import com.evobms.project.Battery.domain.ExtremeValues;
import java.text.ParseException;
import java.text.SimpleDateFormat;
/**
 * 图标组件Controller
 *
 * @author 田志阳
 * @date 2025-11-15
 */
@RestController
public class BatteryChartController {

    @Autowired
    private IVehicleDataService vehicleDataService;

    @Autowired
    private IVehicleLocationService vehicleLocationService;

    @Autowired
    private ISubsystemVoltageService subsystemVoltageService;

    @Autowired
    private ISubsystemTemperatureService subsystemTemperatureService;

    @Autowired
    private IExtremeValuesService extremeValuesService;

    // 图表数据：按最近 hours 小时返回整车电压/电流/SOC 的时间序列
    @GetMapping("/battery-data/{deviceId}/chart")
    public List<ChartDataPoint> getChartData(@PathVariable("deviceId") String deviceId, @RequestParam(value = "hours", required = false, defaultValue = "24") int hours) {
        long millis = System.currentTimeMillis() - (long) hours * 3600_000L;
        Date startTime = new Date(millis);
        List<VehicleData> rows = vehicleDataService.selectByDeviceAndStartTime(deviceId, startTime);
        return rows.stream().map(v -> new ChartDataPoint(
                v.getTimestamp(),
                v.getTotalVoltage() == null ? 0 : v.getTotalVoltage().doubleValue(),
                v.getTotalCurrent() == null ? 0 : v.getTotalCurrent().doubleValue(),
                v.getSoc() == null ? 0 : v.getSoc()
        )).collect(Collectors.toList());
    }

    // 整车最新：返回 deviceId 最新的一条整车数据
    @GetMapping("/vehicle-data/{deviceId}/latest")
    public VehicleData latestVehicleData(@PathVariable("deviceId") String deviceId) {
        return vehicleDataService.selectLatestByDeviceId(deviceId);
    }

    // 位置最新：返回 deviceId 最新的一条位置数据
    @GetMapping("/vehicle-location/{deviceId}/latest")
    public VehicleLocation latestVehicleLocation(@PathVariable("deviceId") String deviceId) {
        return vehicleLocationService.selectLatestByDeviceId(deviceId);
    }

    // 位置轨迹：按时间范围返回位置列表，start/end 为毫秒时间戳，可选 limit 限制条数
    @GetMapping("/vehicle-location/{deviceId}")
    public List<VehicleLocation> locationRange(@PathVariable("deviceId") String deviceId,
                                               @RequestParam("start") long startMillis,
                                               @RequestParam("end") long endMillis,
                                               @RequestParam(value = "limit", required = false) Integer limit) {
        Date start = new Date(startMillis);
        Date end = new Date(endMillis);
        return vehicleLocationService.selectByDeviceAndRange(deviceId, start, end, limit);
    }

    // 子系统最新帧（电压）：返回指定子系统号最新的一帧电压数据
    @GetMapping("/subsystem-voltage/{deviceId}/{subsystemNo}/latest")
    public SubsystemVoltage latestVoltage(@PathVariable("deviceId") String deviceId, @PathVariable("subsystemNo") Integer subsystemNo) {
        return subsystemVoltageService.selectLatestByDeviceAndSubsystem(deviceId, subsystemNo);
    }

    // 子系统最新帧（温度）：返回指定子系统号最新的一帧温度数据
    @GetMapping("/subsystem-temperature/{deviceId}/{subsystemNo}/latest")
    public SubsystemTemperature latestTemperature(@PathVariable("deviceId") String deviceId, @PathVariable("subsystemNo") Integer subsystemNo) {
        return subsystemTemperatureService.selectLatestByDeviceAndSubsystem(deviceId, subsystemNo);
    }

    @GetMapping("/extreme-values/{deviceId}/latest")
    public ExtremeValues latestExtremeValues(@PathVariable("deviceId") String deviceId,
                                             @RequestParam(value = "before", required = false) String before) {
        if (before == null || before.isEmpty()) {
            return extremeValuesService.selectLatestByDeviceId(deviceId);
        }
        java.util.Date beforeTime = null;
        if (before.matches("\\d+")) {
            beforeTime = new java.util.Date(Long.parseLong(before));
        } else {
            try {
                beforeTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(before);
            } catch (ParseException e) {
                return extremeValuesService.selectLatestByDeviceId(deviceId);
            }
        }
        return extremeValuesService.selectLatestByDeviceIdBefore(deviceId, beforeTime);
    }
}
