package svc

import (
	"applet/app/lib/zhimeng"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/tidwall/gjson"

	"applet/app/utils"
	"applet/app/utils/logx"
)

var DWZ_TOKEN = "eecdf4b18f416b0cf26fef98f7e1f4ff"

// KuaiZhanShortURL is 快站短链
func KuaiZhanShortURL(c *gin.Context, url string) string {
	args := map[string]interface{}{
		"appkey":     SysCfgGet(c, "third_zm_app_key"),
		"secret_key": SysCfgGet(c, "third_zm_app_key"),
		"url":        utils.Base64StdEncode(url),
	}
	resp, err := zhimeng.Send("kuaizhan", "short_url", args)
	if err != nil {
		return ""
	}
	kurl := gjson.GetBytes(resp, "data.shortUrl").String()
	if kurl == "" {
		kurl = url
	}
	return kurl
}

func ShortenUrl(url string) (string, error) {
	host := "https://dwz.cn/admin/v2/create"
	args := map[string]string{
		"Url":            url,
		"TermOfValidity": "1-year",
	}

	resp, err := utils.CurlPost(host, utils.Serialize(args), map[string]string{
		"Content-Type": "application/json",
		"Token":        DWZ_TOKEN,
	})
	//	{"Code":0,"IsNew":true,"ShortUrl":"https://dwz.cn/4kSgiKVl","LongUrl":"https://open.taobao.com/search.htm?q=taobao.tbk.sc.material","ErrMsg":""}
	if err != nil {
		return "", logx.Warn(err)
	}
	var tmp struct {
		Code     int    `json:"Code"`
		IsNew    bool   `json:"IsNew"`
		ShortURL string `json:"ShortUrl"`
		LongURL  string `json:"LongUrl"`
		ErrMsg   string `json:"ErrMsg"`
	}
	if err = json.Unmarshal(resp, &tmp); err != nil {
		return url, logx.Warn("resp: " + string(resp) + ", err:" + err.Error())
	}
	if tmp.ShortURL == "" {
		tmp.ShortURL = url
	}
	return tmp.ShortURL, nil
}
