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) (result string, err error) {
	chatUrl := utils.EtaAiUrl + `chat/auto_msg`

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

	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
}

type ChatAutoMsgResp struct {
	Ret  int
	Data string
	Msg  string
}