package com.fizz.business.comm.OPC;

import com.fizz.business.domain.msg.OpcMessage;
import com.fizz.business.domain.msg.PdiSetup;
import com.kangaroohy.milo.model.ReadWriteEntity;
import com.kangaroohy.milo.service.MiloService;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.fizz.business.service.manager.OpcMessageIdsManager.pdiSetupIds;

@Service
@Log4j2
@ConditionalOnProperty(prefix = "kangaroohy.milo", name = "enabled", havingValue = "true")
public class OpcMessageSend {

    @Resource
    private MiloService miloService;

    private void sendPdiSetup(PdiSetup pdiSetup) {
        try {
            List<ReadWriteEntity> entities =  getWriteEntities(pdiSetup, pdiSetupIds);
            miloService.writeToOpcUa(entities);
        } catch (Exception e) {
            log.error("发送设定失败：{0}",e.getMessage());
        }

    }

    /**
     * 单独写入当前钢卷号到 OPC
     * 使用 pdiSetupIds 中 coilId 对应的节点
     */
    public void sendCoilId(String coilId) {
        try {
            String coilNode = pdiSetupIds.entrySet().stream()
                    .filter(e -> "coilId".equals(e.getValue()))
                    .map(Map.Entry::getKey)
                    .findFirst()
                    .orElse(null);
            if (coilNode == null) {
                log.warn("未找到 coilId 对应的 OPC 节点，写入跳过");
                return;
            }
            List<ReadWriteEntity> entities = new ArrayList<>();
            entities.add(ReadWriteEntity.builder()
                    .identifier(coilNode)
                    .value(coilId)
                    .build());
            miloService.writeToOpcUa(entities);
            log.info("写入 OPC coilId 成功，node={} value={}", coilNode, coilId);
        } catch (Exception e) {
            log.error("写入 OPC coilId 失败，coilId={}，原因：{}", coilId, e.getMessage(), e);
        }
    }

    private List<ReadWriteEntity> getWriteEntities(OpcMessage msg, Map<String,String> msgIds) {
        List<ReadWriteEntity> entities = new ArrayList<>();
        for (String key : msgIds.keySet()) {
            String fieldName = msgIds.get(key);
            Object value = null;
            try {
                // 获取OpcMessage类中对应字段的Field对象
                Field field = msg.getClass().getDeclaredField(fieldName);
                // 设置可访问以处理私有字段
                field.setAccessible(true);
                // 获取msg对象中该字段的值
                value = field.get(msg);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                // 处理字段不存在或访问异常，可记录日志或设置默认值
                e.printStackTrace();
               return new ArrayList<>();
            }

            ReadWriteEntity entity = ReadWriteEntity.builder()
                    .identifier(key)
                    .value(value)
                    .build();
            entities.add(entity);
        }
        return entities;
    }
}
