package main

import (
	"PsycheEpic/src/config"
	"PsycheEpic/src/service"
	"PsycheEpic/src/utils"
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

type RequestBody struct {
	Phone           string `json:"phone"`
	SerialNo        string `json:"serialNo"`
	SchoolName      string `json:"schoolName"`
	CallbackAddress string `json:"callbackAddress"`
	RequestNo       string `json:"requestNo"`
}

// 发送 POST 请求的函数
func PostSelectAiMentalClinicList(c *gin.Context) {
	// 设置请求头
	key := config.Conf.AppKey
	appSecret := config.Conf.AppSecret
	// 获取当前时间
	now := time.Now()
	// 将当前时间转换为Unix时间戳（秒级）
	timestamp := now.Unix()
	timeStr := utils.Strval(timestamp)
	uuid := utils.GenerateUUID()
	//获取token
	token, _ := service.GetPopAccessToken(key, appSecret)
	//获取签名
	signature, _ := service.GenerateSignature(token, timeStr, uuid, appSecret)

	headers := map[string]string{
		"access-pop-token":         token,
		"access-pop-key":           "d1526328-ac75-4496-9b99-6598293af574",
		"access-pop-timestrap":     timeStr,
		"access-pop-noncestr":      uuid,
		"Content-Type":             "application/json",
		"access-pop-signature":     signature,
		"access-pop-supplier-type": "1",
	}

	// 设置请求体
	// 创建一个 RequestBody 类型的实例
	requestBody := RequestBody{
		Phone:           "17727960067",
		SerialNo:        "学生编号",
		SchoolName:      "学校名称",
		CallbackAddress: "https://180.174.13.225:8089/AiMentalClinicData",
		RequestNo:       uuid,
	}

	// 将结构体实例转换为 JSON 格式的字节流
	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Println("Error marshalling JSON:", err)
		return
	}
	url := config.Conf.MentalClinicUrl
	// 创建请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	// 添加请求头
	for key, value := range headers {
		req.Header.Set(key, value)
	}

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 将响应体作为字节切片发送回客户端
	c.Data(resp.StatusCode, "application/json", body)
}

func main() {
	router := gin.Default()
	config.InitConfig()
	router.POST("/selectAiMentalClinicList", PostSelectAiMentalClinicList)
	router.Run(":8080")
}

// processData 是一个独立的函数，用于处理 POST 请求
func ProcessData(c *gin.Context) {
	var jsonData map[string]interface{}

	// 绑定 JSON 到 jsonData
	if err := c.BindJSON(&jsonData); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 打印接收到的数据（可选）
	println(jsonData)

	// 响应
	c.JSON(http.StatusOK, gin.H{"message": "ok"})
}
