package cn.component.influxdb;

import cn.facade.constant.AtvConst;
import cn.util.core.IsKit;
import cn.util.core.LogKit;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.influxdb.InfluxDB;
import org.influxdb.dto.Point;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/** * InfluxDB写入工具 */
@Component
@Service
public class InfluxDbUtil {
    //策略
    private static String retentionPolicy = "";
    private static String INFLUXDB_DB = "test";//数据库
    private static InfluxDB influxDB;

    public static void setParam(String dbname,String retentionPolicy, InfluxDB influxDB) {
        InfluxDbUtil.INFLUXDB_DB = dbname;
        InfluxDbUtil.retentionPolicy = retentionPolicy;
        InfluxDbUtil.influxDB = influxDB;
    }

    /*
     * 执行shell语句
     *
     * @param command shell命令
     */
    public static QueryResult query(String command) {
        return influxDB.query(new Query(command, INFLUXDB_DB));
    }

    /**
     * 查询全表
     * @param tableName 表名
     */

    public QueryResult queryTable(String tableName) {
        StringBuilder str = new StringBuilder("select * from ");
        str.append(tableName);
        str.append(" order by time");
        String command = str.toString();
        return influxDB.query(new Query(command, INFLUXDB_DB));
    }

    /**
     * * 插入
     * * @param tags 标签
     * * @param fields 字段
     */

    public void insert(Map<String, String> tags, Map<String, Object> fields, String measurement) {
        Point.Builder builder = Point.measurement(measurement);
        builder.tag(tags);
        builder.fields(fields);
        influxDB.write(INFLUXDB_DB, "", builder.build());
    }

    /**
     * 创建自定义保留策略
     *
     * @param policyName  策略名
     * @param days        保存天数
     * @param replication 保存副本数量
     * @param isDefault   是否设为默认保留策略
     */
    public void createRetentionPolicy(String dataBaseName, String policyName, int days, int replication, Boolean isDefault) {
        String sql = String.format("CREATE RETENTION POLICY \"%s\" ON \"%s\" DURATION %sd REPLICATION %s ", policyName, dataBaseName, days, replication);
        if (isDefault) {
            sql = sql + " DEFAULT";
            retentionPolicy = policyName;
        }
        this.query(sql);
    }

    /**
     * * 设置数据保存策略
     * * defalut 策略名 /database 数据库名/ 30d 数据保存时限30天/ 1 副本个数为1/ 结尾DEFAULT 表示 设为默认的策略
     */
    public void createRetentionPolicy() {
        String command = String.format("CREATE RETENTION POLICY \"%s\" ON \"%s\" DURATION %s REPLICATION %s DEFAULT", "defalut", INFLUXDB_DB, "30d", 1);
        this.query(command);
    }

    public String getString(JSONObject jsonObject, String name) {
        String result = jsonObject.getString(name);
        return result == null ? "" : result;
    }

    String measurement;
    TimeUnit timeUnit;
    JSONObject jsonObj;

