package com.ruoyi.dataprocess.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.constant.TdEngineConstants;
import com.ruoyi.dataprocess.domain.HwDevice;
import com.ruoyi.dataprocess.mapper.HwDeviceMapper;
import com.ruoyi.dataprocess.service.IDeviceStatusService;
import com.ruoyi.tdengine.api.RemoteTdEngineService;
import com.ruoyi.tdengine.api.domain.TdField;
import com.ruoyi.tdengine.api.domain.TdTableVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 设备状态处理服务
 * @ClassName: DeviceStatusServiceImpl
 * @Author : xins
 * @Date :2023-09-12  15:31
 * @Version :1.0
 */
@Service
public class DeviceStatusServiceImpl implements IDeviceStatusService {

    @Autowired
    private HwDeviceMapper hwDeviceMapper;

    @Resource
    private RemoteTdEngineService remoteTdEngineService;

    @Override
    public void handleDeviceStatus(String payloadString, String clientId) {
//        ddd:{"msg":"设备设备连接状态信息","deviceType":"edge","connectStatus":1,
//                "statusTime":1694506127199,"deviceCode":"hw-data-process-1"}
        JSONObject json = JSON.parseObject(payloadString);
        String deviceCode = json.getString("deviceCode");
        if (clientId.equals(deviceCode)) { //校验是不是自己，如果是自己则不记录状态，返回即可。
            return;
        }
        HwDevice hwDevice = hwDeviceMapper.selectHwDeviceByDeviceCode(deviceCode);
        if (hwDevice != null) {
            Long deviceId = hwDevice.getDeviceId();
            TdTableVo tdTableVo = new TdTableVo();
            tdTableVo.setDatabaseName(TdEngineConstants.PLATFORM_DB_NAME);
            tdTableVo.setTableName(TdEngineConstants.DEFAULT_DEVICE_STATUS_TABLE_NAME_PREFIX + deviceId);

            List<TdField> schemaFields = new ArrayList<>();
            TdField onlineStatusField = new TdField();
            onlineStatusField.setFieldName("onlineStatus");
            onlineStatusField.setFieldValue(json.getInteger("connectStatus"));
            schemaFields.add(onlineStatusField);

            TdField deviceTypeField = new TdField();
            deviceTypeField.setFieldName("deviceType");
            deviceTypeField.setFieldValue(json.getString("deviceType"));
            schemaFields.add(deviceTypeField);

            TdField tsField = new TdField();
            tsField.setFieldName(TdEngineConstants.DEFAULT_FIRST_FIELD_NAME);
            tsField.setFieldValue(json.getLong("statusTime"));
            schemaFields.add(tsField);

            tdTableVo.setSchemaFields(schemaFields);

            this.remoteTdEngineService.insertTable(tdTableVo);

            //更新设备当前状态信息
            hwDevice.setOnlineStatus(String.valueOf(json.getInteger("connectStatus")));
            hwDeviceMapper.updateHwDevice(hwDevice);
        }
    }
}
