package com.skyversation.poiaddr.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DbConnection {
    private static DbConnection dbConnection;
    public Connection connection;

    public static DbConnection getInstance() {
        if (dbConnection == null) {
            return new DbConnection();
        }
        return dbConnection;
    }

    private Statement stmt;
    @Value("${app.db.username}")
    private String db_user_name;
    @Value("${app.db.password}")
    private String db_password;
    @Value("${app.db.driver}")
    private String jdbcDriver;
    @Value("${app.db.jdbc_url}")
    private String jdbcURL;

    @PostConstruct
    public void initDbConnection() throws SQLException {
//      加载驱动
        System.out.println("加载驱动！");
        dbConnection = this;
        try {
            Class.forName(jdbcDriver);
        } catch (Exception e) {
            System.err.println("加载驱动异常：" + e);
            System.exit(1);
        }
        System.out.println("配置文件中的数据库用户名：" + db_user_name + "；密码：" + db_password);
        connection = DriverManager.getConnection(jdbcURL, db_user_name, db_password);
        stmt = connection.createStatement();

    }

    public int updateSql(String sqlStr) throws SQLException {
//        System.out.println("执行更新操作sql：" + sqlStr);
        return stmt.executeUpdate(sqlStr);
    }

    public List<Map<String, Object>> runSqlStr(String sqlStr) throws SQLException {
        ResultSet rs = stmt.executeQuery(sqlStr);
        ResultSetMetaData rsmd = rs.getMetaData();
        int size = rsmd.getColumnCount();
        List<Map<String, Object>> requestData = new ArrayList<>();
        while (rs.next()) {
            Map<String, Object> dataItem = new HashMap<>();
            for (int i = 0; i < size; i++) {
                dataItem.put(rsmd.getColumnName(i + 1), rs.getString(i + 1));
            }
            requestData.add(dataItem);
        }
        rs.close();
        return requestData;
    }
}