    /**
     * 插入数据
     *
     * @param measurement 表名
     * @param json        信息
     */
    public void insertJSON(String measurement, JSONObject json, TimeUnit timeUnit) {
        if (IsKit.isNullOrEmpty(json)) {
            LogKit.info("数据为空");
            return;
        }
        if (IsKit.isNullOrEmpty(measurement)) {
            LogKit.info("表名为空");
            return;
        }
        //表明类型---measurement确定一下
        this.measurement = measurement;
        //修改时间戳
        this.timeUnit = timeUnit;
        //修改保存策略
        if(retentionPolicy == ""){
            this.createRetentionPolicy("test","rp_365_days",365,1,true);
        }
        //批量插入设置



        this.jsonObj = null;
        //JSONArray
        try {
            //分支一
            if (Objects.equals(measurement, AtvConst.INFLUXDB_TABLE_BOARDCARD)) {
                _saveBoardcard(json);
                return;
            }
            //分支二
            if (Objects.equals(measurement, AtvConst.INFLUXDB_TABLE_CARRIAGE)) {
                _saveCarriage(json);
                return;
            }
            //分支三
            if (Objects.equals(measurement, AtvConst.INFLUXDB_TABLE_ALARMSTATE)) {
                _saveAlarmstate(json);
                return;
            }
            //分支四
            if (Objects.equals(measurement, AtvConst.INFLUXDB_TABLE_PUTCARD)) {
                _savePutcard(json);
                return;
            }
            //分支五
            if (Objects.equals(measurement, AtvConst.INFLUXDB_TABLE_PORT)) {
                _savePort(json);
                return;
            }
            //分支六
            if (Objects.equals(measurement, AtvConst.INFLUXDB_TABLE_TRUNK)) {
                _saveTrunk(json);
                return;
            }
            //分支七
            if (Objects.equals(measurement, AtvConst.INFLUXDB_TABLE_RINGNETWORK)) {
                _saveRingnetwork(json);
                return;
            }
            LogKit.info("表名错误");
        } catch (Exception e) {
            LogKit.info("ERROR" + json.toString());
        }
    }
/************************上************************************/
    private void _saveCarriage(JSONObject json)
	{
        jsonObj = json.getJSONObject("data");
        if (IsKit.isNull(jsonObj.getJSONArray(AtvConst.INFLUXDB_TABLE_CARRIAGE))) {
            return;
        }
        JSONArray carriages = jsonObj.getJSONArray(AtvConst.INFLUXDB_TABLE_CARRIAGE);
        //JSONArray alarmstate = JSONArray.parseArray(data.getString("alarmstate"));
        //对carriages字段循环插入
        //for (Object carr : carriages)
        for(int i = 0;i<carriages.size();i++)
		{
            if (IsKit.isNull(carriages.getJSONObject(i))) {
                continue;
            }

            JSONObject carriage = carriages.getJSONObject(i);

            Map<String, String> tags = new HashMap<>();
            Map<String, Object> fields = new HashMap<>();

            tags.put("cmd_code", getString(json, "cmd_code"));
            tags.put("country", getString(json, "country"));
            tags.put("cityNo", getString(json, "cityNo"));
            tags.put("metroLine", getString(json, "metroLine"));
            //tags.put("timestamp", json.getString("timestamp"));
            tags.put("vehicleNo", getString(json, "vehicleNo"));
            tags.put("carNo_1", getString(json, "carNo"));
            tags.put("deviceNo_1", getString(json, "deviceNo"));

            tags.put("carNo_2", getString(carriage, "carNo"));
            tags.put("deviceNo_2", getString(carriage, "deviceNo"));
            tags.put("LineID", getString(carriage, "LineID"));
            tags.put("startID", getString(carriage, "startID"));

            tags.put("terminalID", getString(carriage, "terminalID"));
            tags.put("nowID", getString(carriage, "nowID"));
            tags.put("PAstate", getString(carriage, "PAstate"));
            tags.put("PAmodel", getString(carriage, "PAmodel"));
            tags.put("MICmodel", getString(carriage, "MICmodel"));
            tags.put("PAcarMS", getString(carriage, "PAcarMS"));
            tags.put("carDirection", getString(carriage, "carDirection"));
            tags.put("PAupdown", getString(carriage, "PAupdown"));
            tags.put("emergentPAID", getString(carriage, "emergentPAID"));

            for (Map.Entry<String, String> entry : tags.entrySet()) {
                if (IsKit.isNull(entry.getValue())) {
                    LogKit.info(entry.getKey());
                }
            }

            fields.put("emergentPANO", carriage.getString("emergentPANO"));
            tags.put("PAstartflag", getString(carriage, "PAstartflag"));
            fields.put("playfilename", carriage.getString("playfilename"));
            fields.put("opendoorDir", carriage.getInteger("opendoorDir"));

            Point.Builder builder = Point.measurement(measurement);
            builder.tag(tags);
            builder.fields(fields);
            builder.time(json.getLong("timestamp"), timeUnit);
            influxDB.write(INFLUXDB_DB, InfluxDbUtil.retentionPolicy, builder.build());
        }
    }

