package com.usky.vpp.controller.web;

import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.bean.CommonPage;
import com.usky.vpp.domain.VppDevice;
import com.usky.vpp.service.VppDeviceService;
import com.usky.vpp.service.vo.DeviceRequest;
import com.usky.vpp.service.vo.DeviceTsdbImportResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * 虚拟电厂 - 设备接口
 * 网关前缀: /prod-api/service-vpp
 */
@RestController
@RequestMapping("/device")
public class VppDeviceController {

    @Autowired
    private VppDeviceService vppDeviceService;

    @GetMapping
    public ApiResult<CommonPage<VppDevice>> pageDevice(@RequestParam(required = false) Map<String, Object> params) {
        return ApiResult.success(vppDeviceService.pageDevice(params));
    }

    @GetMapping("/uuid/{deviceUuid}")
    public ApiResult<VppDevice> getByDeviceUuid(@PathVariable("deviceUuid") String deviceUuid) {
        return ApiResult.success(vppDeviceService.getByDeviceUuid(deviceUuid));
    }

    @GetMapping("/{id}")
    public ApiResult<VppDevice> getDevice(@PathVariable("id") Long id) {
        return ApiResult.success(vppDeviceService.getDevice(id));
    }

    @PutMapping("/{id}")
    public ApiResult<Void> updateDevice(@PathVariable("id") Long id, @RequestBody DeviceRequest body) {
        vppDeviceService.updateDevice(id, body);
        return ApiResult.success();
    }

    @DeleteMapping("/{id}")
    public ApiResult<Void> deleteDevice(@PathVariable("id") Long id) {
        vppDeviceService.deleteDevice(id);
        return ApiResult.success();
    }

    /**
     * 解析 CSV 并导入设备时序数据到 TDengine。
     * <p>CSV 需包含 ts（时间戳）与 p（数值）列，支持表头；时间支持毫秒/秒时间戳或 yyyy-MM-dd HH:mm:ss。</p>
     *
     * @param deviceUuid 设备 UUID，对应子表 _{deviceUuid}
     * @param file       CSV 文件
     */
    @PostMapping(value = "/import-tsdb", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ApiResult<DeviceTsdbImportResultVO> importTsdbData(@RequestParam("deviceUuid") String deviceUuid,
                                                             @RequestPart("file") MultipartFile file) {
        return ApiResult.success(vppDeviceService.importTsdbData(deviceUuid, file));
    }
}
