package model

import (
	"fmt"
	"hash/crc32"

	"gorm.io/gorm"
)

const (
	NodeCnt  = 16384 //2^14
	NodeMask = 0x3fff
	NodeBit  = 14
)

var (
	TblCnt uint = 4
)

func calcDbTable(id uint) (tbl uint) {
	// nodeId := id % NodeCnt //16384 总表数
	tbl = id % TblCnt //实际表数 4
	if tbl == 0 {
		tbl = TblCnt
	}
	return
}

func subTableI(gId int64, baseTableName string) string {
	node := gId & NodeMask
	tb := calcDbTable(uint(node))
	name := baseTableName
	fmt.Printf("%v_%d", name, tb)
	return fmt.Sprintf("%v_%d", name, tb)
}

func GetAccountTable(accId int64, baseTableName string) string {
	node := accId & NodeMask
	tb := calcDbTable(uint(node))
	name := baseTableName
	fmt.Printf("%v_%d", name, tb)
	return fmt.Sprintf("%v_%d", name, tb)
}

func subTableS(key string, baseTableName string) string {
	node := hashNameCode(key)
	tb := calcDbTable(node)
	name := baseTableName
	return fmt.Sprintf("%v_%d", name, tb)
}

func hashNameCode(name string) uint {
	n := crc32.ChecksumIEEE([]byte(name))
	return uint(n % NodeCnt)
}

// UserAccountTable gormDB的scopes， 根据传入id来获取对应的表名
func UserAccountTable(m *UserAccount, accId int64) func(tx *gorm.DB) *gorm.DB {
	return func(tx *gorm.DB) *gorm.DB {
		return tx.Table(subTableI(accId, m.TableName()))
	}
}

func UserAccountTableByKey(m *UserAccount, key string) func(tx *gorm.DB) *gorm.DB {
	return func(tx *gorm.DB) *gorm.DB {
		return tx.Table(subTableS(key, m.TableName()))
	}
}