    private void _saveBoardcard(JSONObject json)
	{
        jsonObj = json.getJSONObject("data");
        if (IsKit.isNull(jsonObj.getJSONArray(AtvConst.INFLUXDB_TABLE_BOARDCARD))) {
            return;
        }

        JSONArray boardCards = jsonObj.getJSONArray(AtvConst.INFLUXDB_TABLE_BOARDCARD);
        for (int i = 0 ; i<boardCards.size();i++)
		{
            if (IsKit.isNull(boardCards.getJSONObject(i))) {
                continue;
            }

            JSONObject boardCardInfo = (boardCards.getJSONObject(i));

            Map<String, String> tags = new HashMap<>();
            Map<String, Object> fields = new HashMap<>();

            tags.put("cmd_code", getString(json, "cmd_code"));

            tags.put("country", getString(json, "country"));
            tags.put("cityNo", getString(json, "cityNo"));
            tags.put("metroLine", getString(json, "metroLine"));
            //tags.put("timestamp", json.getString("timestamp"));
            tags.put("vehicleNo", getString(json, "vehicleNo"));
            tags.put("carNo_1", getString(json, "carNo"));
            tags.put("deviceNo_1", getString(json, "deviceNo"));
            tags.put("carNo_2", getString(jsonObj, "carNo"));
            tags.put("deviceNo_2", getString(jsonObj, "deviceNo"));


            //tags.put("RS485", boardCardInfo.getString("RS485"));
            tags.put("cardslotID", getString(boardCardInfo, "cardslotID"));
            tags.put("boardCardsNO", getString(boardCardInfo, "boardCardsNO"));
            tags.put("cardtype", getString(boardCardInfo, "cardtype"));
            for (Map.Entry<String, String> entry : tags.entrySet()) {
                if (IsKit.isNull(entry.getValue())) {
                    LogKit.info(entry.getKey());
                }
            }
            fields.put("RS485", boardCardInfo.getString("RS485"));
            fields.put("worktime", boardCardInfo.getInteger("worktime"));
            fields.put("voltage12", boardCardInfo.getDouble("voltage12"));
            fields.put("voltage5", boardCardInfo.getDouble("voltage5"));
            fields.put("voltage3v3", boardCardInfo.getDouble("voltage3v3"));
            fields.put("current12", boardCardInfo.getDouble("current12"));
            fields.put("current5", boardCardInfo.getDouble("current5"));
            fields.put("current3v3", boardCardInfo.getDouble("current3v3"));
            fields.put("temperature", boardCardInfo.getDouble("temperature"));
            fields.put("CAN1", boardCardInfo.getInteger("CAN1"));
            fields.put("CAN2", boardCardInfo.getInteger("CAN2"));
            fields.put("RS232No1", boardCardInfo.getInteger("RS232No1"));
            fields.put("RS232No2", boardCardInfo.getInteger("RS232No2"));
            fields.put("net1", boardCardInfo.getInteger("net1"));
            fields.put("net2", boardCardInfo.getInteger("net2"));
            fields.put("audiochannel1", boardCardInfo.getInteger("audiochannel1"));
            fields.put("audiochannel2", boardCardInfo.getInteger("audiochannel2"));
            fields.put("audiochannel3", boardCardInfo.getInteger("audiochannel3"));
            fields.put("audiochannel4", boardCardInfo.getInteger("audiochannel4"));
            fields.put("audiochannel5", boardCardInfo.getInteger("audiochannel5"));
            fields.put("audiochannel6", boardCardInfo.getInteger("audiochannel6"));
            fields.put("audiochannel7", boardCardInfo.getInteger("audiochannel7"));
            fields.put("audiochannel8", boardCardInfo.getInteger("audiochannel8"));
            fields.put("softVer", boardCardInfo.getString("softVer"));

            Point.Builder builder = Point.measurement(measurement);
            builder.tag(tags);
            builder.fields(fields);
            builder.time(json.getLong("timestamp"), timeUnit);
            influxDB.write("test", InfluxDbUtil.retentionPolicy, builder.build());
        }
    }

