package main

import (
	"database/sql"
	"errors"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DbConnPools = make(map[string]*gorm.DB)

func setDb() (sql *sql.DB, err error) {
	db, err = InstanceDb(c.Dns)
	if err != nil {
		fatal("数据库连接失败:%v", err)
	}

	return db.DB()
}

func InstanceDb(dns string) (*gorm.DB, error) {
	var (
		dbConn *gorm.DB
		ok     bool
	)
	if dbConn, ok = DbConnPools[dns]; ok {
		sqlDB, _ := dbConn.DB()
		connTest := sqlDB.Ping()
		if connTest == nil {
			return nil, nil
		}
	}

	db, err := NewDb(&DbConfig{
		DriverName: "mysql",
		Dns:        dns,
		Debug:      true,
	})

	if err != nil {
		return nil, errors.New("s链接失败")
	}

	return db, nil
}

type DbConfig struct {
	DriverName   string
	Dns          string
	Debug        bool
	MaxIdleConns int
}

func NewDb(config *DbConfig, opt ...gorm.Option) (gorm *gorm.DB, err error) {
	gorm, err = config.Conn(opt...)
	return gorm, err
}

func (m *DbConfig) Conn(opt ...gorm.Option) (*gorm.DB, error) {
	dial := DriverMysql(m.Dns)

	db, err := gorm.Open(
		dial,
		opt...,
	)

	if err != nil {
		return nil, err
	}
	sqlDB, _ := db.DB()
	if m.Debug {
		db = db.Debug()
	}
	sqlDB.SetMaxIdleConns(3)  // 设置最大空闲连接数
	sqlDB.SetMaxOpenConns(10) // 设置最大打开连接数
	return db, nil
}

func DriverMysql(dns string) gorm.Dialector {
	return mysql.Open(dns + "")
}
