package database

import (
	"exhibitionCentre/config"
	"exhibitionCentre/logging"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB *gorm.DB

func init() {
	var err error
	if DB, err = initDB(); err != nil {
		logging.Log.Fatalf("连接Mysql数据库失败: %s\n", err.Error())
	}
	logging.Log.Info("连接Mysql数据库完成.")
}

func mysqlConfigString() (string, int, int) {
	dbuser := config.Config.Mysql.UserName
	dbpwd := config.Config.Mysql.Password
	dbname := config.Config.Mysql.Database
	dbhost := config.Config.Mysql.Host
	maxidle := config.Config.Mysql.MaxIdle
	maxconn := config.Config.Mysql.MaxConn
	conn := dbuser + ":" + dbpwd + "@tcp(" + dbhost + ")/" + dbname + "?parseTime=true&charset=utf8&loc=Local"
	return conn, maxidle, maxconn
}

func initDB() (*gorm.DB, error) {
	dbDSN, maxidle, maxconn := mysqlConfigString()

	db, err := gorm.Open(mysql.Open(dbDSN), &gorm.Config{}) //("mysql", sqlCfgStr)
	if err != nil {
		logging.Log.Error("open db failed: ", err)
		return nil, err
	}

	sqlDB, err := db.DB()
	if err != nil {
		logging.Log.Error("获取DB失败: ", err)
		return nil, err
	}
	sqlDB.SetMaxIdleConns(maxidle)
	sqlDB.SetMaxOpenConns(maxconn)
	sqlDB.SetConnMaxLifetime(time.Hour)

	return db, nil
}
