/*
 * @description:
 * @Author: CP
 * @Date: 2020-08-20 22:25:17
 * @FilePath: \construction_management\datasource\dbhelper.go
 */
package datasource

import (
	"fmt"
	"log"
	"sync"

	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"github.com/spf13/viper"
	"go.mod/conf"
	"go.mod/web/utils"
)

//互斥锁
var dbLock sync.Mutex
var masterInstance *xorm.Engine

//单例模式
func InstanceDbMaster() *xorm.Engine {
	if masterInstance != nil {
		return masterInstance
	}
	dbLock.Lock()
	defer dbLock.Unlock()
	if masterInstance != nil {
		return masterInstance
	}
	return NewDbMaster()
}

func NewDbMaster() *xorm.Engine {

	debug := utils.GetEnvInfo("DEBUG")
	configFilePrefix := "config"
	configFileName := fmt.Sprintf("%s-pro.yaml", configFilePrefix)

	if debug == "qa" || debug == "mbp" {
		fmt.Println("读取QA配置文件成功")
		configFileName = fmt.Sprintf("%s-debug.yaml", configFilePrefix)
	} else if debug == "uat" {
		fmt.Println("读取UAT配置文件成功")
		configFileName = fmt.Sprintf("%s-uat.yaml", configFilePrefix)
	} else {
		fmt.Println("读取PROD配置文件成功")
	}

	v := viper.New()
	v.SetConfigFile(configFileName)
	if err := v.ReadInConfig(); err != nil {
		log.Fatal("读取配置文件出错:", err)
		return nil
	}

	if err := v.Unmarshal(&conf.MysqlConfig); err != nil {
		panic(err)
	}
	fmt.Println(conf.MysqlConfig)
	sourcename := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",
		conf.MysqlConfig.User,
		conf.MysqlConfig.Pwd,
		conf.MysqlConfig.Host,
		conf.MysqlConfig.Port,
		conf.MysqlConfig.Datebase)
	instance, err := xorm.NewEngine(conf.DriverName, sourcename)
	if err != nil {
		log.Fatal("dbhelper.NewDbMaster NewEngine error ", err)
		return nil
	}
	//展示执行的sql语句
	instance.ShowSQL(true)
	masterInstance = instance
	return instance
}
