package biz

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/transport/http"
	"github.com/nacos-group/nacos-sdk-go/util"
	"time"
	"voucher/internal/biz/bo"
	"voucher/internal/biz/do"
)

func (this *VoucherBiz) uid(_ context.Context, msg string) string {
	return util.Md5(msg)
}

func (this *VoucherBiz) PushWechatQuery(ctx http.Context, req *do.WechatQuery) error {

	if req.ProductNo != "" {
		_, err := this.ProductRepo.GetByProductNo(ctx, req.ProductNo)
		if err != nil {
			return err
		}
	}

	queue := this.bc.RdsMQ.GetWechatQuery()
	if queue == nil {
		return fmt.Errorf("队列不存在")
	}

	msg, err := json.Marshal(req)
	if err != nil {
		return err
	}

	strMsg := string(msg)

	uid := this.uid(ctx, strMsg)
	if this.Get(uid) {
		return fmt.Errorf("此台服务队列正在处理中,key:%s,ip:%s", uid, ctx.Header().Get("X-Forwarded-For"))
	}

	this.Add(uid)

	_, err = this.rdb.Rdb.RPush(ctx, queue.Name, strMsg).Result()
	if err != nil {
		this.Remove(uid)
		return fmt.Errorf("添加到队列失败:%v", err)
	}

	return nil
}

func (this *VoucherBiz) WechatQuery(ctx context.Context, msg string) error {

	defer this.Remove(this.uid(ctx, msg))

	var req *do.WechatQuery

	if err := json.Unmarshal([]byte(msg), &req); err != nil {
		return err
	}

	start := time.Now()
	startStr := time.Now().String()

	log.Warnf("微信券查询处理开始:%s,msg:%s", startStr, msg)
	fmt.Printf("微信券查询处理开始:%s,msg:%s", startStr, msg)

	n := 0
	num := 0
	notifyNum := 0
	err := this.OrderRepo.FinSucByStockIdInBatches(ctx, req, func(ctx context.Context, rows []*bo.OrderBo) error {

		n += 1
		for _, order := range rows {

			num += 1
			if err := this.wechatQuery(ctx, order, &notifyNum); err != nil {
				log.Errorf("微信查询券订单状态发生错误,msg:%s,orderNo:%s,couponId:%s,appId:%s,openId:%s,stockId:%s,err:%v",
					msg, order.OrderNo, order.VoucherNo, order.AppID, order.Account, order.BatchNo, err)
			}

		}

		groupTime := time.Now()
		log.Warnf("微信券查询处理第:%d组,已执行条数:%d,核销通知条数:%d,执行开始时间:%s，当前时间:%s,已耗时:%s", n, num, notifyNum, startStr, groupTime.String(), groupTime.Sub(start).String())

		return nil
	})

	endTime := time.Now()
	log.Warnf("微信券查询处理耗时:%s,结束时间:%s,处理%d组,处理%d单,核销通知条数:%d,msg:%s", endTime.Sub(start).String(), endTime.String(), n, num, notifyNum, msg)
	fmt.Printf("微信券查询处理耗时:%s,结束时间%s,处理%d组,处理%d单,核销通知条数:%d,msg:%s", endTime.Sub(start).String(), endTime.String(), n, num, notifyNum, msg)

	return err
}

func (this *VoucherBiz) wechatQuery(ctx context.Context, order *bo.OrderBo, notifyNum *int) error {

	status, err := this.WechatCpnRepo.Query(ctx, order)
	if err != nil {
		return err
	}

	if status.IsUse() {
		return this.queryUsed(ctx, order, notifyNum)
	} else if status.IsExpired() {
		return this.expired(ctx, order)
	}

	return nil
}

func (this *VoucherBiz) queryUsed(ctx context.Context, order *bo.OrderBo, notifyNum *int) error {

	*notifyNum += 1

	if order.Status.IsUse() {
		return this.notify(ctx, order)
	}

	if err := this.OrderRepo.Used(ctx, order.ID); err != nil {
		return err
	}

	return this.notify(ctx, order)
}
