package service

import (
	"WorldEpcho/src/config"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

// 定义返回的结构体
type TokenResponse struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
}

func GetWeixinToken() (string, int64, error) {
	appId := config.Conf.WechatAppId
	// 微信小程序appSecret
	appSecret := config.Conf.WechatAppSecret
	formatURL := config.Conf.WechatAccessTokenUrl
	// 构造请求URL
	url := fmt.Sprintf(formatURL, appId, appSecret)

	// 发送GET请求
	resp, err := http.Get(url)
	if err != nil {
		log.Printf("failed to get token: %v", err) // 使用log.Printf代替log.Fatalf，避免中断程序

		return "", 0, err
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Printf("failed to read response body: %v", err)
		return "", 0, err
	}

	// 反序列化JSON到结构体
	var tokenResponse TokenResponse
	if err = json.Unmarshal(body, &tokenResponse); err != nil {
		log.Printf("failed to unmarshal json: %v", err)
		return "", 0, err
	}

	// 计算过期时间
	// 计算过期时间的时间戳
	expireTimeStamp := time.Now().Add(time.Second * time.Duration(tokenResponse.ExpiresIn)).Unix()
	//expireTime := time.Now().Add(time.Second * time.Duration(tokenResponse.ExpiresIn)).Format("2006-01-02 15:04:05")

	// 返回token和过期时间
	return tokenResponse.AccessToken, expireTimeStamp, nil
}
