package util

import (
	"github.com/GUAIK-ORG/go-snowflake/snowflake"
	"github.com/google/uuid"
	"github.com/issue9/conv"
	"math/rand"
	"time"
	"youngee_b_api/app/dao"
	"youngee_b_api/app/entity"
	"youngee_b_api/util"
)

var snowflakeInstance *snowflake.Snowflake

func init() {
	s, err := snowflake.NewSnowflake(int64(0), int64(0))
	if err != nil {
		panic(err)
	}
	snowflakeInstance = s
}

func GetSelectionID() string {
	rand.Seed(time.Now().UnixNano())
	td := conv.MustString(time.Now().Day())
	for {
		if len(td) == 3 {
			break
		}
		td = "0" + td
	}
	selectionId := conv.MustString(time.Now().Year())[2:] + td + conv.MustString(rand.Intn(100000-10000)+10000)
	return selectionId
}

func GetProjectID() string {
	rand.Seed(time.Now().UnixNano())
	td := conv.MustString(time.Now().Day())
	for {
		if len(td) == 3 {
			break
		}
		td = "0" + td
	}
	selectionId := conv.MustString(time.Now().Year())[2:] + td + conv.MustString(rand.Intn(100000-10000)+10000)
	return selectionId
}

func MakeRechargeId(enterpriseID string) string {
	// 1、年月日
	year := time.Now().Year()
	month := time.Now().Month()
	day := time.Now().Day()
	yearData, _ := util.GetDayNum("year", year)
	monthData, _ := util.GetDayNum("month", int(month))
	dayData, _ := util.GetDayNum("day", day)
	sum := 0
	sum += dayData + monthData
	leap := 0
	if (yearData%400 == 0) || ((yearData%4 == 0) && (yearData%100 != 0)) {
		leap = 1
	}
	if (leap == 1) && (monthData > 2) {
		sum += 1
	}
	last := ""
	rechargeIdPrefix := "8" + enterpriseID[len(enterpriseID)-2:] + conv.MustString(sum)
	var rechargeIdLast string
	err := dao.Db.Model(entity.RechargeRecord{}).Select("recharge_id").Where("recharge_id like ?", rechargeIdPrefix+"%").
		Last(&rechargeIdLast).Error
	if err != nil {
		last = "0"
	} else {
		last = rechargeIdLast[len(rechargeIdLast)-2:]
	}
	var lastInt int
	lastInt = conv.MustInt(last)
	if lastInt+1 < 10 {
		last = "0" + conv.MustString(conv.MustInt(last)+1)
	} else {
		last = conv.MustString(conv.MustInt(last) + 1)
	}
	return rechargeIdPrefix + last
}

func GenerateDateRelatedUUID(num int64) string {
	date := time.Now().Format("20060102") // 获取当前日期
	u := uuid.New()
	return date + u.String()[:(num-8)]
}

func GenerateUUID(num int) string {
	u := uuid.New()
	return u.String()[:num]
}
