package com.fizz.business.comm.OPC;

import com.fizz.business.constants.enums.ExitCutTypeEnum;
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.apache.commons.beanutils.BeanUtils;
import org.apache.commons.compress.utils.Lists;
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());
        }

    }

    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;
    }
}
