package com.usky.demo.service.rocketmq.tdengine;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.usky.common.core.util.JsonUtils;
import com.usky.demo.service.rocketmq.MqttStrategy;
import com.usky.demo.service.vo.MQDataVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;

@Service("tdengine")
@DS("taos")
public class tdengine implements MqttStrategy {
    @Autowired
    private DataSource dataSource;

    @Override
    public String disposeMessage(MQDataVO mqBaseVO) {
        Connection conn = null;
        Statement stmt = null;
        try {
            conn = dataSource.getConnection();
            stmt = conn.createStatement();

            Map<String, String> tags = new HashMap<>();
            Map<String, Object> fields = new HashMap<>();
            Map<String, String> realtags = new HashMap<>();
            Map<String, Object> realfields = new HashMap<>();
            Map map_data = JsonUtils.fromJson(mqBaseVO.getData().toString(),Map.class);
            System.out.println("test11111");
            String deviceUUId = map_data.get("deviceUUId").toString();
            String productCode = map_data.get("productCode").toString().toLowerCase();
            Long timestamp = Long.valueOf(map_data.get("timestamp").toString());
            String tableName = "_"+deviceUUId;
            String STableName = "super_"+productCode;

            StringBuilder tagValue = new StringBuilder();
            Object tg = JSONObject.toJSONString(map_data.get("tags"));
            JSONObject tag = JSON.parseObject(tg.toString());
            for (String entry : tag.keySet()){
                tags.put(entry.toLowerCase(),tag.get(entry).toString());
                tagValue.append("'"+tag.get(entry).toString()+"',");
            }
            System.out.println("test33333"+tg.toString());

            Object met = JSONObject.toJSONString(map_data.get("metrics"));
            StringBuilder fieldName = new StringBuilder();
            StringBuilder fieldValue = new StringBuilder();
            JSONObject metrics = JSON.parseObject(met.toString());
            for(String entry : metrics.keySet()){
                fields.put(entry.toLowerCase(),metrics.get(entry));
                realfields.put(entry.toLowerCase(),Float.valueOf(metrics.get(entry).toString()));
                fieldName.append(","+entry.toLowerCase());
                fieldValue.append(","+metrics.get(entry).toString());
            }
            System.out.println("test44444"+met.toString());
            String sql = "insert into "+tableName+" using "+STableName+ " tags("+tagValue.toString().substring(0,tagValue.length()-1)+") (ts"+fieldName.toString()+") values ("+timestamp+fieldValue.toString()+")";
            stmt.execute(sql);

            //创建设备实时数据表，用于保存每个设备最新一条数据记录
            long realtimestamp = 1756828800000L;
            String realsql = "insert into datarealtime values("+ realtimestamp + " , '"+ deviceUUId + "', " + timestamp + " , '" + tags.get("device_id").toString() + "' )";
            stmt.execute(realsql);

            stmt.close();
            conn.close();

        }  catch (SQLException e) {
            // 处理异常
            System.err.println("SQL执行错误: " + e.getMessage());
            e.printStackTrace();

        } finally {
            // 必须在finally中关闭资源，确保无论是否发生异常都能释放
            // 先关闭Statement，再关闭Connection
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    System.err.println("关闭Statement失败: " + e.getMessage());
                }
            }
            if (conn != null) {
                try {
                    // 归还连接到连接池
                    conn.close();
                } catch (SQLException e) {
                    System.err.println("关闭Connection失败: " + e.getMessage());
                }
            }
        }
        return "";
    }
}
