package com.shr.utils;

import java.sql.*;

import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;

import cn.hutool.core.lang.Console;


/**
 * 直接访问数据库
 * @author Administrator
 *
 */
public class DBHelper {

	private static DBHelper dbHelper=null;
	private Connection connection;
	private DataSourceProperties dataSource;
	private PreparedStatement preparedStatement;
	private ResultSet resultSet;
	
	private DBHelper() {
	}
	
	public static DBHelper createDBHelper(DataSourceProperties dataSource) {
	
		dbHelper = new DBHelper();
		dbHelper.dataSource = dataSource;
		Console.log("dataSource。url:" +  dataSource.getUrl());
		dbHelper.initDB();
		dbHelper.getConn();
		return dbHelper;
	}
	
	public void getConn() {
	
		try {
			connection = DriverManager.getConnection( dataSource.getUrl(), dataSource.getUsername(), dataSource.getPassword());
			connection.setAutoCommit(false);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	
	}
	
	public void close() {
	
		if (resultSet != null) {
			try {
				resultSet.close();
				if (preparedStatement != null) {
					preparedStatement.close();
				}
				if (connection != null) {
					connection.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	
	}
	
	public ResultSet executeQuery(String sql, Object[] params) {
		Console.log("sql:" +  dataSource.getUsername());
		dbHelper.setPrepareStatementParams(sql, params);
		try {
			Console.log("dataSource。username:" +  dataSource.getUsername());
			resultSet = preparedStatement.executeQuery();
			Console.log("dataSource。pawss:" +  dataSource.getPassword());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return resultSet;
	}
	
	public Boolean executeUpdate(String sql, Object[] params) {
	
		boolean result = false;
		dbHelper.setPrepareStatementParams(sql, params);
		try {
			if (preparedStatement.executeUpdate() > 0) {
				dbHelper.commit();
				result = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return result;
	
	}
	
	@SuppressWarnings("unused")
	private void setPrepareStatementParams(String sql, Object[] params) {
	
		try {
			preparedStatement = connection.prepareStatement(sql);
			if (params != null) {
				for (int i = 0; i < params.length; i++) {
					preparedStatement.setObject((i + 1), params[i]);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	
	}
	
	private void initDB() {
		try {
			Class.forName(dataSource.getDriverClassName());
			Console.log("dataSource。getDriverClassName:" +  dataSource.getDriverClassName());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	private void commit() {
	
		try {
			connection.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}