package com.fastbee.iot.tdengine.init;

import com.fastbee.iot.tdengine.config.TDengineConfig;
import com.fastbee.iot.tdengine.service.ILogService;
import com.taosdata.jdbc.TSDBDriver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

/**
 * 类名: ApplicationStarted
 * 时间: 2022/5/18,0018 1:41
 * 开发人: wxy
 */
@Slf4j
@Component
public class ApplicationStarted {
    @Autowired
    private ILogService tdLogService;
    @Autowired
    private TDengineConfig tDengineConfig;

    @PostConstruct
    public void run() {
        //先获取TDengine的配置，检测TDengine是否已经配置
        if (tDengineConfig.isEnabled()) {
            initTDengine(tDengineConfig.getDbName());
            log.info("使用TDengine存储设备数据，初始化成功");
        } else {
            log.info("使用MySql存储设备数据，初始化成功");
        }
    }

    /**
     * @return
     * @Method
     * @Description 开始初始化加载系统参数, 创建数据库和超级表
     * @Param null
     * @date 2022/5/22,0022 14:27
     * @author wxy
     */
    public void initTDengine(String dbName) {
        try {
            createDatabase();
            //创建数据库表
            tdLogService.createSTable(dbName);
            log.info("完成超级表的创建");
        } catch (Exception e) {
            log.error("错误", e.getMessage());
            e.printStackTrace();
        }

    }

    /**
     * @return
     * @Method
     * @Description 根据数据库连接自动创建数据库
     * @Param null
     * @date 2022/5/24,0024 14:32
     * @author wxy
     */
    private void createDatabase() {
        try {
            String jdbcUrl = tDengineConfig.getUrl();
            String dbName = tDengineConfig.getDbName();
            String username = tDengineConfig.getUsername();
            String password = tDengineConfig.getPassword();
            jdbcUrl += ("&user=" + username);
            jdbcUrl += ("&password=" + password);
            int startIndex = jdbcUrl.indexOf('/', 12);
            int endIndex = jdbcUrl.indexOf('?');
            String newJdbcUrl = jdbcUrl.substring(0, startIndex);
            newJdbcUrl = newJdbcUrl + jdbcUrl.substring(endIndex);
            log.info(newJdbcUrl);
            Properties connProps = new Properties();
            connProps.setProperty(TSDBDriver.PROPERTY_KEY_CHARSET, "UTF-8");
            connProps.setProperty(TSDBDriver.PROPERTY_KEY_LOCALE, "en_US.UTF-8");
            connProps.setProperty(TSDBDriver.PROPERTY_KEY_TIME_ZONE, "UTC-8");
            Connection conn = DriverManager.getConnection(newJdbcUrl, connProps);
            conn.createStatement().execute(String.format("create database  if not exists  %s;", dbName));
            conn.close();
            log.info("完成数据库创建");
        } catch (Exception e) {
            log.info("错误", e.getMessage());
            e.printStackTrace();
        }
    }
}
