package tmall

import (
	"context"
	"errors"
	"kami/utility/integration/tmall"
	"time"
	"topsdk"
	"topsdk/ability648"
	"topsdk/ability648/domain"
	"topsdk/ability648/request"
	"topsdk/ability648/response"
	"topsdk/util"

	"github.com/duke-git/lancet/v2/pointer"
	"github.com/duke-git/lancet/v2/retry"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/util/gconv"
)

// TBMallTradeGet 获取订单信息
// tId 订单Id
func (c *InnerClient) TBMallTradeGet(ctx context.Context, tid int) (res *domain.TaobaoTradeGetTrade, err error) {
	cfg, sessionInfo, err := tmall.GetCfgAndSession(ctx)
	res = &domain.TaobaoTradeGetTrade{}
	if err != nil {
		return
	}
	result := new(response.TaobaoTradeGetResponse)
	if err3 := retry.Retry(func() error {
		cli := topsdk.NewDefaultTopClient(cfg.AppKey, cfg.AppSecret, cfg.Gateway, 1000*6*5, 1000*6*5)
		var err2 error
		result, err2 = ability648.NewAbility648(&cli).TaobaoTradeGet(&request.TaobaoTradeGetRequest{
			Tid:    gconv.PtrInt64(tid),
			Fields: &[]string{"tid", "buyer_nick", "type", "status", "buyer_memo", "payment", "end_time", "created", "seller_rate", "buyer_rate", "total_fee", "pay_time", "end_time", "modified", "consign_time", "buyer_memo", "seller_memo", "alipay_no", "buyer_message"},
		}, sessionInfo.AccessToken)
		if pointer.IsNil(result) || result.RequestId == "" || err2 != nil {
			glog.Error(ctx, "淘宝订单获取错误, 淘宝订单号：", tid)
			return errors.Join(err2, gerror.New("淘宝授权错误"))
		}
		return nil
	}, retry.Context(ctx)); err3 != nil {
		return nil, errors.Join(err3, gerror.New("天猫订单获取错误"))
	}
	return &result.Trade, nil
}

// GetTradeGetListByCreatedTime 获取订单列表
func (c *InnerClient) GetTradeGetListByCreatedTime(ctx context.Context, tradeStatus tmall.EnumTradeStatus, duration time.Duration) (tradeList []domain.TaobaoTradesSoldGetTrade, err error) {
	tradeList = make([]domain.TaobaoTradesSoldGetTrade, 0)
	cfg, sessionInfo, err := tmall.GetCfgAndSession(ctx)
	if err != nil {
		return
	}
	cli := topsdk.NewDefaultTopClient(cfg.AppKey, cfg.AppSecret, cfg.Gateway, 1000*6*5, 1000*6*5)
	startCreated := util.LocalTime(time.Now().Add(-duration))
	var pageNo int64 = 1
	hasNext := true
	for hasNext {
		result := new(response.TaobaoTradesSoldGetResponse)
		if err2 := retry.Retry(func() error {
			result, err = ability648.NewAbility648(&cli).TaobaoTradesSoldGet(&request.TaobaoTradesSoldGetRequest{
				StartCreated: &startCreated,
				Fields:       &[]string{"tid", "type", "status", "payment", "oid", "orders"},
				PageNo:       &pageNo,
				Status:       gconv.PtrString(tradeStatus),
				PageSize:     gconv.PtrInt64(100),
				UseHasNext:   gconv.PtrBool(true),
			}, sessionInfo.AccessToken)
			if pointer.IsNil(result) || result.RequestId == "" || err != nil {
				err = gerror.Wrap(err, "淘宝授权错误")
			}
			return err
		}, retry.Context(ctx), retry.RetryTimes(5)); err2 != nil {
			return tradeList, errors.Join(err, gerror.New("淘宝授权错误"))
		}
		hasNext = result.HasNext
		pageNo++ // 页码+1
		tradeList = append(tradeList, result.Trades...)
	}
	return tradeList, err
}

