package com.fizz.business.controller;

import com.fizz.business.form.OpcBatchWriteDataForm;
import com.fizz.business.form.OpcWriteDataForm;
import com.fizz.business.service.OpcDataService;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * OPC 数据读写控制器
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/opc/data")
@Tag(name = "OPC 数据读写")
@ConditionalOnProperty(prefix = "kangaroohy.milo", name = "enabled", havingValue = "true")
@Anonymous
public class OpcDataController {

    private final OpcDataService opcDataService;

    /**
     * 向单个点位写入数据（通过字段名）
     */
    @Operation(summary = "向单个点位写入数据", description = "通过字段名向指定的 OPC 点位写入数据")
    @PostMapping("/write")
    public R<?> writeData(@Valid @RequestBody OpcWriteDataForm form) {
        try {
            boolean success = opcDataService.writeData(form);
            if (success) {
                return R.ok("写入成功");
            } else {
                return R.fail("写入失败，可能是字段名未找到对应的 OPC 节点路径，请查看日志");
            }
        } catch (Exception e) {
            log.error("写入 OPC 数据异常", e);
            return R.fail("写入异常：" + e.getMessage());
        }
    }

    /**
     * 批量向多个点位写入数据（通过字段名）
     */
    @Operation(summary = "批量向多个点位写入数据", description = "通过字段名向多个 OPC 点位批量写入数据")
    @PostMapping("/batchWrite")
    public R<?> batchWriteData(@Valid @RequestBody OpcBatchWriteDataForm form) {
        try {
            boolean success = opcDataService.batchWriteData(form);
            if (success) {
                return R.ok("批量写入成功，共 " + form.getDataList().size() + " 个点位");
            } else {
                return R.fail("批量写入失败，可能是部分字段名未找到对应的 OPC 节点路径，请查看日志");
            }
        } catch (Exception e) {
            log.error("批量写入 OPC 数据异常", e);
            return R.fail("批量写入异常：" + e.getMessage());
        }
    }
}

