package zltx

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

type OrderAfterSaleResellerBatchTool struct {
	config config.ToolConfig
}

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

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

// 未使用-仅实现接口
func (t *OrderAfterSaleResellerBatchTool) Description() string {
	return "直连天下下游分销商批充订单售后工具"
}

// 未使用-仅实现接口
func (t *OrderAfterSaleResellerBatchTool) Definition(ctx context.Context) entitys.ToolDefinition {
	return entitys.ToolDefinition{}
}

type OrderAfterSaleResellerBatchRequest struct {
	OrderNumber       []string `json:"orderNumber"`       // 订单号
	AfterType         string   `json:"afterType"`         // 处理方式 1.退款 2.扣款
	AfterSalesPrice   string   `json:"afterSalesPrice"`   // 售后金额
	AfterSalesReason  string   `json:"afterSalesReason"`  // 售后原因
	ResponsibleType   string   `json:"responsibleType"`   // 费用承担者 1.供应商 2.商务 3.公司 4.无
	ResponsiblePerson string   `json:"responsiblePerson"` // 费用承担供应商
}

type OrderAfterSaleResellerBatchResponse struct {
	Code int                                `json:"code"`
	Msg  string                             `json:"msg"`
	Data []*OrderAfterSaleResellerBatchData `json:"data"`
}

type OrderAfterSaleResellerBatchData 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         map[int]string `json:"platforms"`
	AfterType         int            `json:"afterType"`         // 处理方式 1.退款 2.扣款
	Remark            string         `json:"remark"`            // 售后原因
	AfterAmount       float64        `json:"afterAmount"`       // 售后金额
	ResponsibleType   int            `json:"responsibleType"`   // 费用承担者 1.供应商 2.商务 3.公司 4.无
	ResponsiblePerson string         `json:"responsiblePerson"` // 费用承担供应商
	IsExistsAfterSale bool           `json:"isExistsAfterSale"` // 是否已存在售后
	CreateTime        int            `json:"createTime"`        // 创建时间
}

// 接口返回
type OrderAfterSaleResellerBatchApiResponse struct {
	Code  int                                `json:"code"`
	Error string                             `json:"error"`
	Data  OrderAfterSaleResellerBatchApiData `json:"data"`
}
type OrderAfterSaleResellerBatchApiData struct {
	Data    []OrderAfterSaleResellerBatchApiBase             `json:"data"`
	ExtData map[string]OrderAfterSaleResellerBatchApiExtItem `json:"extraData"`
}
type OrderAfterSaleResellerBatchApiBase 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       map[int]string `json:"platforms"`
}
type OrderAfterSaleResellerBatchApiExtItem struct {
	IsExistsAfterSale bool `json:"isExistsAfterSale"` // 是否已存在售后 - 未使用
	SerialCreateTime  int  `json:"createTime"`        // 流水创建时间
}

func (t *OrderAfterSaleResellerBatchTool) Execute(ctx context.Context, rec *entitys.Recognize) error {
	var req OrderAfterSaleResellerBatchRequest
	if err := json.Unmarshal([]byte(rec.Match.Parameters), &req); err != nil {
		return fmt.Errorf("解析参数失败，请重试或联系管理员")
	}
	if len(req.OrderNumber) == 0 {
		return fmt.Errorf("批充订单号不能为空")
	}

	entitys.ResLog(rec.Ch, t.Name(), "正在拉取售后订单信息")

	return t.checkOrderAfterSaleResellerBatch(req, rec)
}

func (t *OrderAfterSaleResellerBatchTool) checkOrderAfterSaleResellerBatch(toolReq OrderAfterSaleResellerBatchRequest, rec *entitys.Recognize) error {
	ext, err := rec_extra.GetTaskRecExt(rec)
	if err != nil {
		return err
	}
	req := l_request.Request{
		Url: t.config.BaseURL,
		Headers: map[string]string{
			"Authorization": fmt.Sprintf("Bearer %s", ext.Auth),
		},
		Method: "POST",
		Json: map[string]any{
			"order_numbers": toolReq.OrderNumber, // 流水号
			"order_type":    2,                   // 2.批充
		},
	}
	res, err := req.Send()
	if err != nil {
		return err
	}
	// 解析响应
	var resp OrderAfterSaleResellerBatchApiResponse
	if err = json.Unmarshal(res.Content, &resp); err != nil {
		return err
	}
	if resp.Code != 200 {
		return fmt.Errorf("售后订单查询异常: %s", resp.Error)
	}
	if len(resp.Data.Data) == 0 {
		return fmt.Errorf("未查询到相应售后订单，请核实订单号是否正确")
	}

	toolResp := OrderAfterSaleResellerBatchResponse{
		Code: resp.Code,
		Msg:  resp.Error,
		Data: make([]*OrderAfterSaleResellerBatchData, 0, len(resp.Data.Data)),
	}

	// 转换数据
	for _, item := range resp.Data.Data {
		// 处理方式
		afterType := util.StringToInt(toolReq.AfterType)
		if afterType == 0 {
			afterType = 1 // 默认退款
		}
		// 费用承担者
		responsibleType := util.StringToInt(toolReq.ResponsibleType)
		if responsibleType == 0 {
			responsibleType = 4 // 默认无
		}
		// 售后金额
		afterSalesPrice := util.StringToFloat64(toolReq.AfterSalesPrice)
		if afterSalesPrice == 0 {
			afterSalesPrice = item.OrderPrice
		}

		toolResp.Data = append(toolResp.Data, &OrderAfterSaleResellerBatchData{
			OrderType:         item.OrderType,
			OrderNumber:       item.OrderNumber,
			OrderAmount:       item.OrderAmount,
			OrderPrice:        item.OrderPrice,
			SignCompany:       item.SignCompany,
			OrderQuantity:     item.OrderQuantity,
			ResellerID:        item.ResellerID,
			ResellerName:      item.ResellerName,
			OurProductID:      item.OurProductID,
			OurProductTitle:   item.OurProductTitle,
			Account:           item.Account,
			Platforms:         item.Platforms,
			AfterType:         afterType,
			Remark:            toolReq.AfterSalesReason,
			AfterAmount:       afterSalesPrice,
			ResponsibleType:   responsibleType,
			ResponsiblePerson: toolReq.ResponsiblePerson,
		})
	}

	// 追加扩展数据
	for _, item := range toolResp.Data {
		if extItem, ok := resp.Data.ExtData[item.OrderNumber]; ok {
			item.IsExistsAfterSale = item.OrderType > 100 // 102 批充&已售后
			item.CreateTime = extItem.SerialCreateTime
		}
	}

	jsonByte, err := json.Marshal(toolResp)
	if err != nil {
		return err
	}

	entitys.ResLog(rec.Ch, t.Name(), "售后订单信息拉取完成")
	entitys.ResJson(rec.Ch, t.Name(), string(jsonByte))
	return nil
}
