package database

import (
	"github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"main/config"
	"sync"
)

var instance *MysqlConnectionPool
var once sync.Once
var db *gorm.DB
var err error

// GetInstance 获取数据库连接池
func GetInstance() *MysqlConnectionPool {
	once.Do(func() {
		instance = &MysqlConnectionPool{}
	})
	return instance
}

// InitDataPool 数据库初始化连接
func (m *MysqlConnectionPool) InitDataPool() (isSuccess bool) {
	dbConfig := config.Config.Database
	if dbConfig.Prd {
		db, err = gorm.Open(mysql.Open(dbConfig.Dsn), &gorm.Config{})
	} else {
		db, err = gorm.Open(mysql.Open(dbConfig.Dsn), &gorm.Config{
			Logger: logger.Default.LogMode(logger.Info),
		})
	}
	if err != nil {
		logrus.Errorln("数据库配置失败：", err)
		return false
	}
	return true
}

// GetMysqlDb 获取数据库连接
func (m *MysqlConnectionPool) GetMysqlDb() (dbCon *gorm.DB) {
	return db
}

type MysqlConnectionPool struct {
}
