package bbxt

import (
	"ai_scheduler/internal/pkg"
	"ai_scheduler/internal/pkg/l_request"
	"ai_scheduler/internal/pkg/util"
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"

	"strings"

	"github.com/go-kratos/kratos/v2/log"
)

type StatisOursProductLossSumReq struct {
	ResellerId int      `json:"reseller_id,omitempty"`
	Ct         []string `json:"ct,omitempty"`
}

type StatisOursProductLossSumRes struct {
	List []*StatisOursProductLossSumResponse `protobuf:"bytes,1,rep,name=list,proto3" json:"list,omitempty"`
}

type StatisOursProductLossSumResponse struct {
	OursProductId   int32   `json:"oursProductId,omitempty"`
	OursProductName string  `json:"oursProductName,omitempty"`
	ResellerName    string  `json:"resellerName,omitempty"`
	ResellerId      int32   `json:"resellerId,omitempty"`
	Loss            float64 `json:"loss,omitempty"`
}

const Base = "https://reportapi.1688sup.com/api"
const AuthUrl = "http://test.analysis.com/api"

// StatisOursProductLossSumApi 负利润分析
func StatisOursProductLossSumApi(param *StatisOursProductLossSumReq) (*StatisOursProductLossSumRes, error) {
	url := "/dataanalytics/statisOursProductLossSum"
	var res StatisOursProductLossSumRes
	if err := request(url, param, &res, ""); err != nil {
		return nil, err
	}
	return &res, nil
}

// StatisOursProductLossSumApi 负利润分析
func StatisOursProductLossSumApiWithAuth(param *StatisOursProductLossSumReq, token string) (*StatisOursProductLossSumRes, error) {
	url := "/dataanalytics/statisOursProductLossSum"
	var res StatisOursProductLossSumRes
	if err := request(url, param, &res, token); err != nil {
		return nil, err
	}
	return &res, nil
}

type GetProfitRankingSumRequest struct {
	Ct          []string `json:"ct,omitempty"`
	Page        int32    `json:"page,omitempty"`
	Limit       int32    `json:"limit,omitempty"`
	ResellerIds []int32  `json:"reseller_ids,omitempty"`
}

type GetProfitRankingSumResponse struct {
	List      []*ProfitRankingSumResponse `protobuf:"bytes,1,rep,name=list,proto3" json:"list,omitempty"`
	DataCount int32                       `protobuf:"varint,2,opt,name=data_count,json=dataCount,proto3" json:"data_count,omitempty"`
}

type ProfitRankingSumResponse struct {
	// 分销商ID
	ResellerId string `protobuf:"bytes,1,opt,name=reseller_id,json=resellerId,proto3" json:"ResellerId,omitempty"`
	// 分销商名称
	ResellerName string `protobuf:"bytes,2,opt,name=reseller_name,json=resellerName,proto3" json:"ResellerName,omitempty"`
	// 当前利润
	CurrentProfit float64 `protobuf:"fixed64,3,opt,name=current_profit,json=currentProfit,proto3" json:"CurrentProfit,omitempty"`
	// 昨日同比利润
	HistoryOneProfit float64 `protobuf:"fixed64,4,opt,name=history_one_profit,json=historyOneProfit,proto3" json:"HistoryOneProfit,omitempty"`
	// 上周同比利润
	HistoryTwoProfit float64 `protobuf:"fixed64,5,opt,name=history_two_profit,json=historyTwoProfit,proto3" json:"HistoryTwoProfit,omitempty"`
	// 昨日同比利润差值
	HistoryOneDiff float64 `protobuf:"fixed64,6,opt,name=history_one_diff,json=historyOneDiff,proto3" json:"HistoryOneDiff,omitempty"`
	// 上周同比利润差值
	HistoryTwoDiff float64 `protobuf:"fixed64,7,opt,name=history_two_diff,json=historyTwoDiff,proto3" json:"HistoryTwoDiff,omitempty"`
}

// GetProfitRankingSumApi 利润同比分销商排行榜
func GetProfitRankingSumApi(param *GetProfitRankingSumRequest) (*GetProfitRankingSumResponse, error) {
	url := "/dataanalytics/profitRankingSum"
	var res GetProfitRankingSumResponse
	if err := request(url, param, &res, ""); err != nil {
		return nil, err
	}
	return &res, nil
}