// GetTradeGetListByCreatedTimeAndRateStatus 获取订单列表
func (c *InnerClient) GetTradeGetListByCreatedTimeAndRateStatus(ctx context.Context, tradeStatus tmall.EnumTradeStatus, rateStatus tmall.EnumRateStatus, duration time.Duration) (tradeList []domain.TaobaoTradesSoldGetTrade, err error) {
	tradeList = make([]domain.TaobaoTradesSoldGetTrade, 0)
	cfg, sessionInfo, err := tmall.GetCfgAndSession(ctx)
	if err != nil {
		return
	}
	cli := topsdk.NewDefaultTopClient(cfg.AppKey, cfg.AppSecret, cfg.Gateway, 1000*60*5, 1000*60*5)
	startCreated := util.LocalTime(time.Now().Add(-duration))
	var pageNo int64 = 1
	hasNext := true
	for hasNext {
		result := new(response.TaobaoTradesSoldGetResponse)
		if err2 := retry.Retry(func() error {
			result, err = ability648.NewAbility648(&cli).TaobaoTradesSoldGet(&request.TaobaoTradesSoldGetRequest{
				StartCreated: &startCreated,
				Fields:       &[]string{"tid", "type", "status", "payment", "oid", "orders"},
				PageNo:       &pageNo,
				RateStatus:   gconv.PtrString(rateStatus),
				Status:       gconv.PtrString(tradeStatus),
				PageSize:     gconv.PtrInt64(100),
				UseHasNext:   gconv.PtrBool(true),
			}, sessionInfo.AccessToken)
			if pointer.IsNil(result) || result.RequestId == "" || err != nil {
				err = gerror.Wrap(err, "淘宝授权错误")
			}
			return err
		}, retry.Context(ctx), retry.RetryTimes(5)); err2 != nil {
			return tradeList, errors.Join(err, gerror.New("淘宝授权错误"))
		}
		hasNext = result.HasNext
		pageNo++ // 页码+1
		tradeList = append(tradeList, result.Trades...)
	}
	return tradeList, err
}

// VirtualDelivery 虚拟发货
func (c *InnerClient) VirtualDelivery(ctx context.Context, tid int64) (isSucceed bool, err error) {
	isSucceed = false
	cfg, sessionInfo, err := tmall.GetCfgAndSession(ctx)
	if err != nil {
		return
	}
	var result *response.TaobaoLogisticsDummySendResponse
	cli := topsdk.NewDefaultTopClient(cfg.AppKey, cfg.AppSecret, cfg.Gateway, 1000*60*5, 1000*60*5)
	if err2 := retry.Retry(func() error {
		result, err = ability648.NewAbility648(&cli).TaobaoLogisticsDummySend(&request.TaobaoLogisticsDummySendRequest{
			Tid: &tid,
		}, sessionInfo.AccessToken)
		if pointer.IsNil(result) || result.RequestId == "" || err != nil {
			err = errors.Join(err, gerror.New("淘宝授权错误"))
		}
		return err
	}, retry.Context(ctx), retry.RetryTimes(3)); err2 != nil {
		return isSucceed, errors.Join(err, gerror.New("淘宝授权错误"))
	}
	isSucceed = *result.Shipping.IsSuccess
	return
}

// TradeRatesGet 搜索评价数据
func (c *InnerClient) TradeRatesGet(ctx context.Context, tid int64) (tradeRate []domain.TaobaoTraderatesGetResults, err error) {
	tradeRate = make([]domain.TaobaoTraderatesGetResults, 10)
	cfg, sessionInfo, err := tmall.GetCfgAndSession(ctx)
	if err != nil {
		return
	}
	var result *response.TaobaoTraderatesGetResponse
	if err2 := retry.Retry(func() error {
		cli := topsdk.NewDefaultTopClient(cfg.AppKey, cfg.AppSecret, cfg.Gateway, 1000*60*5, 1000*60*5)
		result, err = ability648.NewAbility648(&cli).TaobaoTraderatesGet(&request.TaobaoTraderatesGetRequest{
			RateType: gconv.PtrString("give"),
			Role:     gconv.PtrString("buyer"),
			Tid:      &tid,
			PageSize: gconv.PtrInt64(150),
		}, sessionInfo.AccessToken)
		if pointer.IsNil(result) || result.RequestId == "" || err != nil {
			err = errors.Join(err, gerror.New("淘宝授权错误"))
		}
		return err
	}, retry.Context(ctx), retry.RetryTimes(5)); err2 != nil {
		return tradeRate, errors.Join(err, gerror.New("淘宝授权错误"))
	}
	tradeRate = result.TradeRates
	return
}
