package chatrecords

import (
	"context"
	"fmt"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"github.com/zeromicro/go-zero/core/errorx"
	"strconv"
	"wechat-api/ent/employee"
	"wechat-api/hook/dify"
	"wechat-api/internal/utils"
	jwtutils "wechat-api/internal/utils/jwt"

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

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

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

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

func (l *GptsGetApiMessageLogic) GptsGetApiMessage(req *types.GptMessageReq, tokenStr string) (*types.GptMessageResp, error) {
	resp := types.GptMessageResp{}

	claims, err := jwtutils.ParseJwtToken(l.svcCtx.Config.Auth.AccessSecret, tokenStr)
	if err != nil {
		return nil, errorx.NewInvalidArgumentError("用户未登录")
	}
	userId, ok := claims["userId"].(string)

	if !ok || userId == "" {
		return nil, errorx.NewInvalidArgumentError("用户需要登录")
	}

	userInfo, _ := l.svcCtx.CoreRpc.GetUserById(l.ctx, &core.UUIDReq{Id: userId})
	valid := utils.CheckGptLogin(userInfo.RoleIds)
	if !valid {
		return nil, errorx.NewInvalidArgumentError("用户不允许登陆")
	}

	var firstId, limit string
	if req.FirstId != nil && *req.FirstId != "" {
		firstId = *req.FirstId
	}
	if req.Limit != nil && *req.Limit > 0 {
		limit = strconv.Itoa(*req.Limit)
	}

	employeeItem, err := l.svcCtx.DB.Employee.Query().Where(employee.ID(*req.AgentId)).Only(l.ctx)
	if err != nil {
		return nil, errorx.NewInvalidArgumentError("智能体不存在")
	}

	user := fmt.Sprintf("%s-%d", userId, *req.AgentId)
	response, err := dify.GetChatHistory(employeeItem.APIBase, employeeItem.APIKey, user, *req.ConversationId, firstId, limit)
	if err != nil {
		return &resp, nil
	}

	resp.Data.HasMore = response.HasMore
	for _, v := range response.Data {
		resp.Data.Data = append(resp.Data.Data, types.Message{
			Id:             &v.ID,
			ConversationId: &v.ConversationId,
			Answer:         &v.Answer,
			Query:          &v.Query,
			Inputs:         &v.Inputs,
			CreatedAt:      tea.Int(int(v.CreatedAt)),
		})
	}

	return &resp, nil
}
