package wechat

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/fonchain_enterprise/micro-account/pkg/cache"
	"io/ioutil"
	"net/http"
	"time"
)

type TokenInfo struct {
	AccessToken string `json:"access_token"`
	CreateDate  string `json:"createDate"`
	ErrCode     int    `json:"errcode"`
}

func getNowAccessToken(appID, appSecret string) (openInfo *TokenInfo, err error) {

	str := "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"
	url := fmt.Sprintf(str, appID, appSecret)

	resp, err := http.Get(url)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}

	body, err := ioutil.ReadAll(resp.Body)

	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		fmt.Printf("请求失败%d\n", resp.StatusCode)
		return nil, errors.New(fmt.Sprintf("请求失败%d", resp.StatusCode))
	}

	fmt.Println("返回数据是", string(body))

	err = json.Unmarshal(body, &openInfo)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}

	if openInfo.ErrCode != 0 {
		fmt.Println("微信提示错误", string(body))
		return nil, errors.New("微信提示错误:" + string(body))
	}

	return

}

func GetAccessToken(appID, appSecret string) (openInfo *TokenInfo, err error) {

	key := "wx:token:" + appID

	str := cache.RedisClient.Get(key)
	if str.Val() != "" { //存在
		err := json.Unmarshal([]byte(str.Val()), &openInfo)
		return openInfo, err
	}

	//更新
	openInfo, err = getNowAccessToken(appID, appSecret)
	if err != nil {
		return nil, err
	}

	openInfo.CreateDate = time.Now().Format("2006-01-02 15:04:05")

	r, err := json.Marshal(openInfo)

	fmt.Println(string(r))

	_, err = cache.RedisClient.Set(key, string(r), 6500*time.Second).Result()

	return openInfo, err

}