package service

import (
	"WorldEpcho/src/config"
	"WorldEpcho/src/models"
	"WorldEpcho/src/utils"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strconv"
	"strings"
)

//创建数字人API接口时候返回的响应体
type HuaSoulApiRespones struct {
	Code    int    `from:"code" json:"code"`
	ISLIUid string `from:"ISLIUid" json:"ISLIUid"`
}

func HuaSoulNewAPI(param ...string) (int, string, error) {
	/*
	  根据数字人Id，查询数据库
	*/
	var digitalId, uuid string
	//判断参数长度
	if len(param) == 2 {
		for i := 0; i < len(param); i++ {
			fmt.Println("param: ", param[i])
			digitalId = param[0]
			uuid = param[1]
			fmt.Println(config.ColorCyan, "UUID为: ", uuid, config.ColorReset)
		}
	}
	if len(param) == 1 {
		for i := 0; i < len(param); i++ {
			fmt.Println("param: ", param[i])
			digitalId = param[0]
		}
	}

	dpId, err := strconv.ParseInt(digitalId, 10, 64)
	if err != nil {
		// 转换失败，处理错误
	}

	digitalPerson, err := models.GetDigitalPersonByID(dpId)
	if err != nil {
		log.Println(err.Error())
		log.Println("创建会话时，查询数字人信息失败")
		return 0, "", fmt.Errorf("创建会话时，查询数字人信息失败")
	}
	//fmt.Println(digitalPerson)
	/*
	   构建一个请求参数对象
	*/
	RequestParam := models.NewSoulParam{
		Auth:   config.Conf.SoulAuth,
		Name:   digitalPerson.Name,
		Gend:   digitalPerson.Gender,
		Mantra: digitalPerson.Catchphrases, //口头禅
		Trait:  digitalPerson.Personality,
		BgInfo: digitalPerson.BackgroundInfo,
		IQ:     digitalPerson.MindDeep,
	}
	//从缓存中获取应用名称和用户信息模板
	var name, template string

	if AppCache[uuid] != nil {
		name = AppCache[uuid].AppName
		template = AppCache[uuid].UserInfoTemplate
	}

	if name != "" && template != "" {
		appinfo := models.AppInfo{
			AppName:          name,
			UserInfoTemplate: template,
		}
		// 将结构体转换为 JSON 格式
		jsonData, err := json.Marshal(appinfo)
		if err != nil {
			fmt.Println("Error converting to JSON:", err)
			return 0, "", fmt.Errorf("AppInfo结构体信息转换失败")
		}
		// 将字节切片转换为字符串并打印
		jsonString := string(jsonData)
		fmt.Println("AppInfo: ", jsonString)
		//如果app信息不为空，赋值给请求参数对象
		RequestParam.AppInfo = jsonString
	}
	fmt.Println(RequestParam)
	//quest_url := "http://192.168.2.209:13679/soul/new"
	quest_url := config.Conf.SoulUrl + "/soul/new"
	fmt.Println("New quest_url", quest_url)
	// 准备POST请求的body数据，这里使用bytes.Buffer来构建一个简单的JSON格式数据作为示例
	//requestBody := []byte(`{"key1": "value1", "key2": "value2"}`)
	/*
		requestBody, err := json.Marshal(ReustParam)
		if err != nil {
			fmt.Println("Failed to marshal request body:", err)
			return -1, "请求参数体，解析失败"
		}
	*/
	PostData := url.Values{}
	PostData.Add("auth", RequestParam.Auth)
	PostData.Add("name", RequestParam.Name)
	PostData.Add("gend", RequestParam.Gend)
	PostData.Add("mantra", RequestParam.Mantra)
	PostData.Add("trait", RequestParam.Trait)
	PostData.Add("bgInfo", RequestParam.BgInfo)
	PostData.Add("IQ", utils.Strval(RequestParam.IQ))
	if RequestParam.AppInfo != "" {
		PostData.Add("appInfo", RequestParam.AppInfo)
	}

	// 发送POST请求
	resp, err := http.Post(quest_url, "application/x-www-form-urlencoded", strings.NewReader(PostData.Encode()))
	if err != nil {
		fmt.Println("创建数字人会话连接，出现错误", err)
		log.Println(err.Error())
		return 0, "", nil
	}

	defer resp.Body.Close()

	fmt.Println("Response status:", resp.Status)

	// 读取响应的body数据
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("创建数字人会话连接，读取响应信息错误:", err)
		return 0, "", nil
	}
	// 解析JSON
	var response HuaSoulApiRespones

	err = json.Unmarshal(body, &response)
	if err != nil {
		fmt.Println("创建数字人连接，获取响应体，解析json错误:", err)
		return 0, "", nil
	}
	// 使用解析后的参数
	fmt.Println("New Soul API Code:", response.Code, "code为1成功 0服务失效 3信息格式有误 4非法的服务商")
	fmt.Println("New ISLIUid:", response.ISLIUid)
	return response.Code, response.ISLIUid, nil

}
