package db

import (
	"fmt"
	"gopkg.in/yaml.v3"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
	"time"
)

var (
	config *Config
	dbList []*gorm.DB
)

func ConnectDB() {
	_loadConfig()
	_goConnectDB()
}

func CopyData() {
	if len(dbList) == 0 {
		panic("dbList is nil")
	}

	timeNow := time.Now().Add(-5 * 24 * time.Hour)
	format := timeNow.Format("2006-01-02")
	parse, _ := time.Parse("2006-01-02", format)

	fmt.Println("Copy data from", parse)

	for _, db := range dbList {
		copyOrders(db, parse)
		time.Sleep(time.Second * 2)
		copyPayDetails(db, parse)
		time.Sleep(time.Second * 2)
		copyUserMoneyDetails(db, parse)
		time.Sleep(time.Second * 2)
		//copyCourseCollect(db, parse)
		//time.Sleep(time.Second * 2)
		//copyCourseUser(db, parse)
		//time.Sleep(time.Second * 2)
		copyDiscSpinningRecord(db, parse)
		time.Sleep(time.Second * 2)
		copyCashOut(db, parse)
		time.Sleep(time.Second * 2)
		copySysUserMoneyDetails(db, parse)
		time.Sleep(time.Second * 2)
	}
}

func DisconnectDB() {
	for _, db := range dbList {
		s, err := db.DB()
		if err != nil {
			continue
		}
		_ = s.Close()
	}

	fmt.Println("Disconnect to DB success")
}

func _loadConfig() {
	// 读取YAML文件内容
	yamlFile, err := os.ReadFile("db_config.yml")
	if err != nil {
		panic(err)
	}

	c := &Config{}
	err = yaml.Unmarshal(yamlFile, c)
	if err != nil {
		panic(err)
	}

	config = c
}

func _goConnectDB() {
	if config == nil {
		panic("config is nil")
	}

	if config.Env != "dev" && config.Env != "prod" {
		panic("config.Env is not valid")
	}

	configInfo := config.Dev
	if config.Env == "prod" {
		configInfo = config.Prod
	}

	for _, dbInfo := range configInfo.Dbs {
		connectUrl := _getDbConnectUrl(configInfo, dbInfo)
		db, err := gorm.Open(mysql.Open(connectUrl))
		if err != nil {
			panic(err)
		}
		dbList = append(dbList, db)
	}

	fmt.Println("Connect to DB success")
}

func _getDbConnectUrl(configInfo *ConnectInfo, dbName string) string {
	return configInfo.Name +
		":" +
		configInfo.Password +
		"@tcp(" + configInfo.Host + ":" + configInfo.Port + ")/" +
		dbName +
		"?charset=utf8mb4&parseTime=True&loc=Local"
}