type GetStatisOfficialProductSumRequest struct {
	Ct                []string `protobuf:"bytes,1,rep,name=ct,proto3" json:"ct,omitempty"`
	DownwardValue     int32    `protobuf:"varint,4,opt,name=downward_value,json=downwardValue,proto3" json:"downward_value,omitempty"`
	Page              int32    `protobuf:"varint,5,opt,name=page,proto3" json:"page,omitempty"`
	Limit             int32    `protobuf:"varint,6,opt,name=limit,proto3" json:"limit,omitempty"`
	OfficialProductId []int32  `protobuf:"varint,7,rep,packed,name=official_product_id,json=officialProductId,proto3" json:"official_product_id,omitempty"`
}

type GetStatisOfficialProductSumResponse struct {
	OfficialProductSum []*GetStatisOfficialProductSum `protobuf:"bytes,1,rep,name=OfficialProductSum,json=officialProductSum,proto3" json:"officialProductSum,omitempty"`
	DataCount          int32                          `protobuf:"varint,2,opt,name=DataCount,json=dataCount,proto3" json:"dataCount,omitempty"`
}

type GetStatisOfficialProductSum struct {
	OfficialProductId   int32  `protobuf:"varint,1,opt,name=official_product_id,json=officialProductId,proto3" json:"officialProductId,omitempty"`
	OfficialProductName string `protobuf:"bytes,2,opt,name=official_product_name,json=officialProductName,proto3" json:"officialProductName,omitempty"`
	CurrentNum          int32  `protobuf:"varint,3,opt,name=current_num,json=currentNum,proto3" json:"currentNum,omitempty"`
	HistoryOneNum       int32  `protobuf:"varint,4,opt,name=history_one_num,json=historyOneNum,proto3" json:"historyOneNum,omitempty"`
	HistoryTwoNum       int32  `protobuf:"varint,5,opt,name=history_two_num,json=historyTwoNum,proto3" json:"historyTwoNum,omitempty"`
	HistoryOneDiff      int32  `protobuf:"varint,6,opt,name=history_one_diff,json=historyOneDiff,proto3" json:"historyOneDiff,omitempty"`
	HistoryTwoDiff      int32  `protobuf:"varint,7,opt,name=history_two_diff,json=historyTwoDiff,proto3" json:"historyTwoDiff,omitempty"`
}

// GetStatisOfficialProductSumApi 销量同比分析
func GetStatisOfficialProductSumApi(param *GetStatisOfficialProductSumRequest) (*GetStatisOfficialProductSumResponse, error) {
	url := "/dataanalytics/statisOfficialProduct"
	var res GetStatisOfficialProductSumResponse
	if err := request(url, param, &res, ""); err != nil {
		return nil, err
	}
	return &res, nil
}

type GetStatisOfficialProductSumDeclineResponse struct {
	OfficialProductSumDecline []*GetStatisOfficialProductSumDecline `protobuf:"bytes,1,rep,name=official_product_sum_decline,json=officialProductSumDecline,proto3" json:"officialProductSumDecline,omitempty"`
	DataCount                 int32                                 `protobuf:"varint,2,opt,name=data_count,json=dataCount,proto3" json:"dataCount,omitempty"`
}

type GetStatisOfficialProductSumDecline struct {
	ResellerId          int32  `protobuf:"varint,1,opt,name=reseller_id,json=resellerId,proto3" json:"resellerId,omitempty"`
	OfficialProductId   int32  `protobuf:"varint,2,opt,name=official_product_id,json=officialProductId,proto3" json:"officialProductId,omitempty"`
	OfficialProductName string `protobuf:"bytes,3,opt,name=official_product_name,json=officialProductName,proto3" json:"officialProductName,omitempty"`
	ResellerName        string `protobuf:"bytes,4,opt,name=reseller_name,json=resellerName,proto3" json:"resellerName,omitempty"`
	CurrentNum          int32  `protobuf:"varint,5,opt,name=current_num,json=currentNum,proto3" json:"currentNum,omitempty"`
	HistoryOneNum       int32  `protobuf:"varint,6,opt,name=history_one_num,json=historyOneNum,proto3" json:"historyOneNum,omitempty"`
	HistoryTwoNum       int32  `protobuf:"varint,7,opt,name=history_two_num,json=historyTwoNum,proto3" json:"historyTwoNum,omitempty"`
	HistoryOneDiff      int32  `protobuf:"varint,8,opt,name=history_one_diff,json=historyOneDiff,proto3" json:"historyOneDiff,omitempty"`
	HistoryTwoDiff      int32  `protobuf:"varint,9,opt,name=history_two_diff,json=historyTwoDiff,proto3" json:"historyTwoDiff,omitempty"`
}

