package v1

import (
	"context"
	"designs/global"
	"designs/service"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"net/url"
	"time"
)

// 获取微信的accessCode
func GetAccessToken(gid string, ttAppid string, ttSecret string) (string, error) {
	tokenKey := gid + "||" + "wxToken"

	AccessToken := global.App.Redis.Get(context.Background(), tokenKey).Val()
	if AccessToken == "" {

		params := url.Values{
			"appid":      {ttAppid},
			"secret":     {ttSecret},
			"grant_type": {"client_credential"},
		}

		//请求接口获取token
		content, err := service.CurlGet("https://api.weixin.qq.com/cgi-bin/token", params, nil)
		if err != nil {
			return "", err
		}
		var resp struct {
			AccessToken string `json:"access_token"`
			ExpiresIn   int    `json:"expires_in"`
			ExpiresAt   int    `json:"expiresAt"`
			Errcode     int    `json:"errcode"`
			Errmsg      string `json:"errmsg"`
		}

		str2oErr := json.Unmarshal([]byte(content), &resp)
		if str2oErr != nil {
			return "", err
		}

		if resp.Errcode != 0 {
			return "", errors.New(resp.Errmsg)
		}

		AccessToken = resp.AccessToken
		global.App.Redis.Set(context.Background(), tokenKey, AccessToken, time.Second*30)
	}

	return AccessToken, nil
}

// 获取微信的当日数据
func GetDaily(c *gin.Context) {
	//form := request.Check(c, &struct {
	//
	//}{})

}
