package com.fizz.business.service.impl;

import com.fizz.business.comm.OPC.OpcMessageSend;
import com.fizz.business.form.OpcBatchWriteDataForm;
import com.fizz.business.form.OpcWriteDataForm;
import com.fizz.business.service.OpcDataService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * OPC 数据读写服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "kangaroohy.milo", name = "enabled", havingValue = "true")
public class OpcDataServiceImpl implements OpcDataService {

    private final OpcMessageSend opcMessageSend;

    @Override
    public boolean writeData(OpcWriteDataForm form) {
        try {
            return opcMessageSend.writeDataByFieldName(form.getFieldName(), form.getValue());
        } catch (Exception e) {
            log.error("写入 OPC 数据异常，fieldName={}, value={}", form.getFieldName(), form.getValue(), e);
            return false;
        }
    }

    @Override
    public boolean batchWriteData(OpcBatchWriteDataForm form) {
        try {
            Map<String, Object> fieldDataMap = form.getDataList().stream()
                    .collect(Collectors.toMap(
                            OpcWriteDataForm::getFieldName,
                            OpcWriteDataForm::getValue,
                            (v1, v2) -> v2 // 如果有重复的 key，保留后面的值
                    ));
            return opcMessageSend.batchWriteDataByFieldName(fieldDataMap);
        } catch (Exception e) {
            log.error("批量写入 OPC 数据异常", e);
            return false;
        }
    }
}