// GetStatisOfficialProductSumDeclineApi 销量同比分析
func GetStatisOfficialProductSumDeclineApi(param *GetStatisOfficialProductSumRequest) (*GetStatisOfficialProductSumDeclineResponse, error) {
	url := "/dataanalytics/statisOfficialProductDecline"
	var res GetStatisOfficialProductSumDeclineResponse
	if err := request(url, param, &res, ""); err != nil {
		return nil, err
	}
	return &res, nil
}

type resCode struct {
	Code  int             `json:"code"`
	Data  json.RawMessage `json:"data"`
	Error string          `json:"error"`
}

type GetStatisFilterOfficialProductRequest struct {
	OfficialProductId int32 `protobuf:"varint,1,opt,name=official_product_id,json=officialProductId,proto3" json:"official_product_id,omitempty"`
}

type GetStatisFilterOfficialProductResponse struct {
	List []*StatisFilterOfficialProductResponse `protobuf:"bytes,1,rep,name=list,proto3" json:"list,omitempty"`
}

type StatisFilterOfficialProductResponse struct {
	OfficialProductId   int32  `protobuf:"varint,1,opt,name=official_product_id,json=officialProductId,proto3" json:"OfficialProductId,omitempty"`
	OfficialProductName string `protobuf:"bytes,2,opt,name=official_product_name,json=officialProductName,proto3" json:"OfficialProductName,omitempty"`
}

// GetStatisFilterOfficialProductApi 官方商品列表
func GetStatisFilterOfficialProductApi(param *GetStatisFilterOfficialProductRequest) (*GetStatisFilterOfficialProductResponse, error) {
	url := "/dataanalytics/statisFilterOfficialProduct"
	var res GetStatisFilterOfficialProductResponse
	if err := request(url, param, &res, ""); err != nil {
		return nil, err
	}
	return &res, nil
}

//type GetManagerAndDefaultLossReasonRequest struct {
//	ResellerId int32 ` json:"reseller_id"`
//	GoodsIds   int32 ` json:"reseller_id"`
//}

type GetManagerAndDefaultLossReasonRequest struct {
	Param map[int32]map[string][]int32 ` json:"param"`
}

type GetManagerAndDefaultLossReasonResponse struct {
	Res []*GetManagerAndDefaultLossReasonResponseList `json:"res,omitempty"`
}

type GetManagerAndDefaultLossReasonResponseList struct {
	ResellerInfo *GetManagerAndDefaultLossReasonResponse_ResellerInfo  `json:"resellerInfo,omitempty"`
	ProductList  []*GetManagerAndDefaultLossReasonResponse_ProductList `json:"productList,omitempty"`
}

type GetManagerAndDefaultLossReasonResponse_ResellerInfo struct {
	ResellerId    int32  `json:"resellerId,omitempty"`
	AfterSaleName string `json:"AfterSaleName,omitempty"`
}

type GetManagerAndDefaultLossReasonResponse_ProductList struct {
	ProductId  int32  `json:"productId,omitempty"`
	LossReason string `json:"lossReason,omitempty"`
}

//return []*GetManagerAndDefaultLossReasonResponseList{
//{
//ResellerInfo: &GetManagerAndDefaultLossReasonResponse_ResellerInfo{
//ResellerId:    25009,
//AfterSaleName: "张三",
//},
//ProductList: []*GetManagerAndDefaultLossReasonResponse_ProductList{
//{
//ProductId:  129,
//LossReason: "小米钱包h5-QQ音乐绿钻季卡原因",
//},
//{
//ProductId:  2218,
//LossReason: "小米钱包h5-百度网盘新vip会员月卡原因",
//},
//{
//ProductId:  3226,
//LossReason: "小米钱包h5-腾讯视频月卡-小米钱包2024原因",
//},
//{
//ProductId:  3364,
//LossReason: "小米钱包h5-腾讯视频月卡-0元直充原因",
//},
//},
//},
//}, nil

