// @Author gmy 2024/8/7 10:41:00
package utils

import (
	"fmt"
	"github.com/mozillazg/go-pinyin"
	"strings"
	"unicode"
)

// GenerateIndexCode 指标编码规则:粮油商务网拼音首字母+指标名称拼音首字母,数字、字母保留,特殊字符拿掉
// 例:美湾:9月U:国际大豆进口成本价:期货收盘:张家港 -----> lyswwmw9yUgjddjkcbjqhspzjg
func GenerateIndexCode(sourceName string, indexName string) string {

	// 获取汉字的拼音首字母,保留数字和大写字母
	firstLetters := getFirstLetters(indexName)

	// 组合 sourceName 和处理后的拼音首字母
	indexCode := fmt.Sprintf("%s%s", sourceName, firstLetters)

	return indexCode
}

// getFirstLetters 获取汉字的拼音首字母,并保留数字和大写字母
func getFirstLetters(input string) string {
	// 设置拼音转换选项,只获取首字母
	args := pinyin.NewArgs()
	args.Style = pinyin.FirstLetter

	// 定义用于存储结果的字符串
	var result strings.Builder

	// 遍历输入字符串中的每个字符
	for _, r := range input {
		if unicode.IsDigit(r) || unicode.IsUpper(r) {
			// 保留数字和大写字母
			result.WriteRune(r)
		} else if unicode.Is(unicode.Han, r) {
			// 如果是汉字,则获取其拼音首字母
			py := pinyin.Pinyin(string(r), args)
			if len(py) > 0 && len(py[0]) > 0 {
				result.WriteString(py[0][0])
			}
		}
		// 对于其他字符,忽略处理
	}

	return result.String()
}

/*func GenerateIndexCode(sourceName string, indexName string) string {
	// 获取拼音首字母
	indexInitials := getFirstLetter(indexName)

	// 保留源名称中的字母和数字
	sourceNameFiltered := filterAlphanumeric(indexName)

	// 拼接源名称和首字母
	indexCode := sourceName + sourceNameFiltered + indexInitials

	// 保留字母和数字,去掉其他特殊字符
	re := regexp.MustCompile(`[^a-zA-Z0-9]`)
	indexCode = re.ReplaceAllString(indexCode, "")

	// 转换为小写
	indexCode = strings.ToLower(indexCode)

	return indexCode
}

// 获取字符串中的拼音首字母
func getFirstLetter(s string) string {
	a := pinyin.NewArgs()
	p := pinyin.Pinyin(s, a)
	firstLetters := ""
	for _, syllables := range p {
		if len(syllables) > 0 {
			firstLetters += strings.ToUpper(syllables[0][:1])
		}
	}
	return firstLetters
}

// 过滤只保留字母和数字
func filterAlphanumeric(s string) string {
	re := regexp.MustCompile(`[^a-zA-Z0-9]`)
	return re.ReplaceAllString(s, "")
}*/