package utils

import (
	"applet/app/cfg"
	"applet/app/utils/cache"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/go-creed/sat"
	"strings"
)

func ReadReverse(c *gin.Context, str string) string {
	if c.GetString("translate_open") == "zh_Hant_" { //繁体先不改
		sat.InitDefaultDict(sat.SetPath(cfg.WxappletFilepath.URL + "/" + "sat.txt")) //使用自定义词库
		sat := sat.DefaultDict()
		res := sat.ReadReverse(str)
		list := strings.Split(res, "http")
		imgList := []string{".png", ".jpg", ".jpeg", ".gif"}
		for _, v := range list {
			for _, v1 := range imgList {
				if strings.Contains(v, v1) { //判断是不是有图片 有图片就截取 替换简繁体
					strs := strings.Split(v, v1)
					if len(strs) > 0 {
						oldStr := strs[0]
						newStr := sat.Read(oldStr)
						res = strings.ReplaceAll(res, oldStr, newStr)
					}
				}
			}
		}
		return res
	}
	if c.GetString("translate_open") != "zh_Hant_" { //除了繁体，其他都走这里
		//简体---其他语言
		cTouString, err := cache.GetString("multi_language_c_to_" + c.GetString("translate_open"))
		if err != nil {
			return str
		}
		var cTou = make(map[string]string)
		json.Unmarshal([]byte(cTouString), &cTou)
		if len(cTou) == 0 {
			return str
		}
		//其他语言--简体
		getString1, err1 := cache.GetString("multi_language_" + c.GetString("translate_open") + "_to_c")
		if err1 != nil {
			return str
		}
		var uToc = make(map[string]string)
		json.Unmarshal([]byte(getString1), &uToc)
		if len(uToc) == 0 {
			return str
		}
		res := str
		for k, v := range cTou {
			res = strings.ReplaceAll(res, k, v)
		}
		list := strings.Split(res, "http")
		imgList := []string{".png", ".jpg", ".jpeg", ".gif"}
		for _, v := range list {
			for _, v1 := range imgList {
				if strings.Contains(v, v1) { //判断是不是有图片 有图片就截取 替换简繁体
					strs := strings.Split(v, v1)
					if len(strs) > 0 {
						oldStr := strs[0]
						newStr := oldStr
						for k2, v2 := range uToc {
							newStr = strings.ReplaceAll(oldStr, k2, v2)
						}
						res = strings.ReplaceAll(res, oldStr, newStr)
					}
				}
			}
		}
		return res
	}
	return str

}

func ReadReverse1(str, types string) string {
	res := map[string]map[string]string{}
	err := cache.GetJson("multi_language", &res)
	if err != nil {
		return str
	}
	for k, v := range res {
		str = strings.ReplaceAll(str, k, v[types])
	}
	resStr := str
	list := strings.Split(resStr, "http")
	imgList := []string{".png", ".jpg", ".jpeg", ".gif"}
	for _, v := range list {
		for _, v1 := range imgList {
			if strings.Contains(v, v1) { //判断是不是有图片 有图片就截取 替换简繁体
				strs := strings.Split(v, v1)
				if len(strs) > 0 {
					oldStr := strs[0]
					for k2, v2 := range res {
						if v2[types] == oldStr {
							resStr = strings.ReplaceAll(resStr, oldStr, k2)
						}
					}
					//res = strings.ReplaceAll(res, oldStr, newStr)
				}
			}
		}
	}
	return resStr
}
