package org.nl.acs.monitor.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nl.acs.device.domain.Device;
import org.nl.acs.monitor.DeviceStageMonitor;
import org.nl.acs.monitor.service.DeviceStageMonitorService;
import org.nl.acs.opc.DeviceAppService;
import org.springframework.stereotype.Service;

/**
 * @Author: lyd
 * @Description:
 * @Date: 2022-08-17
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DeviceStageMonitorServiceImpl implements DeviceStageMonitorService {
    private final DeviceAppService deviceAppService;


    @Override
    public JSONArray getData(JSONArray jsonArray) throws Exception {
        JSONArray arr = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject obj = new JSONObject();
            JSONObject js = jsonArray.getJSONObject(i);
            String device_code = js.getString("device_code");

            if (ObjectUtil.isEmpty(device_code)) continue;

            Device device = deviceAppService.findDeviceByCode(device_code);
            if (ObjectUtil.isNull(device)) continue;


            JSONObject json = new JSONObject();
            if (device.getDeviceDriver() instanceof DeviceStageMonitor) {
                DeviceStageMonitor monitorService = (DeviceStageMonitor) device.getDeviceDriver();
                json = monitorService.getDeviceStatusName();
            }

            obj.put("data", json);
            obj.put("device_name",json.get("device_name"));
            obj.put("device_code", js.get("device_code"));
            obj.put("id", js.getString("id")); // 设备不存在就只保留id，方便前端查看
            arr.add(obj);
        }

        return arr;
    }
}