    private void _saveAlarmstate(JSONObject json)
	{
        jsonObj = json.getJSONObject("data");
        if (IsKit.isNull(jsonObj.getJSONArray(AtvConst.INFLUXDB_TABLE_ALARMSTATE))) {
            return;
        }
        JSONArray alarmstate = jsonObj.getJSONArray(AtvConst.INFLUXDB_TABLE_ALARMSTATE);
        //for (Object obj : alarmstate)
        for(int i = 0; i<alarmstate.size();i++)
		{
//            if (obj.toString().equals("{}")) {
//                continue;
//            }
            if (IsKit.isNull(alarmstate.getJSONObject(i))) {
                continue;
            }

            Map<String, String> tags = new HashMap<>();
            Map<String, Object> fields = new HashMap<>();

            JSONObject alarm = alarmstate.getJSONObject(i);
            tags.put("cmd_code", getString(json, "cmd_code"));
            tags.put("country", getString(json, "country"));
            tags.put("cityNo", getString(json, "cityNo"));
            tags.put("metroLine", getString(json, "metroLine"));
            //tags.put("timestamp", json.getString("timestamp"));
            tags.put("vehicleNo", getString(json, "vehicleNo"));
            tags.put("carNo_1", getString(json, "carNo"));
            tags.put("deviceNo_1", getString(json, "deviceNo"));

            tags.put("carNo_2", getString(alarm, "carNo"));
            tags.put("deviceNo_2", getString(alarm, "deviceNo"));
            //?
            for (Map.Entry<String, String> entry : tags.entrySet()) {
                if (IsKit.isNull(entry.getValue())) {
                    LogKit.info(entry.getKey());
                }
            }

            fields.put("state", alarm.getString("state"));

            Point.Builder builder = Point.measurement(measurement);
            builder.tag(tags);
            builder.fields(fields);
            builder.time(json.getLong("timestamp"), timeUnit);
            influxDB.write(INFLUXDB_DB, InfluxDbUtil.retentionPolicy, builder.build());
        }
    }

    private void _savePutcard(JSONObject json)
	{
        JSONArray jsonArray = json.getJSONArray("data");

		for (int i = 0;i<jsonArray.size();i++)
		{

            if (IsKit.isNull(jsonArray.getJSONObject(i))) {
                continue;
            }


            Map<String, String> tags = new HashMap<>();
            Map<String, Object> fields = new HashMap<>();
            JSONObject data_obj = jsonArray.getJSONObject(i);

            tags.put("cmd_code", getString(json, "cmd_code"));
            tags.put("country", getString(json, "country"));
            tags.put("cityNo", getString(json, "cityNo"));
            tags.put("metroLine", getString(json, "metroLine"));
            //tags.put("timestamp", getString(json,"timestamp"));
            tags.put("vehicleNo", getString(json, "vehicleNo"));
            tags.put("carNo_1", getString(json, "carNo"));
            tags.put("deviceNo_1", getString(json, "deviceNo"));
            //JSONObject data_obj = data.getJSONObject(0);
            tags.put("carNo_2", getString(data_obj, "carNo"));
            tags.put("deviceNo_2", getString(data_obj, "deviceNo"));
            tags.put("state", getString(data_obj, "state"));
            fields.put("version", getString(data_obj, "version"));
            tags.put("playstate", getString(data_obj, "playstate"));

            for (Map.Entry<String, String> entry : tags.entrySet()) {
                if (IsKit.isNull(entry.getValue())) {
                    LogKit.info(entry.getKey());
                }
            }
            fields.put("updatestate", data_obj.getInteger("updatestate"));

            Point.Builder builder = Point.measurement(measurement);
            builder.tag(tags);
            builder.fields(fields);
            builder.time(json.getLong("timestamp"), timeUnit);
            influxDB.write(INFLUXDB_DB, InfluxDbUtil.retentionPolicy, builder.build());
        }
    }

