package com.fizz.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fizz.business.domain.DeviceSnapshot;
import com.fizz.business.mapper.DeviceSnapshotMapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/deviceSnapshot")
@Tag(name = "设备数据快照")
@Anonymous
@RequiredArgsConstructor
public class DeviceSnapshotController {

    private final DeviceSnapshotMapper deviceSnapshotMapper;

    @GetMapping("/latest")
    @Operation(description = "获取最新N条设备快照（可按deviceCode过滤）")
    public R<List<DeviceSnapshot>> latest(@RequestParam(value = "limit", defaultValue = "60") Integer limit,
                                          @RequestParam(value = "deviceCode", required = false) String deviceCode) {
        LambdaQueryWrapper<DeviceSnapshot> qw = new LambdaQueryWrapper<DeviceSnapshot>()
                .orderByDesc(DeviceSnapshot::getCreateTime)
                .last("limit " + Math.max(1, Math.min(limit, 500)));

        if (deviceCode != null && !deviceCode.isEmpty()) {
            qw.eq(DeviceSnapshot::getDeviceCode, deviceCode);
        }

        return R.ok(deviceSnapshotMapper.selectList(qw));
    }

    @GetMapping("/range")
    @Operation(description = "按时间范围查询设备快照（可按deviceCode过滤）")
    public R<List<DeviceSnapshot>> range(@RequestParam("start") String start,
                                         @RequestParam("end") String end,
                                         @RequestParam(value = "deviceCode", required = false) String deviceCode) {
        LocalDateTime startTime = LocalDateTime.parse(start);
        LocalDateTime endTime = LocalDateTime.parse(end);

        LambdaQueryWrapper<DeviceSnapshot> qw = new LambdaQueryWrapper<DeviceSnapshot>()
                .between(DeviceSnapshot::getCreateTime, startTime, endTime)
                .orderByAsc(DeviceSnapshot::getCreateTime);

        if (deviceCode != null && !deviceCode.isEmpty()) {
            qw.eq(DeviceSnapshot::getDeviceCode, deviceCode);
        }

        return R.ok(deviceSnapshotMapper.selectList(qw));
    }
}

