package com.usky.ems.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.usky.ems.domain.TdengineData;
import com.usky.ems.service.TdengineService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;

/**
 * TDengine数据查询服务实现类
 *
 * @author system
 * @since 2024-01-01
 */
@Service
@DS("taos")
public class TdengineServiceImpl implements TdengineService {

    private static final Logger logger = LoggerFactory.getLogger(TdengineServiceImpl.class);

    @Autowired
    private DataSource tdengineDataSource;

    @Override
    public TdengineData getLatestData(String deviceUuid) {
        if (tdengineDataSource == null) {
            logger.warn("TDengine数据源未配置");
            return null;
        }

        // 子表名格式：_ + deviceUuid
        String tableName = "_" + deviceUuid;
        String sql = "SELECT ts, device_id, voltage_a, voltage_b, voltage_c, " +
                     "current_a, current_b, current_c, activepowera, activepowerb, activepowerc, " +
                     "totalActivePower, totalPowerFactor, totalActiveEnergyF, totalActiveEnergyR, " +
                     "totalReactiveEnergyF, totalReactiveEnergyR " +
                     "FROM " + tableName + " " +
                     "ORDER BY ts DESC LIMIT 1";

        try (Connection conn = tdengineDataSource.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return mapResultSetToTdengineData(rs);
                }
            }
        } catch (Exception e) {
            logger.error("查询TDengine数据失败, deviceUuid: {}", deviceUuid, e);
        }
        
        return null;
    }

    @Override
    public Map<String, TdengineData> getLatestDataBatch(List<String> deviceUuids) {
        Map<String, TdengineData> result = new HashMap<>();
        
        if (tdengineDataSource == null || deviceUuids == null || deviceUuids.isEmpty()) {
            return result;
        }

        // 为每个设备查询最新数据
        for (String deviceUuid : deviceUuids) {
            TdengineData data = getLatestData(deviceUuid);
            if (data != null) {
                result.put(deviceUuid, data);
            }
        }
        
        return result;
    }

    /**
     * 将ResultSet映射为TdengineData对象
     */
    private TdengineData mapResultSetToTdengineData(ResultSet rs) throws Exception {
        TdengineData data = new TdengineData();
        data.setTs(rs.getTimestamp("ts"));
        data.setDeviceId(rs.getString("device_id"));
        data.setVoltageA(getDouble(rs, "voltage_a"));
        data.setVoltageB(getDouble(rs, "voltage_b"));
        data.setVoltageC(getDouble(rs, "voltage_c"));
        data.setCurrentA(getDouble(rs, "current_a"));
        data.setCurrentB(getDouble(rs, "current_b"));
        data.setCurrentC(getDouble(rs, "current_c"));
        data.setActivepowera(getDouble(rs, "activepowera"));
        data.setActivepowerb(getDouble(rs, "activepowerb"));
        data.setActivepowerc(getDouble(rs, "activepowerc"));
        data.setTotalActivePower(getDouble(rs, "totalactivepower"));
        data.setTotalPowerFactor(getDouble(rs, "totalpowerfactor"));
        data.setTotalActiveEnergyF(getDouble(rs, "totalactiveenergyf"));
        data.setTotalActiveEnergyR(getDouble(rs, "totalactiveenergyr"));
        data.setTotalReactiveEnergyF(getDouble(rs, "totalreactiveenergyf"));
        data.setTotalReactiveEnergyR(getDouble(rs, "totalreactiveenergyr"));
        return data;
    }

    private Double getDouble(ResultSet rs, String column) {
        try {
            double value = rs.getDouble(column);
            return rs.wasNull() ? null : value;
        } catch (Exception e) {
            return null;
        }
    }
}
