package controllers

import (
	"eta/eta_report/models"
	"eta/eta_report/services"
	"eta/eta_report/services/wechat"
	"eta/eta_report/utils"
	"fmt"
)

type WechatCommonController struct {
	BaseCommonController
}

// GetWxSign
// @Title 微信获取签名接口-无token校验
// @Description 微信获取签名接口
// @Param   Url   query   string  true       "url地址"
// @Success 200 {object} models.WechatSign
// @router /open/getWxSign [get]
func (this *WechatCommonController) GetWxSign() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	// 微信配置信息
	conf, e := models.GetBusinessConf()
	if e != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取配置信息失败, Err: " + e.Error()
		return
	}
	appId := ""
	appSecret := ""
	if v, ok := conf[models.BusinessConfWxAppId]; ok {
		appId = v
	}
	if v, ok := conf[models.BusinessConfWxAppSecret]; ok {
		appSecret = v
	}

	if appId == "" || appSecret == "" {
		br.Ret = models.BaseRespIgnoreTipsRet
		br.Msg = "微信公众号信息未配置"
		return
	}
	getUrl := this.GetString("Url")
	fmt.Println("getUrl:", getUrl)
	tReq := wechat.WxTokenReq{
		WxAppId:     appId,
		WxAppSecret: appSecret,
	}

	var accessToken string
	if utils.BusinessCode == utils.BusinessCodeRelease {
		// 弘则ETA从eta_pub统一获取
		token, e, msg := wechat.GetAccessToken(tReq)
		if e != nil {
			br.Msg = "获取微信配置失败"
			br.ErrMsg = "获取access_token失败,err:" + msg
			return
		}
		accessToken = token
	} else {
		// 从eta_report获取
		token, e, msg := wechat.GetWxAccessToken(tReq.WxAppId, tReq.WxAppSecret)
		if e != nil {
			br.Msg = "获取微信信息失败"
			br.ErrMsg = "获取access_token失败,err:" + msg
			return
		}
		accessToken = token
	}

	errCode, ticket, err := services.GetWxTicket(accessToken)
	if err != nil {
		if errCode == 40001 {
			// 重新获取
			if utils.BusinessCode == utils.BusinessCodeRelease {
				token, e, msg := wechat.GetAccessToken(tReq)
				if e != nil {
					br.Msg = "获取微信配置失败"
					br.ErrMsg = "获取access_token失败,err:" + msg
					return
				}
				accessToken = token
			} else {
				token, e, msg := wechat.GetWxAccessToken(tReq.WxAppId, tReq.WxAppSecret)
				if e != nil {
					br.Msg = "获取微信信息失败"
					br.ErrMsg = "获取access_token失败,err:" + msg
					return
				}
				accessToken = token
			}

			errCode, ticket, err = services.GetWxTicket(accessToken)
			if err != nil {
				br.Msg = "获取Ticket失败,请联系客服"
				br.ErrMsg = "获取Ticket失败,Err" + err.Error()
				return
			}
		}
		br.Msg = "获取Ticket失败,请联系客服"
		br.ErrMsg = "获取Ticket失败,Err" + err.Error()
		return
	}
	if ticket == "" {
		br.Msg = "获取Ticket失败,请联系客服"
		br.ErrMsg = "ticket为空" + ticket
		return
	}
	nonceStr := utils.GetRandStringNoSpecialChar(16)
	signature, nonceString, timestamp := services.GetWxSignature(ticket, getUrl, nonceStr)
	resp := new(models.WechatSign)
	resp.AppId = appId
	resp.NonceStr = nonceString
	resp.Timestamp = timestamp
	resp.Url = getUrl
	resp.Signature = signature

	br.Ret = 200
	br.Success = true
	br.Msg = "获取签名成功"
	br.Data = resp
}