package services

import (
	"eta/eta_mini_crm_ht/models"
	"eta/eta_mini_crm_ht/utils"
	"fmt"
	"github.com/silenceper/wechat/v2"
	"github.com/silenceper/wechat/v2/cache"
	"github.com/silenceper/wechat/v2/credential"
	"github.com/silenceper/wechat/v2/officialaccount"
	"github.com/silenceper/wechat/v2/officialaccount/config"
	"github.com/silenceper/wechat/v2/officialaccount/js"
	"github.com/silenceper/wechat/v2/officialaccount/user"
	"time"
)

type WechatAccessToken struct {
}

func GetWxChat() (officialAccount *officialaccount.OfficialAccount) {
	wc := wechat.NewWechat()
	memory := cache.NewMemory()
	conf := &config.Config{
		AppID:          utils.HT_WX_APPID,
		AppSecret:      utils.HT_WX_APP_SECRET,
		Token:          "",
		EncodingAESKey: "",
		Cache:          memory,
	}
	officialAccount = wc.GetOfficialAccount(conf)
	wechatAccessToken := &WechatAccessToken{}
	officialAccount.SetAccessTokenHandle(wechatAccessToken)
	return
}

// GetAccessToken 获取accessToken
func (wechat WechatAccessToken) GetAccessToken() (accessToken string, err error) {
	//如果300s就要过期了，那么就去刷新accessToken
	wxToken, err := models.GetWxTokenById()
	if err != nil {
		return
	}
	//如果300s就要过期了，那么就去刷新accessToken
	if wxToken.ExpiresIn < time.Now().Unix()+300 {
		tmpAccessToken, expires, tmpErr := getTokenFromServer(utils.HT_WX_APPID, utils.HT_WX_APP_SECRET)
		if tmpErr != nil {
			err = tmpErr
			return
		}

		var updateCols = []string{"access_token", "expires_in"}
		wxToken.AccessToken = tmpAccessToken
		wxToken.ExpiresIn = time.Now().Unix() + expires - 600 //快过期前10分钟就刷新掉
		_ = wxToken.Update(updateCols)
	}
	accessToken = wxToken.AccessToken
	return
}

// accessToken, err = utils.Rc.RedisString(utils.CACHE_WX_ACCESS_TOKEN_DW)
// if accessToken != "" {
// 	return
// }

// // 缓存中没有取到数据，那么就需要强制刷新的accessToken
// tmpAccessToken, _, tmpErr := getTokenFromServer(utils.DW_WX_APPID, utils.DW_WX_APP_SECRET)
// if tmpAccessToken == "" {
// 	err = errors.New("获取微信token失败，Err:" + tmpErr.Error())
// 	return
// }

// redisTimeExpire := time.Duration(expires-600) * time.Second
// err = utils.Rc.Put(utils.CACHE_WX_ACCESS_TOKEN_HZ, tmpAccessToken, redisTimeExpire)
// if err != nil {
// 	err = errors.New("更新微信token失败")
// 	return
// }
// accessToken = tmpAccessToken
// return
// //如果300s就要过期了，那么就去刷新accessToken
// if wxToken.ExpiresIn < time.Now().Unix()+300 {
// 	tmpAccessToken, expires, tmpErr := getTokenFromServer(WxAppId, WxAppSecret)
// 	if tmpErr != nil {
// 		err = tmpErr
// 		return
// 	}

// 	var updateCols = []string{"access_token", "expires_in"}
// 	wxToken.AccessToken = tmpAccessToken
// 	wxToken.ExpiresIn = expires - 600 //快过期前10分钟就刷新掉
// 	wxToken.Update(updateCols)
// }
// accessToken = wxToken.AccessToken
// return refreshWxAccessToken(wxAppId, wxAppSecret)

// getTokenFromServer 服务端获取accessToken
func getTokenFromServer(appid, wxSecret string) (accessToken string, expires int64, err error) {
	apiUrl := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"
	resAccessToken, err := credential.GetTokenFromServer(fmt.Sprintf(apiUrl, appid, wxSecret))
	if err != nil {
		return
	}

	expires = resAccessToken.ExpiresIn
	accessToken = resAccessToken.AccessToken
	return
}

// GetUserInfo 获取微信用户详情
func GetUserInfo(openid string) (userInfo *user.Info, err error) {
	wechatClient := GetWxChat()
	userClient := wechatClient.GetUser()
	userInfo, err = userClient.GetUserInfo(openid)
	return
}

// GetJsConfig 获取公众号jsConfig
func GetJsConfig(signUrl string) (jsConf *js.Config, err error) {
	wechatClient := GetWxChat()
	j := wechatClient.GetJs()
	jsConf, err = j.GetConfig(signUrl)
	return
}
