package db

import (
	"applet/app/db/model"
	"applet/app/utils"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/syyongx/php2go"
	"regexp"
	"strings"
)

func sysModFormat(c *gin.Context, m interface{}) (interface{}, error) {
	var mods []model.SysModule
	protocol := SysCfgGet(c, "file_bucket_scheme")
	domain := SysCfgGet(c, "file_bucket_host")
	//fmt.Println(protocol, domain)
	if protocol == "" || domain == "" {
		return nil, errors.New("System configuration error, object storage protocol and domain name not found")
	}
	modname_list := []string{"product", "search_result_taobao_item", "hot_rank_tab_view"}
	switch m.(type) {
	case *[]model.SysModule:
		ms := m.(*[]model.SysModule)
		for _, item := range *ms {
			item.Data = ReformatStr(protocol, domain, item.Data, c)
			if item.ModName == "product_detail_title" {
				if strings.Contains(item.Data, "tmall") == false {
					item.Data = strings.Replace(item.Data, "\"platform_css\":[", "\"platform_css\":[{\"name\":\"天猫\",\"type\":\"tmall\",\"text_color\":\"#FFFFFF\",\"bg_color\":\"#FF4242\"},", 1)
				}
				if strings.Contains(item.Data, "kuaishou") == false {
					item.Data = strings.Replace(item.Data, "\"platform_css\":[", "\"platform_css\":[{\"name\":\"快手\",\"type\":\"kuaishou\",\"text_color\":\"#FFFFFF\",\"bg_color\":\"#FF4242\"},", 1)
				}
				if strings.Contains(item.Data, "tikTok") == false {
					item.Data = strings.Replace(item.Data, "\"platform_css\":[", "\"platform_css\":[{\"name\":\"抖音\",\"type\":\"tikTok\",\"text_color\":\"#FFFFFF\",\"bg_color\":\"#FF4242\"},", 1)
				}
			}

			if strings.Contains(item.Data, "tmall") == false && utils.InArr(item.ModName, modname_list) {
				item.Data = strings.Replace(item.Data, "{\"index\":\"6\",\"type\":\"kaola\",\"platform_name\":\"考拉\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"}", "{\"index\":\"6\",\"type\":\"kaola\",\"platform_name\":\"考拉\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"},{\"index\":\"7\",\"type\":\"tmall\",\"platform_name\":\"天猫\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"}", 1)
				item.Data = strings.Replace(item.Data, "{\"type\":\"kaola\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"}", "{\"type\":\"kaola\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"},{\"type\":\"tmall\",\"provider_name_color\":\"#FFFFFF\",\"provider_bg_color\":\"#FF4242\"}", 1)
			}
			if strings.Contains(item.Data, "\"virtual_coin_pre_fix_name\":") == false && item.ModName == "product" {
				item.Data = strings.ReplaceAll(item.Data, "\"virtual_coin_name\":", "\"virtual_coin_pre_fix_name\":\"返\",\"virtual_coin_name\":")
			}
			item = SysModDataByReplace(c, item)

			mods = append(mods, item)
		}
		return &mods, nil
	case *model.SysModule:
		m := m.(*model.SysModule)
		m.Data = ReformatStr(protocol, domain, m.Data, c)
		m = SysModDataByReplaceSecond(c, m)
		return m, nil
	case []*model.UserLevel:
		ms := m.([]*model.UserLevel)
		for _, item := range ms {
			item.CssSet = ReformatStr(protocol, domain, item.CssSet, c)
		}
		return ms, nil
	case []*model.SysPushUser:
		ms := m.([]*model.SysPushUser)
		for _, item := range ms {
			item.SendData = ReformatStr(protocol, domain, item.SendData, c)
		}
		return ms, nil
	case *model.SysPushUser:
		m := m.(*model.SysPushUser)
		m.SendData = ReformatStr(protocol, domain, m.SendData, c)
		return m, nil
	default:
		return nil, nil
	}
}

func ReformatComm(str, protocol, domain string) string {
	// PNG
	replaceList := reformatImg(str)
	l := removeDuplicateElement(replaceList)
	for _, s := range l {
		if strings.Contains(s, "http") {
			continue
		}
		ss := s
		s = strings.ReplaceAll(s, `\`, "")
		s = strings.ReplaceAll(s, `"`, "")
		s = php2go.Rawurlencode(s)
		new := fmt.Sprintf("%s://%s/%s", protocol, domain, s)
		//if skipHTTPPng(new) {
		//	continue
		//}
		str = strings.Replace(str, ss, `"`+new+`"`, -1)
	}
	return str
}
func ReformatStr(protocol, domain, str string, c *gin.Context) string {
	//protocol := SysCfgGet(c, "file_bucket_scheme")
	//domain := SysCfgGet(c, "file_bucket_host")

	// PNG
	str = ReformatComm(str, protocol, domain)
	return str
}

// 正则匹配
func reformatPng(data string) []string {
	re, _ := regexp.Compile(`"([^\"]*.png")`)
	list := re.FindAllString(data, -1)
	return list
}
func reformatJpeg(data string) []string {
	re, _ := regexp.Compile(`"([^\"]*.jpeg")`)
	list := re.FindAllString(data, -1)
	return list
}
func reformatMp4(data string) []string {
	re, _ := regexp.Compile(`"([^\"]*.mp4")`)
	list := re.FindAllString(data, -1)
	return list
}

func skipHTTPPng(data string) bool {
	re, _ := regexp.Compile(`(http|https):\/\/([^\"]*.png)`)
	return re.MatchString(data)
}

// 正则匹配
func reformatJPG(data string) []string {
	re, _ := regexp.Compile(`"([^\"]*.jpg")`)
	list := re.FindAllString(data, -1)
	return list
}

// 正则匹配
func reformatGIF(data string) []string {
	re, _ := regexp.Compile(`"([^\"]*.gif")`)
	list := re.FindAllString(data, -1)
	return list
}
func reformatImg(data string) []string {
	re, _ := regexp.Compile(`"([^\"]*.(png|jpg|jpeg|gif|mp4)")`)
	list := re.FindAllString(data, -1)
	return list
}

func removeDuplicateElement(addrs []string) []string {
	result := make([]string, 0, len(addrs))
	temp := map[string]int{}
	i := 1
	for _, item := range addrs {
		if _, ok := temp[item]; !ok {
			temp[item] = i
			result = append(result, item)
			continue
		}
		temp[item] = temp[item] + 1
	}
	// fmt.Println(temp)
	return result
}

// 单条记录获取DB
func SysCfgGet(c *gin.Context, key string) string {
	res := SysCfgFind(c, key)
	//fmt.Println(res)
	if _, ok := res[key]; !ok {
		return ""
	}
	return res[key]
}

// 多条记录获取
func SysCfgFind(c *gin.Context, keys ...string) map[string]string {
	eg := DBs[c.GetString("mid")]
	masterId := c.GetString("mid")
	res := map[string]string{}
	//TODO::判断keys长度(大于10个直接查数据库)
	if len(keys) > 10 {
		cfgList, _ := SysCfgGetAll(eg)
		if cfgList == nil {
			return nil
		}
		for _, v := range *cfgList {
			res[v.Key] = v.Val
		}
	} else {
		for _, key := range keys {
			res[key] = SysCfgGetWithDb(eg, masterId, key)
		}
	}
	return res
}