    private void _savePort(JSONObject json)
	{
        jsonObj = json.getJSONObject("data");
        if (IsKit.isNull(jsonObj.getJSONArray("port"))) {
            return;
        }
        JSONArray Port = jsonObj.getJSONArray("port");
        for (int i=0;i<Port.size();i++)
		{
            if (IsKit.isNull(Port.getJSONObject(i))) {
                continue;
            }
            Map<String, String> tags = new HashMap<>();
            Map<String, Object> fields = new HashMap<>();
            JSONObject po = Port.getJSONObject(i);

            tags.put("cmd_code", getString(json, "cmd_code"));

            tags.put("country", getString(json, "country"));
            tags.put("cityNo", getString(json, "cityNo"));
            tags.put("metroLine", getString(json, "metroLine"));
            //tags.put("timestamp", json.getString("timestamp"));
            tags.put("vehicleNo", getString(json, "vehicleNo"));
            tags.put("carNo", getString(json, "carNo"));
            tags.put("deviceNo", getString(json, "deviceNo"));

            tags.put("mac", getString(jsonObj, "mac"));
            tags.put("ip", getString(jsonObj, "mac"));
            //
            tags.put("errorMessage", getString(jsonObj, "errorMessage"));
            tags.put("errorCode", getString(jsonObj, "errorCode"));
            tags.put("errorCode", getString(jsonObj, "errorCode"));
            fields.put("netmask", getString(jsonObj, "netmask"));
            fields.put("software_ver", getString(jsonObj, "software_ver"));

            tags.put("ID", getString(po, "ID"));
            tags.put("PortStatus", getString(po, "PortStatus"));
            fields.put("totalTXByte", getString(po, "totalTXByte"));
            fields.put("totalRXByte", getString(po, "totalRXByte"));
            fields.put("rxUNI", getString(po, "rxUNI"));
            fields.put("rxMULT", getString(po, "rxMULT"));
            fields.put("rxBRD", getString(po, "rxBRD"));
            fields.put("txUNI", getString(po, "txUNI"));
            fields.put("txMULT", getString(po, "txMULT"));
            fields.put("txBRD", getString(po, "txBRD"));

            for (Map.Entry<String, String> entry : tags.entrySet()) {
                if (IsKit.isNull(entry.getValue())) {
                    LogKit.info(entry.getKey());
                }
            }
            Point.Builder builder = Point.measurement(measurement);
            builder.tag(tags);
            builder.fields(fields);
            builder.time(json.getLong("timestamp"), timeUnit);
            influxDB.write(INFLUXDB_DB, InfluxDbUtil.retentionPolicy, builder.build());
        }
    }

    private void _saveTrunk(JSONObject json)
	{
        jsonObj =json.getJSONObject("data");

        if (IsKit.isNull(jsonObj.getJSONArray("TRUNK"))) {
            return;
        }
        JSONArray TRUNK = jsonObj.getJSONArray("TRUNK");
        for (int i=0;i<TRUNK.size();i++)
		{
            if (IsKit.isNull(TRUNK.getJSONObject(i))) {
                continue;
            }
            Map<String, String> tags = new HashMap<>();
            Map<String, Object> fields = new HashMap<>();
            JSONObject tru = TRUNK.getJSONObject(i);

            tags.put("cmd_code", getString(json, "cmd_code"));
            tags.put("country", getString(json, "country"));
            tags.put("cityNo", getString(json, "cityNo"));
            tags.put("metroLine", getString(json, "metroLine"));
            //tags.put("timestamp", json.getString("timestamp"));
            tags.put("vehicleNo", getString(json, "vehicleNo"));
            tags.put("carNo", getString(json, "carNo"));
            tags.put("deviceNo", getString(json, "deviceNo"));

            tags.put("mac", getString(jsonObj, "mac"));
            tags.put("ip", getString(jsonObj, "mac"));
            //
            tags.put("errorMessage", getString(jsonObj, "errorMessage"));
            tags.put("errorCode", getString(jsonObj, "errorCode"));
            tags.put("errorCode", getString(jsonObj, "errorCode"));
            fields.put("netmask", getString(jsonObj, "netmask"));
            fields.put("software_ver", getString(jsonObj, "software_ver"));

            tags.put("group", getString(tru, "group"));
            tags.put("Enable", getString(tru, "group"));
            tags.put("port", getString(tru, "port"));

            for (Map.Entry<String, String> entry : tags.entrySet()) {
                if (IsKit.isNull(entry.getValue())) {
                    LogKit.info(entry.getKey());
                }
            }
            Point.Builder builder = Point.measurement(measurement);
            builder.tag(tags);
            builder.fields(fields);
            builder.time(json.getLong("timestamp"), timeUnit);
            influxDB.write(INFLUXDB_DB, InfluxDbUtil.retentionPolicy, builder.build());
        }
    }

