package aiser

import (
	"encoding/json"
	"errors"
	"eta/eta_api/models/aimod"
	"eta/eta_api/utils"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

func ChatAutoMsg(prompt string, historyChatList []aimod.HistoryChat, model string) (result string, err error) {
	chatUrl := utils.EtaAiUrl + `chat/auto_msg`

	param := make(map[string]interface{})
	param["Prompt"] = prompt
	param["HistoryChatList"] = historyChatList
	param["model"] = model

	postData, err := json.Marshal(param)

	if err != nil {
		return result, err
	}

	client := &http.Client{}
	//提交请求
	reqest, err := http.NewRequest("POST", chatUrl, strings.NewReader(string(postData)))
	businessCode := utils.BusinessCode
	if businessCode == "" {
		return businessCode, errors.New("未获取到商户号")
	}
	nonce := utils.GetRandStringNoSpecialChar(16)
	timestamp := time.Now().Format(utils.FormatDateTimeUnSpace)
	signature := utils.GetSign(nonce, timestamp, utils.EtaAppid, utils.EtaSecret)
	//增加header选项
	reqest.Header.Add("BusinessCode", businessCode)
	reqest.Header.Add("Nonce", nonce)
	reqest.Header.Add("Timestamp", timestamp)
	reqest.Header.Add("Appid", utils.EtaAppid)
	reqest.Header.Add("Signature", signature)
	reqest.Header.Set("Content-Type", "application/json")

	utils.FileLog.Info("postData:" + string(postData))

	response, err := client.Do(reqest)
	if err != nil {
		return
	}
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)

	utils.FileLog.Info("result:" + string(body))

	resp := new(ChatAutoMsgResp)
	err = json.Unmarshal(body, &resp)
	if err != nil {
		return result, err
	}
	if resp.Ret != 200 {
		return resp.Msg, nil
	}
	result = resp.Data
	return result, nil
}

func OpenAiFileUpload(fileUrl, fileName, model string) (result *OpenAiFileUploadResp, err error) {
	chatUrl := utils.EtaAiUrl + `chat/file/upload`

	param := make(map[string]interface{})
	param["FileUrl"] = fileUrl
	param["FileName"] = fileName
	param["Model"] = model

	postData, err := json.Marshal(param)
	if err != nil {
		return result, err
	}

	client := &http.Client{}
	//提交请求
	reqest, err := http.NewRequest("POST", chatUrl, strings.NewReader(string(postData)))
	businessCode := utils.BusinessCode
	if businessCode == "" {
		return nil, errors.New("未获取到商户号")
	}
	nonce := utils.GetRandStringNoSpecialChar(16)
	timestamp := time.Now().Format(utils.FormatDateTimeUnSpace)
	signature := utils.GetSign(nonce, timestamp, utils.EtaAppid, utils.EtaSecret)
	//增加header选项
	reqest.Header.Add("BusinessCode", businessCode)
	reqest.Header.Add("Nonce", nonce)
	reqest.Header.Add("Timestamp", timestamp)
	reqest.Header.Add("Appid", utils.EtaAppid)
	reqest.Header.Add("Signature", signature)
	reqest.Header.Set("Content-Type", "application/json")

	utils.FileLog.Info("postData:" + string(postData))

	response, err := client.Do(reqest)
	if err != nil {
		return
	}
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)

	utils.FileLog.Info("result:" + string(body))

	resp := new(OpenAiFileUploadResp)
	err = json.Unmarshal(body, &resp)
	if err != nil {
		return result, err
	}
	return resp, nil
}

func FileRetrieve(assistantId, threadId, model string, historyChatList []aimod.HistoryChat, OpenaiFileId []string) (result *OpenAiFileRetrieveResp, err error) {
	chatUrl := utils.EtaAiUrl + `chat/file/retrieve`

	param := make(map[string]interface{})
	param["FileRetrieveList"] = historyChatList
	param["OpenaiFileId"] = OpenaiFileId
	param["AssistantId"] = assistantId
	param["ThreadId"] = threadId
	param["Model"] = model

	postData, err := json.Marshal(param)
	if err != nil {
		return result, err
	}

	client := &http.Client{}
	//提交请求
	reqest, err := http.NewRequest("POST", chatUrl, strings.NewReader(string(postData)))
	businessCode := utils.BusinessCode
	if businessCode == "" {
		return nil, errors.New("未获取到商户号")
	}
	nonce := utils.GetRandStringNoSpecialChar(16)
	timestamp := time.Now().Format(utils.FormatDateTimeUnSpace)
	signature := utils.GetSign(nonce, timestamp, utils.EtaAppid, utils.EtaSecret)
	//增加header选项
	reqest.Header.Add("BusinessCode", businessCode)
	reqest.Header.Add("Nonce", nonce)
	reqest.Header.Add("Timestamp", timestamp)
	reqest.Header.Add("Appid", utils.EtaAppid)
	reqest.Header.Add("Signature", signature)
	reqest.Header.Set("Content-Type", "application/json")

	utils.FileLog.Info("postData:" + string(postData))

	response, err := client.Do(reqest)
	if err != nil {
		return
	}
	defer response.Body.Close()

	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return
	}

	utils.FileLog.Info("result:" + string(body))

	resp := new(OpenAiFileRetrieveResp)
	err = json.Unmarshal(body, &resp)
	if err != nil {
		return result, err
	}
	return resp, nil
}

type ChatAutoMsgResp struct {
	Ret  int
	Data string
	Msg  string
}

type OpenAiFileUploadResp struct {
	Ret  int
	Data *OpenAiFile
	Msg  string
}

type OpenAiFile struct {
	Bytes         int    `json:"bytes"`
	CreatedAt     int64  `json:"created_at"`
	ID            string `json:"id"`
	FileName      string `json:"filename"`
	Object        string `json:"object"`
	Status        string `json:"status"`
	Purpose       string `json:"purpose"`
	StatusDetails string `json:"status_details"`
}

type OpenAiFileRetrieveResp struct {
	Ret    int
	Data   *FileRetrieveResp
	Msg    string
	ErrMsg string
}

type FileRetrieveResp struct {
	AssistantId string `description:"助手ID"`
	ThreadId    string `description:"进程id"`
	Answer      string
}
