package wechat

import (
	"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/user"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/models/tables/wx_token"
	"time"
)

var (
	WxId                string //微信原始ID
	WxAppId             string
	WxAppSecret         string
	TemplateIdByProduct string //产品运行报告通知-模板ID

	TemplateRedirectUrl                   string //模板消息跳转地址
	DayReportTemplateRedirectUrl          string //模板消息跳转地址（晨报、周报）
	TemplateIdByCompanyApply              string //客户申请单审批通知-模板ID
	TemplateCompanyApplyRedirectUrl       string //审批单模板消息跳转地址
	TemplateIdByCompanyReceive            string //销售跨部门领取客户通知-模板ID
	WxMsgTemplateIdActivityChangeApply    string //查研观向活动变更通知-模板ID
	WxMsgTemplateIdActivityChangeApplyXzs string //查研观向活动变更通知-模板ID（小助手）
	TemplateIdByProductXzs                string //产品运行报告通知-模板ID(小助手)
	WxCygxAppId                           string //查研观向小程序APPID
	WxMsgTemplateIdAskByUser              string //查研观向用户提问新消息推送ID
	WxCrmAppId                            string //随手办公小程序APPID
	WxPublicIdXzs                         string //查研观向小助手公众号
	WxPublicSecretXzs                     string //查研观向小助手公众号
)

func init() {
	if global.CONFIG.Serve.RunMode == "debug" {
		WxAppId = "wx9b5d7291e581233a"
		WxAppSecret = "f4d52e34021eee262dce9682b31f8861"
		WxId = "gh_5dc508325c6f"
		TemplateIdByProduct = "-YjuPOB7Fqd-S3ilabYa6wvjDY9aXmeEfPN6DCiy-EY"
		TemplateRedirectUrl = "http://rddpweb.brilliantstart.cn/reportdtl?id="
		DayReportTemplateRedirectUrl = "http://report.brilliantstart.cn/#/allindex/" //晨报模板跳转url
		TemplateIdByCompanyApply = "eTalI1LbiT_B0mTaBeDTlfSMITenK8dQIgEB5yqjjvA"
		TemplateCompanyApplyRedirectUrl = "http://advisoryadmin.brilliantstart.cn/approval/approval/list"
		//销售跨部门领取客户通知
		TemplateIdByCompanyReceive = "KAxFvX79f-DHmtC_Jw98elvqxiDPK0xP_b48LUT-Y14"
		WxMsgTemplateIdActivityChangeApply = "CB7bOl7f3viMG4s1uhRo7WM0Jbx3WvodKuIZ8A_z8fM"

		WxMsgTemplateIdAskByUser = `qfNuops-sKrfIkbA7U97A7gSrX03mUpoEpJksRUdloo`
	} else {
		//WxAppId = "wx4a844c734d8c8e56"
		//WxAppSecret = "26c586e7ccb3c575433f0f37797b3eeb"
		//WxId = "gh_b67e0049fb8c"
		//TemplateIdByProduct = "Cp2wF8gvBtxyWV4DeYuI172oqwyYXVRSm3AyJO42d84"
		//TemplateRedirectUrl = "https://ficc.hzinsights.com/reportdtl?id="
		//DayReportTemplateRedirectUrl = "https://report.hzinsights.com/#/allindex/" //晨报模板跳转url
		//TemplateIdByCompanyApply = "ZKcOfNIWBpwHJxpptufHIK1mp2nIwkT3cxub-35cFqI"
		//TemplateCompanyApplyRedirectUrl = "https://ficc.hzinsights.com/approval/approval/list"
		//WxMsgTemplateIdActivityChangeApply = "dYg6iHooRq74PyCXmw_Ns7qdJZmbtLoKS2p2FKeaXl0"
		////销售跨部门领取客户通知
		//TemplateIdByCompanyReceive = "A5fV-XWBcu-LIj_W-tBiOJ-D39a9WDd9GOB0WGbpoBg"
		//TemplateCompanyApplyRedirectUrl = "https://ficc.hzinsights.com/approval/approval/list"
	}
}

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
}

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
}