    private void _saveRingnetwork(JSONObject json)
	{
        jsonObj = json.getJSONObject("data");
        if (IsKit.isNull(jsonObj.getJSONArray("RingNetwork"))) {
            return;
        }

        JSONArray Network = jsonObj.getJSONArray("RingNetwork");
        for (int i=0;i<Network.size();i++) {
            if (IsKit.isNull(Network.getJSONObject(i))) {
                continue;
            }
            Map<String, String> tags = new HashMap<>();
            Map<String, Object> fields = new HashMap<>();
            JSONObject net = Network.getJSONObject(i);

            tags.put("cmd_code", getString(json, "cmd_code"));
            tags.put("country", getString(json, "country"));
            tags.put("cityNo", getString(json, "cityNo"));
            tags.put("metroLine", getString(json, "metroLine"));
            //tags.put("timestamp", json.getString("timestamp"));
            tags.put("vehicleNo", getString(json, "vehicleNo"));
            tags.put("carNo", getString(json, "carNo"));
            tags.put("deviceNo", getString(json, "deviceNo"));

            tags.put("mac", getString(jsonObj, "mac"));
            tags.put("ip", getString(jsonObj, "mac"));
            //
            tags.put("errorMessage", getString(jsonObj, "errorMessage"));
            tags.put("errorCode", getString(jsonObj, "errorCode"));
            tags.put("errorCode", getString(jsonObj, "errorCode"));
            fields.put("netmask", getString(jsonObj, "netmask"));
            fields.put("software_ver", getString(jsonObj, "software_ver"));

            tags.put("group", getString(net, "group"));
            tags.put("RingState", getString(net, "RingState"));
            tags.put("MasterMAc", getString(net, "MasterMAc"));
            tags.put("Port1State", getString(net, "Port1State"));
            tags.put("Port2State", getString(net, "Port2State"));

            for (Map.Entry<String, String> entry : tags.entrySet()) {
                if (IsKit.isNull(entry.getValue())) {
                    LogKit.info(entry.getKey());
                }
            }
            Point.Builder builder = Point.measurement(measurement);
            builder.tag(tags);
            builder.fields(fields);
            builder.time(json.getLong("timestamp"), timeUnit);
            influxDB.write(INFLUXDB_DB, InfluxDbUtil.retentionPolicy, builder.build());
        }
    }
    /******************************************上界*********************************************************/

    //cmd_17
    private void _savecrowed(JSONObject json){
        jsonObj = json.getJSONObject("data");
        if (IsKit.isNull(jsonObj)){
            return;
        }
        Map<String, String> tags = new HashMap<>();
        //Map<String, Object> fields = new HashMap<>();

        tags.put("cmd_code", getString(json, "cmd_code"));
        tags.put("country", getString(json, "country"));
        tags.put("cityNo", getString(json, "cityNo"));
        tags.put("metroLine", getString(json, "metroLine"));
        //tags.put("timestamp", json.getString("timestamp"));
        tags.put("vehicleNo", getString(json, "vehicleNo"));
        tags.put("carNo", getString(json, "carNo"));
        tags.put("deviceNo", getString(json, "deviceNo"));

        for (Map.Entry<String,Object> entry : jsonObj.entrySet()){
            if(entry.getKey().startsWith("crowed")) {
                String s = entry.getKey();
                char num = s.charAt(s.length()-1);
                Map<String, Object> fields = new HashMap<>();
                tags.put("CarNo_2", "" + num + "");
                fields.put("cold_mode", jsonObj.getString("cold_mode"+num));
                //fields.put("crowds",entry.getValue());

                fields.put("crowds",s);
                for (Map.Entry<String, String> entry1: tags.entrySet()) {
                    if (IsKit.isNull(entry1.getValue())) {
                        LogKit.info(entry1.getKey());
                    }
                }
                Point.Builder builder = Point.measurement(measurement);
                builder.tag(tags);
                builder.fields(fields);
                builder.time(json.getLong("timestamp"), timeUnit);
                influxDB.write(INFLUXDB_DB, InfluxDbUtil.retentionPolicy, builder.build());
            }
        }
    }

