package helper

import (
	"strconv"
	"sync"

	extendConfig "go-admin/config"

	"github.com/bwmarrin/snowflake"
	log "github.com/go-admin-team/go-admin-core/logger"
)

// 全局雪花节点实例
var (
	node *snowflake.Node
	once sync.Once
)

func InitSnowflakeNode() error {
	var err error

	node, err = snowflake.NewNode(extendConfig.ExtConfig.ServiceId)
	if err != nil {
		return err
	}

	return nil
}

// 获取订单雪花id
func GetOrderNo() string {
	if node == nil {
		once.Do(func() {
			if node == nil {
				if err := InitSnowflakeNode(); err != nil {
					log.Fatalf("初始化雪花算法节点失败: %v", err)
				}
			}
		})
	}

	if node == nil {
		log.Fatal("雪花算法节点未初始化")
	}

	orderID := node.Generate()
	idStr := strconv.FormatInt(orderID.Int64(), 10)

	return idStr
}
