package official_product_decline

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

type Client struct {
	cfg config.ToolConfig
}

func New(cfg config.ToolConfig) *Client {
	return &Client{
		cfg: cfg,
	}
}

// Call 调用销售同比下滑详情接口
func (c *Client) Call(ctx context.Context, req OfficialProductDeclineRequest) (*OfficialProductDeclineData, error) {
	// 构建 URL 参数
	var queryParams []string

	if req.Page > 0 {
		queryParams = append(queryParams, fmt.Sprintf("page=%d", req.Page))
	}
	if req.Limit > 0 {
		queryParams = append(queryParams, fmt.Sprintf("limit=%d", req.Limit))
	}
	if req.DownwardValue > 0 {
		queryParams = append(queryParams, fmt.Sprintf("downwardValue=%d", req.DownwardValue))
	}
	// showTime 可能是 0，所以这里不做 > 0 判断，如果业务默认是 0 可以忽略，或者根据实际需求
	// 假设始终传递该参数如果已设置
	queryParams = append(queryParams, fmt.Sprintf("showTime=%d", req.ShowTime))

	for _, pid := range req.OfficialProductIds {
		queryParams = append(queryParams, fmt.Sprintf("official_product_id[]=%s", pid))
	}

	for _, t := range req.Ct {
		queryParams = append(queryParams, fmt.Sprintf("ct[]=%s", strings.ReplaceAll(t, " ", "+")))
	}

	queryString := strings.Join(queryParams, "&")
	fullURL := fmt.Sprintf("%s?%s", c.cfg.BaseURL, queryString)

	headers := map[string]string{
		"User-Agent":      "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",
		"Accept":          "application/json, text/plain, */*",
		"Authorization":   fmt.Sprintf("Bearer %s", c.cfg.APIKey),
		"Accept-Language": "zh-CN,zh;q=0.9,en-GB;q=0.8,en;q=0.7",
	}

	reqObj := l_request.Request{
		Method:  "GET",
		Url:     fullURL,
		Headers: headers,
	}

	res, err := reqObj.Send()
	if err != nil {
		return nil, fmt.Errorf("请求失败，err: %v", err)
	}

	var resData OfficialProductDeclineResponse
	if err := json.Unmarshal([]byte(res.Text), &resData); err != nil {
		return nil, fmt.Errorf("解析响应失败，err: %v, resp: %s", err, res.Text)
	}

	if resData.Code != 200 {
		return nil, fmt.Errorf("业务错误，code: %d, msg: %s", resData.Code, resData.Msg)
	}

	return &resData.Data, nil
}
