package lib

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"math"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

// #取得随机字符串：通过打乱slice来操作
func GetRandstring(length int, char string, rand_x int64) string {
	if length < 1 {
		return ""
	}

	if len(char) <= 6 || len(char) <= length {
		char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	}

	charArr := strings.Split(char, "")
	ran := rand.New(rand.NewSource(time.Now().Unix() + rand_x))

	l := len(charArr)
	for i := l - 1; i > 0; i-- {
		r := ran.Intn(i)
		charArr[r], charArr[i] = charArr[i], charArr[r]
	}
	rchar := charArr[:length]
	return strings.Join(rchar, "")
}

// 返回一个32位md5加密后的字符串
func Md5(str string) string {
	h := md5.New()
	h.Write([]byte(str))
	return hex.EncodeToString(h.Sum(nil))
}

// 转化
func TimeStrToTime(T_time string) (time.Time, bool) {

	stamp, err := time.ParseInLocation("2006-01-02 15:04:05", T_time, time.Local)
	if err != nil {
		return time.Time{}, false
	}

	return stamp, true
}

// 转化
func DateStrToDate(T_date string) (time.Time, bool) {

	stamp, err := time.ParseInLocation("2006-01-02", T_date, time.Local)

	if err != nil {
		return time.Time{}, false
	}

	return stamp, true
}

func SplitStringIds(str string, prefix string) (r []string) {
	if len(str) == 0 {
		return
	}
	Ids_str := strings.TrimRight(str, "|")
	Ids := strings.Split(Ids_str, "|")
	for _, v := range Ids {
		r = append(r, strings.TrimLeft(v, prefix))
	}
	return r
}

func SplitStringToDotStr(str string, prefix string) (r string) {
	Ids_str := strings.TrimRight(str, "|")
	Ids := strings.Split(Ids_str, "|")
	for _, v := range Ids {
		r += strings.TrimLeft(v, prefix) + ","
	}
	r = strings.TrimRight(r, ",")
	return r
}

func SplitStringToIntIds(str string, prefix string) (r []int) {
	Ids_str := strings.TrimRight(str, "|")
	Ids := strings.Split(Ids_str, "|")
	for _, v := range Ids {
		id, _ := strconv.Atoi(strings.TrimLeft(v, prefix))
		r = append(r, id)
	}
	return r
}

func IntIdsDistinct(Ids []int) (result []int) {
	distinctMap := make(map[int]int, len(Ids))
	for _, Id := range Ids {
		if _, ok := distinctMap[Id]; !ok {
			distinctMap[Id] = 1
			result = append(result, Id)
		}
	}
	return result
}

func StringListToDotStr(str []string) (r string) {
	//for _, v := range str {
	//	r += v + ","
	//}
	//r = strings.TrimRight(r, ",")

	return strings.Join(str, ",")
}

func IntListToDotStr(list []int) (r string) {
	for _, v := range list {
		r += fmt.Sprintf("%d,", v)
	}
	r = strings.TrimRight(r, ",")
	return r
}

// ["a","b","c"] ==> "'a','b','c'"
func StringListToQuotesDotStr(str []string) (r string) {
	for _, v := range str {
		r += fmt.Sprintf("'%s',", v)
	}
	r = strings.TrimRight(r, ",")
	return r
}

// 四舍五入保留小数点后几位
func RoundToDecimal(num float64, decimalPlaces int) float64 {
	shift := math.Pow(10, float64(decimalPlaces))
	return math.Round(num*shift) / shift
}

// 检查sn是否都相同
// 2023103074298131,0|2023143741715643,0|
func IsSNAllSame(T_snid string) (string, []int, bool) {

	entries := strings.Split(strings.Trim(T_snid, "|"), "|")

	if len(entries) == 1 {
		fields := strings.Split(entries[0], ",")
		if len(fields) == 2 {
			return fields[0], []int{To_int(fields[1])}, true // 只有一个条目时，认为全相同
		} else {
			return "", []int{}, false
		}
	}

	firstSN := ""
	ids := []int{}
	for _, entry := range entries {
		fields := strings.Split(entry, ",")
		if len(fields) == 2 {
			currSN := fields[0]
			ids = append(ids, To_int(fields[1]))
			if firstSN == "" {
				firstSN = currSN
			} else if currSN != firstSN {
				return "", []int{}, false // 发现不相同的 SN 值，直接返回 false
			}
		}
	}

	return firstSN, ids, true
}
