package zltx

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

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

type ZltxOrderStatisticsTool struct {
	config *config.Config
	rdb    *utils.Rdb
}

func (z ZltxOrderStatisticsTool) Name() string {
	return "zltxOrderStatistics"
}

func (z ZltxOrderStatisticsTool) Description() string {
	return "通过账号获取订单统计信息"
}

func (z ZltxOrderStatisticsTool) Definition(ctx context.Context) entitys.ToolDefinition {
	return entitys.ToolDefinition{
		Type: "function",
		Function: entitys.FunctionDef{
			Name:        z.Name(),
			Description: z.Description(),
			Parameters: map[string]interface{}{
				"type": "object",
				"properties": map[string]interface{}{
					"number": map[string]interface{}{
						"type":        "string",
						"description": "账号或分销商号",
					},
				},
				"required": []string{"number"},
			},
		},
		AuthFunc: func(rec *entitys.Recognize) ([]byte, error) {
			ext, err := rec_extra.GetTaskRecExt(rec)
			if err != nil {
				return nil, err
			}
			if len(ext.Auth) > 0 {
				return []byte(ext.Auth), nil
			} else {
				login := lsxd.NewLogin(z.config, z.rdb)
				token := login.GetToken(ctx)
				return []byte(token), nil
			}
		},
	}
}

type ZltxOrderStatisticsRequest struct {
	Number interface{} `json:"number"`
}

func (z ZltxOrderStatisticsTool) Execute(ctx context.Context, rec *entitys.Recognize) error {
	var req ZltxOrderStatisticsRequest
	if err := json.Unmarshal([]byte(rec.Match.Parameters), &req); err != nil {
		return err
	}
	if req.Number == nil {
		return fmt.Errorf("number is required")
	}
	return z.getZltxOrderStatistics(ctx, req.Number, rec)
}

type ZltxOrderStatisticsResponse struct {
	Code int `json:"code"`
	Data struct {
		RecentThreeDays []ZltxOrderStatisticsData `json:"recentThreeDays"`
		RecentOneMonth  []ZltxOrderStatisticsData `json:"recentOneMonth"`
	} `json:"data"`
	Error string `json:"error"`
}

type ZltxOrderStatisticsData struct {
	Date    string `json:"date"`
	Number  string `json:"number"`
	Success int    `json:"success"`
	Fail    int    `json:"fail"`
	Total   int    `json:"total"`
}

func (z ZltxOrderStatisticsTool) getZltxOrderStatistics(ctx context.Context, number interface{}, rec *entitys.Recognize) error {
	token, err := z.Definition(ctx).AuthFunc(rec)
	if err != nil {
		return err
	}
	//查询订单详情
	url := fmt.Sprintf("%s%s", z.config.Tools.ZltxOrderStatistics.BaseURL, fmt.Sprintf("%v", number))
	req := l_request.Request{
		Url: url,
		Headers: map[string]string{
			"Authorization": fmt.Sprintf("Bearer %s", string(token)),
		},
		Method: "GET",
	}
	res, err := req.Send()
	var resData ZltxOrderStatisticsResponse
	if err != nil {
		return err
	}
	if err := json.Unmarshal(res.Content, &resData); err != nil {
		return err
	}
	if resData.Code != 200 {
		return fmt.Errorf("为获取到数据，请检查权限: %s", string(res.Content))
	}
	//按照日期排序
	sort.Slice(resData.Data.RecentThreeDays, func(i, j int) bool {
		return resData.Data.RecentThreeDays[i].Date < resData.Data.RecentThreeDays[j].Date
	})
	sort.Slice(resData.Data.RecentOneMonth, func(i, j int) bool {
		return resData.Data.RecentOneMonth[i].Date < resData.Data.RecentOneMonth[j].Date
	})
	jsonByte, err := json.Marshal(resData)
	if err != nil {
		return err
	}
	entitys.ResJson(rec.Ch, z.Name(), string(jsonByte))
	return nil
}

func NewZltxOrderStatisticsTool(config *config.Config, rdb *utils.Rdb) *ZltxOrderStatisticsTool {
	return &ZltxOrderStatisticsTool{
		config: config,
		rdb:    rdb,
	}
}