// GetStatisFilterOfficialProductApi 官方商品列表
func GetManagerAndDefaultLossReasonApi(param *GetManagerAndDefaultLossReasonRequest, token string, reqUrl string) ([]*GetManagerAndDefaultLossReasonResponseList, error) {

	reqParam, err := util.StructToMap(param)
	if err != nil {
		return nil, err
	}

	req := &l_request.Request{
		Url:    reqUrl,
		Method: http.MethodPost,
		Json:   reqParam,
		Headers: map[string]string{
			"Authorization": fmt.Sprintf("Bearer %s", token),
		},
	}
	log.Debug(pkg.JsonStringIgonErr(req.Headers))
	res, err := req.Send()
	if err != nil {
		log.Debug(err.Error())
		return nil, err
	}
	log.Debug(string(res.Content))
	if res.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("request failed, status code: %d,resion: %s", res.StatusCode, res.Reason)
	}
	var code resCode
	if err = json.Unmarshal(res.Content, &code); err != nil {
		return nil, fmt.Errorf("返回结构异常：%s", string(res.Content))
	}
	var resData []*GetManagerAndDefaultLossReasonResponseList
	if err = json.Unmarshal(code.Data, &resData); err != nil {
		return nil, fmt.Errorf("返回数据异常：%s", string(res.Content))
	}
	return resData, nil
}

func request(url string, reqData interface{}, resData interface{}, token string) error {
	requestSchema := Base
	if len(token) > 0 {
		requestSchema = AuthUrl
	}
	reqParam, err := pkg.StructToURLValues(reqData)
	if err != nil {
		return err
	}

	req := &l_request.Request{
		Url:    FormatPHPURL(requestSchema+url, reqParam),
		Method: http.MethodGet,
	}
	if len(token) > 0 {
		req.Headers = map[string]string{
			"Authorization": fmt.Sprintf("Bearer %s", token),
		}
	}
	res, err := req.Send()
	if err != nil {
		return err
	}
	if res.StatusCode != http.StatusOK {
		return fmt.Errorf("request failed, status code: %d,resion: %s", res.StatusCode, res.Reason)
	}
	var code resCode
	if err = json.Unmarshal(res.Content, &code); err != nil {
		return fmt.Errorf("返回结构异常：%s", string(res.Content))
	}
	if code.Code != 200 {
		return fmt.Errorf("返回状态异常：%s", string(code.Error))
	}
	if err = json.Unmarshal(code.Data, resData); err != nil {
		return fmt.Errorf("返回数据异常：%s", string(res.Content))
	}
	return nil
}

// FormatPHPURL 将 url.Values 格式化为 PHP 风格的 URL
// 输入：基础URL和url.Values参数
// 输出：PHP风格的URL字符串
func FormatPHPURL(baseURL string, values url.Values) string {
	if values == nil || len(values) == 0 {
		return baseURL
	}

	var queryParts []string

	// 遍历所有参数
	for key, paramValues := range values {
		// 检查这个key是否有多个值（数组参数）
		if len(paramValues) > 1 {
			// 多值参数，使用PHP数组格式：key[]=value
			for _, value := range paramValues {
				if value != "" {
					// 编码值
					encodedValue := url.QueryEscape(value)
					// 使用PHP数组格式
					queryParts = append(queryParts, fmt.Sprintf("%s[]=%s", key, encodedValue))
				}
			}
		} else if len(paramValues) == 1 && paramValues[0] != "" {
			// 单值参数
			encodedValue := url.QueryEscape(paramValues[0])
			queryParts = append(queryParts, fmt.Sprintf("%s=%s", key, encodedValue))
		}
	}

	if len(queryParts) == 0 {
		return baseURL
	}

	// 构建查询字符串
	query := strings.Join(queryParts, "&")

	// 转换为PHP风格：解码中括号和冒号
	query = strings.ReplaceAll(query, "%5B", "[")
	query = strings.ReplaceAll(query, "%5D", "]")
	query = strings.ReplaceAll(query, "%3A", ":")

	// 注意：保留空格为+号（这是PHP的常见格式）
	// query = strings.ReplaceAll(query, "+", "%20") // 如果需要将+转为%20，可以取消注释

	return baseURL + "?" + query
}
