package zltx

import (
	"ai_scheduler/internal/config"
	"ai_scheduler/internal/entitys"
	"ai_scheduler/internal/pkg/rec_extra"
	"context"
	"encoding/json"
	"fmt"

	"gitea.cdlsxd.cn/self-tools/l_request"
)

type ZltxOrderLogTool struct {
	config config.ToolConfig
}

func (t *ZltxOrderLogTool) Name() string {
	return "zltxOrderDirectLog"
}

func (t *ZltxOrderLogTool) Description() string {
	return "查询订单日志"
}

func (t *ZltxOrderLogTool) Definition(ctx context.Context) entitys.ToolDefinition {
	return entitys.ToolDefinition{
		Type: "function",
		Function: entitys.FunctionDef{
			Name:        t.Name(),
			Description: t.Description(),
			Parameters: map[string]interface{}{
				"type": "object",
				"properties": map[string]interface{}{
					"order_number": map[string]interface{}{
						"type":        "string",
						"description": "订单编号",
					},
					"serial_number": map[string]interface{}{
						"type":        "string",
						"description": "流水号",
					},
				},
				"required": []string{"order_number", "serial_number"},
			},
		},
	}
}

// ZltxOrderDetailRequest 直连天下订单详情请求参数
type ZltxOrderLogRequest struct {
	OrderNumber  string `json:"order_number"`
	SerialNumber string `json:"serial_number"`
}

// ZltxOrderDetailResponse 直连天下订单详情响应
type ZltxOrderDirectLogResponse struct {
	Code  int                      `json:"code"`
	Error string                   `json:"error"`
	Data  []ZltxOrderDirectLogData `json:"data"`
}

// ZltxOrderLogData 直连天下订单详情数据
type ZltxOrderDirectLogData struct {
	Datetime string                 `json:"datetime"`
	ServerID string                 `json:"serverId"`
	Mes      string                 `json:"mes"`
	Data     map[string]interface{} `json:"data"`
}

func (t *ZltxOrderLogTool) Execute(ctx context.Context, rec *entitys.Recognize) error {
	var req ZltxOrderLogRequest
	if err := json.Unmarshal([]byte(rec.Match.Parameters), &req); err != nil {
		return fmt.Errorf("invalid zltxOrderLog request: %w", err)
	}
	if req.OrderNumber == "" || req.SerialNumber == "" {
		return fmt.Errorf("orderNumber and serialNumber is required")
	}
	return t.getZltxOrderLog(req.OrderNumber, req.SerialNumber, rec)
}

func (t *ZltxOrderLogTool) getZltxOrderLog(orderNumber, serialNumber string, rec *entitys.Recognize) (err error) {
	//查询订单详情
	ext, err := rec_extra.GetTaskRecExt(rec)
	if err != nil {
		return
	}
	url := fmt.Sprintf("%s%s/%s", t.config.BaseURL, orderNumber, serialNumber)
	req := l_request.Request{
		Url: url,
		Headers: map[string]string{
			"Authorization": fmt.Sprintf("Bearer %s", ext.Auth),
		},
		Method: "GET",
	}
	res, err := req.Send()
	var resData ZltxOrderDirectLogResponse
	if err != nil {
		return
	}
	if resData.Code != 200 {
		return fmt.Errorf("订单查询失败：日志查询失败：%s", resData.Error)
	}
	if err = json.Unmarshal(res.Content, &resData); err != nil {
		return
	}
	entitys.ResJson(rec.Ch, t.Name(), res.Text)

	return
}

func NewZltxOrderLogTool(config config.ToolConfig) *ZltxOrderLogTool {
	return &ZltxOrderLogTool{
		config: config,
	}
}
