package db

import (
	"applet/app/cfg"
	"applet/app/db/model"
	"applet/app/utils"
	"applet/app/utils/cache"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/tidwall/gjson"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
	"xorm.io/xorm"
)

func GetAppletKey(c *gin.Context, eg *xorm.Engine) map[string]string {
	appId := c.GetHeader("appid")
	isFilterTaobao := "0"
	appletName := ""
	appletLogo := ""
	originalAppId := ""
	bottomNavCssId := ""
	mpAuditVersion := ""
	MpAuditGoodsDetailCssId := ""
	orderCssId := ""
	if appId == "" {
		wxAppletCfg := SysCfgGetWithDb(eg, c.GetString("mid"), "wx_applet_key")
		isFilterTaobao = gjson.Get(wxAppletCfg, "taobaoGoodsOnOff").String()
		appletName = gjson.Get(wxAppletCfg, "appletName").String()
		originalAppId = gjson.Get(wxAppletCfg, "originalAppId").String()
		appletLogo = gjson.Get(wxAppletCfg, "appletIcon").String()
		mpAuditVersion = SysCfgGetWithDb(eg, c.GetString("mid"), "mp_audit_version")
		var tm model.SysTemplate
		if has, err := eg.Where("is_use = 1 AND type = 'bottom' AND platform = 4 ").
			Cols("id,uid,name,is_use,is_system").
			Get(&tm); err != nil || has == false {
			bottomNavCssId = ""
		} else {
			bottomNavCssId = utils.IntToStr(tm.Id)
		}
		if c.GetHeader("AppVersionName") == mpAuditVersion && c.GetHeader("AppVersionName") != "" {
			m := SysCfgGetWithDb(eg, c.GetString("mid"), "mp_audit_template")
			if m != "" {
				bottomNavCssId = utils.Int64ToStr(gjson.Get(m, "bottom").Int())
			}
			m1 := SysCfgGet(c, "mp_audit_template")
			if m1 != "" {
				MpAuditGoodsDetailCssId = utils.Int64ToStr(gjson.Get(m1, "product_detail").Int())
			}
		}
		appId = gjson.Get(wxAppletCfg, "appId").String()
	} else {
		var wxApplet model.WxAppletList
		has, err2 := eg.Where("app_id=?", appId).Get(&wxApplet)
		if has && err2 == nil {
			isFilterTaobao = utils.IntToStr(wxApplet.IsFilterTaobao)
			appletName = wxApplet.AppletName
			appletLogo = wxApplet.AppletLogo
			originalAppId = wxApplet.OriginalAppId
			orderCssId = utils.IntToStr(wxApplet.OrderCssId)
			mpAuditVersion = wxApplet.MpAuditVersion
			bottomNavCssId = utils.IntToStr(wxApplet.BottomNavCssId)
			MpAuditGoodsDetailCssId = ""
			if c.GetHeader("AppVersionName") == mpAuditVersion && c.GetHeader("AppVersionName") != "" {
				bottomNavCssId = utils.IntToStr(wxApplet.MpAuditCssId)
				MpAuditGoodsDetailCssId = utils.IntToStr(wxApplet.MpAuditGoodsDetailCssId)
			}
		}
	}
	r := map[string]string{
		"order_css_id":                 orderCssId,
		"app_id":                       appId,
		"is_filter_taobao":             isFilterTaobao,
		"applet_name":                  appletName,
		"applet_logo":                  appletLogo,
		"original_app_id":              originalAppId,
		"bottom_nav_css_id":            bottomNavCssId,
		"mp_audit_version":             mpAuditVersion,
		"mp_audit_goods_detail_css_id": MpAuditGoodsDetailCssId,
	}
	return r

}
func GetShareUse(c *gin.Context, eg *xorm.Engine) map[string]string {
	var wxApplet model.WxAppletList
	has, err2 := eg.Where("share_use=?", 1).Asc("id").Get(&wxApplet)
	wxAppletCfg := SysCfgGetWithDb(eg, c.GetString("mid"), "wx_applet_key")
	originalAppId := gjson.Get(wxAppletCfg, "originalAppId").String()
	appId := gjson.Get(wxAppletCfg, "appId").String()
	if has && err2 == nil {
		originalAppId = wxApplet.OriginalAppId
		appId = wxApplet.AppId
	}
	r := map[string]string{
		"app_id":          appId,
		"original_app_id": originalAppId,
	}
	return r
}
func GetAppletToken(c *gin.Context, appId string, isMore, isReset string) (accessToken string) {
	key := fmt.Sprintf("%s:%s:%s", c.GetString("mid"), "wx_applet_access_token2", appId)
	token, err := cache.GetString(key)
	if err == nil && token != "" && strings.Contains(token, "{") == false && isReset == "0" {
		// 有缓存
		accessToken = token
	} else {
		ExpiresIn := 1800
		accessTokenStr := ApiToSuperAdminWx(c, appId, isMore)
		if accessTokenStr == "" {
			return ""
		}
		ExpiresIn = int(gjson.Get(accessTokenStr, "expires_in").Int()) - 60*60*1 //TODO::暂时只用1个小时
		accessToken = gjson.Get(accessTokenStr, "authorizer_access_token").String()
		if ExpiresIn > 0 {
			//fmt.Printf("返回结果: %#v", res)
			_, err = cache.SetEx(key, accessToken, ExpiresIn)
			if err != nil {
				fmt.Println("微信授权错误", err)
				return ""
			}
		}

	}
	return accessToken
}

// 总后台微信token isMore多小程序登录总后台要判断读另一个表
func ApiToSuperAdminWx(c *gin.Context, appid string, isMore string) string {
	var req = make(map[string]string, 0)
	var host string
	host = cfg.WebsiteBackend.URL + "/Wx/getAuthorizerResult?appid=" + appid + "&is_more=" + isMore
	fmt.Println(host)
	tr := &http.Transport{
		MaxIdleConnsPerHost: 200,
		MaxIdleConns:        200,
		MaxConnsPerHost:     200,
		TLSClientConfig:     &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{
		Timeout:   5 * time.Second,
		Transport: tr,
	}
	byte1, _ := json.Marshal(req)
	req1, _ := http.NewRequest("POST", host, strings.NewReader(string(byte1)))
	req1.Header.Set("Content-Type", "application/json")
	resp, err := (client).Do(req1)
	if err != nil || resp == nil {
		if resp != nil {
			_, _ = io.Copy(ioutil.Discard, resp.Body)
		}
		return ""
	}
	defer resp.Body.Close()
	respByte, _ := ioutil.ReadAll(resp.Body)

	if len(respByte) == 0 {
		return ""
	}
	return string(respByte)

}
