//go:build windows

package yu_phone

import (
	_ "embed"
	yu_deflate "gogs.qqck.cn/s/tools/deflate"
	yu_fast "gogs.qqck.cn/s/tools/fast"
	yu_strconv "gogs.qqck.cn/s/tools/strconv"
	"strings"
)

var (
	//go:embed phone.dat
	data    []byte
	phone2D [][]int
	addrArr []string
	ispArr  []string
)

func init() {
	data = yu_deflate.DeflateDe(data)

	PrefSize := int(data[0]) | int(data[1])<<8 | int(data[2])<<16 | int(data[3])<<24
	descLength := int(data[8]) | int(data[9])<<8 | int(data[10])<<16 | int(data[11])<<24
	ispLength := int(data[12]) | int(data[13])<<8 | int(data[14])<<16 | int(data[15])<<24
	// PhoneSize := binary.LittleEndian.Uint32(data[4:8])
	// verNum := binary.LittleEndian.Uint32(data[16:20])

	headLength := 20
	startIndex := headLength + descLength + ispLength

	// Description array
	descString := yu_fast.B2S(data[headLength : headLength+descLength])
	addrArr = strings.Split(descString, "&")

	// ISP array
	ispString := yu_fast.B2S(data[headLength+descLength : headLength+descLength+ispLength])
	ispArr = strings.Split(ispString, "&")

	// Phone2D array
	phone2D = make([][]int, 200)
	for m := 0; m < PrefSize; m++ {
		i := m*7 + startIndex
		pref := int(data[i])
		index := int(data[i+1]) | int(data[i+2])<<8 | int(data[i+3])<<16 | int(data[i+4])<<24
		length := int(data[i+5]) | int(data[i+6])<<8

		phone2D[pref] = make([]int, 10000)
		for n := 0; n < length; n++ {
			p := startIndex + PrefSize*7 + (n+index)*4
			suff := int(data[p]) | int(data[p+1])<<8
			addrispIndex := int(data[p+2]) | int(data[p+3])<<8
			phone2D[pref][suff] = addrispIndex
		}
	}
}

type Info struct {
	// 区划：530400
	AreaCode string `json:"areacode"`
	// 城市：玉溪
	City string `json:"city"`
	// 区号：0877
	CityCode string `json:"citycode"`
	// 运营商：中国移动
	Isp string `json:"isp"`
	// 邮编：653100
	PostCode string `json:"postcode"`
	// 省份：云南
	Province string `json:"province"`
}

func (t *Info) IsVaild() bool {
	return t.Province != ""
}

// Query
//
//	@Description: 查询手机号信息
func Query(phone string) (info Info) {
	if len(phone) < 7 {
		return
	}
	prefix := phone[:3]
	suffix := phone[3:7]
	pref := yu_strconv.ParseInt(prefix)
	suff := yu_strconv.ParseInt(suffix)
	if pref >= len(phone2D) || suff >= len(phone2D[pref]) {
		return
	}
	addrispIndex := phone2D[pref][suff]

	if addrispIndex == 0 {
		return
	}
	j_info := strings.Split(addrArr[addrispIndex/100], "|")
	if len(j_info) != 5 {
		return
	}

	info.AreaCode, info.City, info.CityCode, info.PostCode, info.Province = j_info[4], j_info[1], j_info[3], j_info[2], j_info[0]
	info.Isp = ispArr[addrispIndex%100]

	return
}
