package com.usky.ai.controller.web;

import com.usky.ai.domain.AiDevice;
import com.usky.ai.service.AiDeviceService;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.bean.CommonPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/device")
public class DeviceController {

    private final AiDeviceService aiDeviceService;

    @Autowired
    public DeviceController(AiDeviceService aiDeviceService) {
        this.aiDeviceService = aiDeviceService;
    }

    // 返回设备信息，支持分页
    @GetMapping
    public ApiResult<CommonPage<AiDevice>> devices(
            @RequestParam(required = false) String boardId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        List<AiDevice> devices = aiDeviceService.getDevices(boardId, pageNum, pageSize);
        long total = aiDeviceService.getTotalDevices(boardId); // 获取总记录数
        CommonPage<AiDevice> page = new CommonPage<>(devices, total, pageSize, pageNum);
        return ApiResult.success(page);
    }

    // 新增设备
    @PostMapping
    public ApiResult<Void> addDevice(@RequestBody AiDevice device) {
        try {
            aiDeviceService.addDevice(device);
            return ApiResult.success();
        } catch (IllegalArgumentException e) {
            return ApiResult.error(e.getMessage());
        } catch (Exception e) {
            return ApiResult.error("新增失败", e.getMessage());
        }
    }

    // 编辑设备
    @PutMapping
    public ApiResult<Void> editDevice(@RequestBody AiDevice device) {
        try {
            aiDeviceService.editDevice(device);
            return ApiResult.success();
        } catch (Exception e) {
            return ApiResult.error("编辑失败", e.getMessage());
        }
    }

    // 删除指定设备信息
    @DeleteMapping("/{boardId}")
    public ApiResult<Void> delete(@PathVariable String boardId) {
        try {
            aiDeviceService.deleteDevice(boardId);
            return ApiResult.success();
        } catch (Exception e) {
            return ApiResult.error("删除失败", e.getMessage());
        }
    }
}