    //cmd_18
    private void _saveCommand(JSONObject json){
        jsonObj = json.getJSONObject("data");
        if (IsKit.isNull(jsonObj.getJSONArray("alarmstate"))) {
            LogKit.info("cmd_code18--the message of alarmstate is NULL");
            return;
        }

        JSONArray alarmstate = jsonObj.getJSONArray("alarmstate");
        for(int i=0; i<alarmstate.size();i++){

            Map<String, String> tags = new HashMap<>();
            Map<String, Object> fields = new HashMap<>();

            tags.put("cmd_code", getString(json, "cmd_code"));
            tags.put("country", getString(json, "country"));
            tags.put("cityNo", getString(json, "cityNo"));
            tags.put("metroLine", getString(json, "metroLine"));
            //tags.put("timestamp", json.getString("timestamp"));
            tags.put("vehicleNo", getString(json, "vehicleNo"));
            tags.put("carNo", getString(json, "carNo"));
            tags.put("deviceNo", getString(json, "deviceNo"));

            JSONObject alarm = alarmstate.getJSONObject(i);

            fields.put("PAmodel",jsonObj.getInteger("PAmodel"));
            fields.put("MICmodel",jsonObj.getInteger("MICmodel"));
            tags.put("carNo_2",getString(alarm,"carNo"));
            tags.put("deviceNo_2",getString(alarm,"deviceNo_2"));
            fields.put("state",alarm.getInteger("state"));

            for (Map.Entry<String, String> entry : tags.entrySet()) {
                if (IsKit.isNull(entry.getValue())) {
                    LogKit.info(entry.getKey());
                }
            }
            Point.Builder builder = Point.measurement(measurement);
            builder.tag(tags);
            builder.fields(fields);
            builder.time(json.getLong("timestamp"), timeUnit);
            influxDB.write(INFLUXDB_DB, InfluxDbUtil.retentionPolicy, builder.build());
        }
    }
    private void _saveListener(JSONObject json){
        jsonObj = json.getJSONObject("data");
        if (IsKit.isNull(jsonObj)){
            LogKit.info("cmd_code20--the message of data is NULL");
            return;
        }

        Map<String, String> tags = new HashMap<>();
        Map<String, Object> fields = new HashMap<>();

        tags.put("cmd_code", getString(json, "cmd_code"));
        tags.put("country", getString(json, "country"));
        tags.put("cityNo", getString(json, "cityNo"));
        tags.put("metroLine", getString(json, "metroLine"));
        //tags.put("timestamp", json.getString("timestamp"));
        tags.put("vehicleNo", getString(json, "vehicleNo"));
        tags.put("carNo", getString(jsonObj, "carNo"));
        tags.put("deviceNo", getString(jsonObj, "deviceNo"));

        fields.put("state",jsonObj.getInteger("state"));

        for (Map.Entry<String, String> entry : tags.entrySet()) {
            if (IsKit.isNull(entry.getValue())) {
                LogKit.info(entry.getKey());
            }
        }
        Point.Builder builder = Point.measurement(measurement);
        builder.tag(tags);
        builder.fields(fields);
        builder.time(json.getLong("timestamp"), timeUnit);
        influxDB.write(INFLUXDB_DB, InfluxDbUtil.retentionPolicy, builder.build());
    }

    /**
     * * 删除
     * * @param command 删除语句
     * * @return 返回错误信息
     */
    public String deleteMeasurementData(String command) {
        QueryResult result = influxDB.query(new Query(command, INFLUXDB_DB));
        return result.getError();
    }

    /**
     * 创建数据库
     *
     * @param dbName 数据库名字
     */
    @SuppressWarnings("deprecation")
    public void createDB(String dbName) {
        influxDB.createDatabase(dbName);
    }

    /**
     * 删除数据库
     *
     * @param dbName 数据库名字
     */

    @SuppressWarnings("deprecation")
    public void deleteDB(String dbName) {
        influxDB.deleteDatabase(dbName);
    }

    /**
     * 删除表
     *
     * @param tableName 删除表
     * @return
     */
    public QueryResult deleteTable(String tableName) {
        StringBuilder str = new StringBuilder("DELETE from ");
        str.append(tableName);
        String command = str.toString();
        return influxDB.query(new Query(command, INFLUXDB_DB));
    }

    public void setDatabase(String database) {
        INFLUXDB_DB = database;
    }

    public String getRetentionPolicy() {
        return retentionPolicy;
    }

    public void setRetentionPolicy(String retentionPolicy) {
        InfluxDbUtil.retentionPolicy = retentionPolicy;
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String getCurrentDateStr() {
        Date date = new Date();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestr = sf.format(date);
        return timestr;
    }
}
