package database

import (
	"github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"main/config"
	"main/model"
	"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
}

// UpdateDbStruct 数据库数据结构更新
func UpdateDbStruct() error {
	err = db.AutoMigrate(
		&model.Logs{},
		&model.Weather{},
		&model.DayKeys{},
		&model.JwtKeys{},
		&model.IpsLocation{},
		&model.User{},
		&model.Userinfo{},
		&model.UserAction{},
		&model.UserAutoLogin{},
		&model.LogFileDealLog{},
		&model.RunningCrontab{},
		&model.Balances{},
		&model.BalanceLogs{},
		&model.UserNotes{},
		&model.BackgammonRoom{},
		&model.SysInfo{},
		&model.SysInfoUpdateLog{},
		&model.ChessStatus{},
		&model.ChessStatusLog{},
		&model.Menus{},
		&model.SysIcons{},
		&model.SysSettings{},
		&model.SysError{},
		&model.Sudoku{},
		&model.SudokuStatus{},
		&model.SysLogs{},
	)
	if err != nil {
		logrus.Errorln("数据库自动迁移失败：", err)
	}
	return err
}

type MysqlConnectionPool struct {
}
