package chatrecords

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"github.com/alibabacloud-go/tea/tea"
	"io"
	"net/http"
	"time"
	"wechat-api/ent/wxcard"
	"wechat-api/ent/wxcarduser"
	"wechat-api/hook/fastgpt"
	"wechat-api/internal/utils/dberrorhandler"
	"wechat-api/internal/utils/jwt"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AnswerApiChatLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAnswerApiChatLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AnswerApiChatLogic {
	return &AnswerApiChatLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx}
}

func (l *AnswerApiChatLogic) AnswerApiChat(req *types.ChatAskReq) (*types.ChatAskResp, error) {
	resp := types.ChatAskResp{}
	userId := l.ctx.Value("userId").(uint64)

	card, err := l.svcCtx.DB.WxCard.Query().Where(wxcard.ID(*req.CardId)).Only(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	userInfo, _ := l.svcCtx.DB.WxCardUser.Query().Where(wxcarduser.ID(userId)).First(l.ctx)

	var chatReq fastgpt.ChatReq
	chatReq.Stream = false
	message := make([]fastgpt.Message, 0, 1)
	message = append(message, fastgpt.Message{
		Content: *req.Question,
		Role:    "user",
	})
	chatReq.Messages = message
	chatReq.ChatId = jwt.HashidsEncode(*req.SessionId)
	chatReq.Variables = fastgpt.Variables{
		Uid:  jwt.HashidsEncode(int(userId)),
		Name: userInfo.Nickname,
	}

	// 設置請求體 (這裡是一個簡單的範例，你可以根據需要調整)
	jsonData, _ := json.Marshal(chatReq)
	fmt.Printf("request data:%v\n", string(jsonData))

	// 建立HTTP請求
	url := card.APIBase + fastgpt.GetChatUrl()
	fmt.Printf("url=%v \n", url)
	request, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Error creating request:%v", err)
		return nil, err
	}

	// 設置請求頭
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Authorization", "Bearer "+card.APIKey)

	// 發送請求
	client := &http.Client{
		Timeout: time.Second * 60,
	}
	response, err := client.Do(request)
	defer response.Body.Close()

	// 对返回的内容进行处理
	answerByte, _ := io.ReadAll(response.Body)
	fmt.Printf("answer=%s\n", answerByte)

	chatData := fastgpt.ChatNoStreamResp{}
	err = json.Unmarshal(answerByte, &chatData)
	if err != nil {
		fmt.Printf("json unmarshall error:%v\n", err)
		return nil, err
	}
	fmt.Printf("response=%v\n", chatData.Choices)
	resp.Data = tea.String(chatData.Choices[0].Message.Content)

	return &resp, nil
}
