package wechat

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/http"
	"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"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/models/response/pc"
	"hongze/hongze_yb/models/tables/wx_token"
	"time"
)

var (
	WxId                            string //微信原始ID
	WxAppId                         string
	WxAppSecret                     string
	TemplateIdWithCommunityQuestion string // 问答社区回复模板消息ID
	TemplateIdWithCommunityQuestionNotifyAdmin string // 问答社区 有提问通知管理员
	//WxYbAppId                       string // 研报小程序AppID
	PcWxAppId                       string //pc版AppId
	PcWxAppSecret                   string //pc版AppSecret

	WxMobileCrmAppId     string //随手办公小程序appid
	WxMobileCrmId        string //随手办公小程序id
	WxAppMobileCrmSecret string //随手办公小程序秘钥

	//内部员工公众号（弘则部门）
	AdminWxAppId                    string
	AdminWxAppSecret                string
)

func init() {
	//WxYbAppId = "wxb059c872d79b9967"

	WxMobileCrmAppId = `wx67b68e39913e511e`
	WxMobileCrmId = `wx67b68e39913e511e`
	WxAppMobileCrmSecret = `660b0375f701a19220bb8a662b41c77c`

	//内部员工公众号（弘则部门）
	AdminWxAppId = "wx1392111da5426e9e"
	AdminWxAppSecret = "30eceb7cf29bf2f046031155ab55d7b4"

	if global.CONFIG.Serve.RunMode == "debug" {
		WxAppId = "wx9b5d7291e581233a"
		WxAppSecret = "f4d52e34021eee262dce9682b31f8861"
		WxId = "gh_5dc508325c6f"
		TemplateIdWithCommunityQuestion = "CB7bOl7f3viMG4s1uhRo7WM0Jbx3WvodKuIZ8A_z8fM"
		TemplateIdWithCommunityQuestionNotifyAdmin = "rciDm9ThigRBGi1SZ4TFd74XA4aoAxSz_ugdv_tZ450"
		PcWxAppId = "wxcba9a7ec590ee2d5"
		PcWxAppSecret = "aa58d257e2521d768cbf1bf89989769d"
	} else {
		WxAppId = "wx4a844c734d8c8e56"
		WxAppSecret = "26c586e7ccb3c575433f0f37797b3eeb"
		WxId = "gh_b67e0049fb8c"
		TemplateIdWithCommunityQuestion = "dYg6iHooRq74PyCXmw_Ns7qdJZmbtLoKS2p2FKeaXl0"
		TemplateIdWithCommunityQuestionNotifyAdmin = "rciDm9ThigRBGi1SZ4TFd74XA4aoAxSz_ugdv_tZ450"
		PcWxAppId = "wx4da95782cfc8c5eb"
		PcWxAppSecret = "8f82ebf2ba3aa06ce44541726385df64"
	}
}

func GetWxChat() (officialAccount *officialaccount.OfficialAccount) {
	wc := wechat.NewWechat()
	memory := cache.NewMemory()
	conf := &config.Config{
		AppID:          WxAppId,
		AppSecret:      WxAppSecret,
		Token:          "",
		EncodingAESKey: "",
		Cache:          memory,
	}
	officialAccount = wc.GetOfficialAccount(conf)
	wechatAccessToken := &WechatAccessToken{}
	officialAccount.SetAccessTokenHandle(wechatAccessToken)
	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
}

type WechatAccessToken struct {
}


// GetAccessToken 获取accessToken
func (wechat WechatAccessToken) GetAccessToken() (accessToken string, err error) {
	wxToken, err := wx_token.GetById()
	if err != nil {
		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{"AccessToken", "ExpiresIn"}
		wxToken.AccessToken = tmpAccessToken
		wxToken.ExpiresIn = expires - 600 //快过期前10分钟就刷新掉
		wxToken.Update(updateCols)
	}
	accessToken = wxToken.AccessToken
	return
}

// 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
}

func PcWxGetUserOpenIdByCode(code string) (item *pc.WxAccessToken, err error) {
	if code == "" {
		err = errors.New("code is empty")
		return nil, err
	}
	requestUrl := `https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code`
	requestUrl = fmt.Sprintf(requestUrl, PcWxAppId, PcWxAppSecret, code)
	result, err := http.Get(requestUrl)
	if err != nil {
		return nil, err
	}
	err = json.Unmarshal(result, &item)
	return
}

func PcWxGetUserInfo(openId, accessToken string) (item *pc.WxUserInfo, err error) {
	requestUrl := `https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s`
	requestUrl = fmt.Sprintf(requestUrl, accessToken, openId)
	result, err := http.Get(requestUrl)
	if err != nil {
		return
	}
	err = json.Unmarshal(result, &item)
	return
}


