package zltx

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

type ZltxOrderAfterSalePreCheckTool struct {
	config config.ToolConfig
}

// NewZltxOrderAfterSalePreCheckTool 创建售后订单预检工具
func NewZltxOrderAfterSalePreCheckTool(config config.ToolConfig) *ZltxOrderAfterSalePreCheckTool {
	return &ZltxOrderAfterSalePreCheckTool{config: config}
}

// Name 返回工具名称
func (t *ZltxOrderAfterSalePreCheckTool) Name() string {
	return "zltxOrderAfterSalePreCheck"
}

func (t *ZltxOrderAfterSalePreCheckTool) Description() string {
	return "直连天下售后订单预检工具"
}

func (t *ZltxOrderAfterSalePreCheckTool) Definition() 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{}{
					"orderType": map[string]interface{}{
						"type":        "integer",
						"description": "售后订单类型",
					},
					"orderNumber": map[string]interface{}{
						"type":        "string",
						"description": "售后订单号",
					},
				},
				"required": []string{"orderType", "orderNumber"},
			},
		},
	}
}

type ZltxOrderAfterSalePreCheckRequest struct {
	OrderType   int    `json:"orderType"`
	OrderNumber string `json:"orderNumber"`
}

type ZltxOrderAfterSalePreCheckResponse struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data struct {
		CheckResult bool `json:"checkResult"`
	} `json:"data"`
}

type CheckResult struct {
	OrderType       int      `json:"orderType"`
	OrderNumber     string   `json:"orderNumber"`
	OrderAmount     float64  `json:"orderAmount"`
	OrderPrice      float64  `json:"orderPrice"`
	SignCompany     int      `json:"signCompany"`
	OrderQuantity   int      `json:"orderQuantity"`
	ResellerID      int      `json:"resellerId"`
	ResellerName    string   `json:"resellerName"`
	OurProductID    int      `json:"ourProductId"`
	OurProductTitle string   `json:"ourProductTitle"`
	Account         []string `json:"account"`
	Platforms       struct {
		Num4 string `json:"4"`
	} `json:"platforms"`
}

func (t *ZltxOrderAfterSalePreCheckTool) Execute(ctx context.Context, requireData *entitys.RequireData) error {
	var req ZltxOrderAfterSalePreCheckRequest
	if err := json.Unmarshal([]byte(requireData.Match.Parameters), &req); err != nil {
		return err
	}
	if req.OrderType == 0 || req.OrderNumber == "" {
		return fmt.Errorf("orderType and orderNumber are required")
	}
	return t.checkZltxOrderAfterSalePreCheck(req.OrderType, req.OrderNumber, requireData)
}

func (t *ZltxOrderAfterSalePreCheckTool) checkZltxOrderAfterSalePreCheck(orderType int, orderNumber string, requireData *entitys.RequireData) error {
	req := l_request.Request{
		Url: t.config.BaseURL,
		Headers: map[string]string{
			"Authorization": fmt.Sprintf("Bearer %s", requireData.Auth),
		},
		Method: "POST",
		Data: map[string]string{
			"orderType":   fmt.Sprintf("%d", orderType),
			"orderNumber": orderNumber,
		},
	}
	res, err := req.Send()
	if err != nil {
		return err
	}
	// 解析响应
	var resp ZltxOrderAfterSalePreCheckResponse
	if err := json.Unmarshal(res.Content, &resp); err != nil {
		return err
	}
	if resp.Code != 0 {
		return fmt.Errorf("check failed: %s", resp.Msg)
	}
	jsonByte, err := json.Marshal(resp)
	if err != nil {
		return err
	}
	entitys.ResJson(requireData.Ch, t.Name(), string(jsonByte))
	return nil
}
