package inits

import (
	"database/sql"
	"errors"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlserver"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"ppms-fj/configs/models"
)

// DBOption 数据库连接信息实体类
type DBOption struct {
	dBServer     string
	user         string
	password     string
	dBPort       int
	dBName       string
	dBType       string
	maxOpenConns int
	maxIdleConns int
}

func NewDBOption(dbConf *models.DB) *DBOption {
	return &DBOption{
		dBType:       dbConf.DBType,
		dBServer:     dbConf.DBServer,
		dBPort:       dbConf.DBPort,
		user:         dbConf.DBUser,
		password:     dbConf.DBPwd,
		dBName:       dbConf.DBName,
		maxOpenConns: dbConf.MaxOpenConns,
		maxIdleConns: dbConf.MaxIdleConns,
	}
}

// GetConnect 获取数据库连接
func (db *DBOption) GetConnect() (*sql.DB, error) {
	if db.dBType == "mssql" {
		dsn := fmt.Sprintf("server=%s;port=%d;user id=%s;password=%s;database=%s", db.dBServer, db.dBPort, db.user, db.password, db.dBName)
		return sql.Open("mssql", dsn)
	} else if db.dBType == "mysql" {
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", db.user, db.password, db.dBServer, db.dBPort, db.dBName)
		return sql.Open("mysql", dsn)
	}
	return nil, errors.New("this dbtype is not supported")
}

// GetGormConnect 获取Gorm数据库连接
func (db *DBOption) GetGormConnect() (*gorm.DB, error) {
	if db.dBType == "mssql" {
		dsn := fmt.Sprintf("sqlserver://%s:%s@%s:%d?database=%s&encrypt=disable", db.user, db.password, db.dBServer, db.dBPort, db.dBName)
		return gorm.Open(sqlserver.Open(dsn), &gorm.Config{
			Logger: logger.Default.LogMode(logger.Error),
		})
	} else if db.dBType == "mysql" {
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true", db.user, db.password, db.dBServer, db.dBPort, db.dBName)
		return gorm.Open(mysql.Open(dsn), &gorm.Config{
			Logger: logger.Default.LogMode(logger.Error),
		})
	}
	return nil, errors.New("this dbtype is not supported")
}
