package service

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

// PhoneInfo 包含用户手机号信息
type PhoneInfo struct {
	PhoneNumber     string `json:"phoneNumber"`
	PurePhoneNumber string `json:"purePhoneNumber"`
	CountryCode     string `json:"countryCode"`
	Watermark       struct {
		Timestamp int64  `json:"timestamp"`
		Appid     string `json:"appid"`
	} `json:"watermark"`
}

// Response 包含微信小程序API的响应数据结构
type Response struct {
	ErrCode   int       `json:"errcode"`
	ErrMsg    string    `json:"errmsg"`
	PhoneInfo PhoneInfo `json:"phone_info"`
}

// GetUserPhoneNumber 发送POST请求到微信小程序的getuserphonenumber接口
func GetWechatUserPhoneNumber(code string) (*PhoneInfo, error) {
	//获取token
	accessToken, exprTimestamp, err := GetWeixinToken()
	if err != nil {
		log.Printf("获取微信token出错: %v", err)
		return nil, err
	}
	// 获取当前时间秒数
	nowTime := time.Now().Unix()
	if nowTime > exprTimestamp {
		log.Printf("微信token已经过期")
		return nil, errors.New("请求微信服务器失败")
	}

	formaturl := config.Conf.WechatGetPhoneUrl
	fmt.Println(config.ColorBlue, " accessToken: ", accessToken, config.ColorReset)
	url := fmt.Sprintf(formaturl, accessToken)

	// 构造请求数据
	requestData := map[string]string{
		"code": code,
	}
	requestBody, err := json.Marshal(requestData)
	if err != nil {
		log.Printf("Error marshaling request data: %v", err)
		return nil, err
	}
	fmt.Println(config.ColorBlue, " 手机code码 : ", string(requestBody), config.ColorReset)
	// 发送POST请求
	resp, err := http.Post(url, "application/json", bytes.NewReader(requestBody))
	if err != nil {
		log.Printf("Error sending POST request: %v", err)
		return nil, err
	}
	defer resp.Body.Close()

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

	// 反序列化响应数据
	var response Response
	if err = json.Unmarshal(body, &response); err != nil {
		log.Printf("Error unmarshaling response: %v", err)
		return nil, err
	}
	if response.ErrCode == 0 && response.ErrMsg == "ok" {
		log.Printf("获取用户手机号成功")
		fmt.Println("response: ", response)
		return &response.PhoneInfo, nil
	} else if response.ErrCode == -1 {
		log.Printf("系统繁忙，此时请开发者稍候再试")
		fmt.Println("response: ", response)
		return nil, errors.New("系统繁忙，此时请开发者稍候再试")
	} else if response.ErrCode == 40029 {
		log.Printf("js_code无效")
		fmt.Println("response: ", response)
		return nil, errors.New("js_code无效")
	} else if response.ErrCode == 45011 {
		log.Printf("API 调用太频繁，请稍候再试")
		fmt.Println("response: ", response)
		return nil, errors.New("API 调用太频繁，请稍候再试")
	} else {
		log.Printf("请求appid身份与获取code的小程序appid不匹配")
		fmt.Println("response: ", response)
		return nil, errors.New("请求appid身份与获取code的小程序appid不匹配")
	}
	fmt.Println("微信用户手机信息: ", response.PhoneInfo)
	return &response.PhoneInfo, nil
}
