package toolmigrate

import (
	"context"
	"fmt"

	"github.com/go-redis/redis/v8"
	_ "github.com/go-sql-driver/mysql"
	csnowflake "github.com/mhaya/extend/snowflake"
	"github.com/mhaya/game/game_cluster/internal/constant"
	"github.com/mhaya/game/game_cluster/internal/data"
	"github.com/mhaya/game/game_cluster/internal/mdb/models"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var Mdb *mongo.Client
var RDB redis.UniversalClient

func InsertMongoPlayer(userS []FaUser) error {
	var playerData []*models.Player
	var docs []interface{}
	// 格式化数据存入mongodb
	for _, user := range userS {
		result, err := RDB.Get(context.Background(), user.Username).Result()
		if err != nil {
			return err
		}
		pid, err := RDB.Get(context.Background(), user.Pid).Result()
		if err != nil || pid == "" {
			pid = ""
		}
		var item = make(map[int]*models.Item)
		ret := data.ItemConfig.GetMap()
		for k, v := range ret {
			item[k] = &models.Item{
				ID:       v.ID,
				ItemType: v.Type,
				ItemKey:  v.ItemKey,
			}
			delete(item, models.ItemAllRoll)
		}

		pl := &models.Player{
			UserName:      result,
			OpenId:        user.Username,
			UserNameMaybe: user.Nickname,
			XID:           user.XId,
			JoinIP:        user.Joinip,
			Pid:           pid,
			JoinTime:      user.Jointime,
			CreateTime:    user.Createtime,
			TonWall:       user.Tonwall,
			UpdateTime:    user.Updatetime,
			Level:         int(user.Level),
			Item:          item,
		}
		pl.Item.AddItem([]data.ItemReward{{ItemID: models.ItemScore, ItemBaseType: 1, Amount: int(user.Score)}})
		pl.Item.AddItem([]data.ItemReward{{ItemID: models.ItemGold, ItemBaseType: 1, Amount: int(user.Roll)}})
		pl.Item.AddItem([]data.ItemReward{{ItemID: models.ItemInvite, ItemBaseType: 3, Amount: int(user.Invite)}})
		pl.Item.AddItem([]data.ItemReward{{ItemID: models.ItemDrawsNumber, ItemBaseType: 1, Amount: int(user.Drawsnumber)}})
		pl.Item.AddItem([]data.ItemReward{{ItemID: models.ItemTon, ItemBaseType: 1, Amount: MoneyRatioFloat64(user.WallTon)}})
		pl.Item.AddItem([]data.ItemReward{{ItemID: models.ItemU, ItemBaseType: 1, Amount: MoneyRatioFloat64(user.WallU)}})
		item[1].MaxNum = int(user.Allroll)
		playerData = append(playerData, pl)

	}
	// 将 playerData 转换为 []interface{} 类型
	docs = make([]interface{}, len(playerData))
	for i, player := range playerData {
		docs[i] = player
	}
	// 批量插入MongoDB
	collection := Mdb.Database("db_mhaya").Collection("player")
	_, err := collection.InsertMany(context.Background(), docs)
	if err != nil {
		return err
	}
	return nil
}

func MoneyRatioFloat64(f float64) int {
	return int(f * constant.MoneyRatio)
}

func InsertMongoBD() error {
	var userS []FaUser
	db, err := connectToDatabase()
	if err != nil {
		return err
	}
	db.Table("fa_user").Find(&userS)

	err = InsertMongoAccount(userS)
	if err != nil {
		return err
	}
	err = InsertMongoPlayer(userS)
	if err != nil {
		return err
	}
	return nil
}

func GetRedisConnect() {
	RDB = redis.NewUniversalClient(&redis.UniversalOptions{
		Addrs:    []string{"127.0.0.1:6379"},
		Password: "",
		DB:       0,
	})
}

func InsertMongoAccount(userS []FaUser) error {
	var AccountData []models.Account

	// redis map 映射
	for _, user := range userS {
		RDB.Set(context.Background(), user.Username, Next(), 0)
	}

	for _, user := range userS {
		result, err := RDB.Get(context.Background(), user.Username).Result()
		if err != nil {
			return err
		}
		AccountData = append(AccountData, models.Account{
			Channel:  "on",
			JoinIp:   user.Joinip,
			JoinTime: user.Jointime,
			OpenId:   user.Username,
			Platform: "tg_sign",
			UserName: result,
		})
	}
	// 将 playerData 转换为 []interface{} 类型
	docs := make([]interface{}, len(AccountData))
	for i, player := range AccountData {
		docs[i] = player
	}
	// 批量插入MongoDB
	collection := Mdb.Database("db_mhaya").Collection("account")
	_, err := collection.InsertMany(context.Background(), docs)
	if err != nil {
		return err
	}
	return nil
}

func connectToMongoDB() error {
	// 假设使用标准库或第三方库进行 MongoDB 连接
	clientOptions := options.Client().ApplyURI("mongodb://192.168.0.185:27017")
	// 创建一个新的 MongoDB 客户端
	mdb, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		return err
	}
	// 检查连接是否成功
	err = mdb.Ping(context.Background(), nil)
	if err != nil {
		return err
	}
	Mdb = mdb
	return nil
}

func connectToDatabase() (*gorm.DB, error) {
	dsn := "root:root@tcp(127.0.0.1:3306)/load_db?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return nil, fmt.Errorf("failed to connect database: %v", err)
	}
	return db, nil
}
func Next() string {
	node, _ := csnowflake.NewNode(1)
	var sid string
	for {
		id := node.Generate()
		sid = id.Base58()
		if RDB.HExists(context.Background(), "PlayerID", sid).Val() {
			continue
		}
		RDB.HSet(context.Background(), "PlayerID", sid, 1)
		return sid
	}
}

func RunToMongoDB() {
	GetRedisConnect()

	err := connectToMongoDB()
	if err != nil {
		return
	}
	// err = InsertMongoBD()
	// if err != nil {
	// 	return
	// }

}
