package service

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

// 发送 POST 请求的函数
func GetPopAccessToken(appkey, appSecret string) (string, error) {
	requestURL := config.Conf.GetTokenUrl
	fmt.Println("requestURL", requestURL)

	requestBody, err := json.Marshal(map[string]string{
		"appKey":    appkey,
		"appSecret": appSecret,
	})
	if err != nil {
		fmt.Println(err.Error())
		return "", err
	}

	resp, err := http.Post(requestURL, "application/json", bytes.NewBuffer(requestBody))
	if err != nil {
		fmt.Println(err.Error())
		return "", err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return "", err
	}

	var responseData map[string]interface{}
	err = json.Unmarshal(body, &responseData)
	if err != nil {
		fmt.Println(err.Error())
		return "", err
	}

	// 检查响应中的code
	if code, ok := responseData["code"].(float64); ok {
		switch int(code) {
		case 200:
			accessTokenData, found := responseData["data"].(map[string]interface{})
			if !found || accessTokenData["accessToken"] == nil {
				fmt.Println("accessToken not found in response data")
				return "", fmt.Errorf("accessToken not found in response data")
			}
			accessTokenStr, ok := accessTokenData["accessToken"].(string)
			if !ok {
				fmt.Println("Access token is not a string")
				return "", fmt.Errorf("access token is not a string")
			}
			fmt.Println("Access token:", accessTokenStr)
			return accessTokenStr, nil

		case 440:
			// 处理授权信息到期
			msg := "开放平台授权信息到期！"
			if message, ok := responseData["msg"].(string); ok {
				msg = message
			}
			fmt.Println("Error:", msg)
			return "", fmt.Errorf("%s", msg)

		case 500:
			// 更进一步的处理工作
			return "", fmt.Errorf("无法获取accessToken")
		default:
			// 更进一步的处理工作
			return "", fmt.Errorf("无法获取accessToken")
		}
	} else {
		return "", fmt.Errorf("无法获取accessToken")
	}

	// 非预期的状态码处理
	return "", fmt.Errorf("无法获取accessToken, unexpected status code: %d", resp.StatusCode)
}
