package biz

import (
	"context"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"time"
	v1 "voucher/api/v1"
	"voucher/internal/biz/bo"
	"voucher/internal/biz/vo"
	"voucher/internal/pkg/lock"
)

func (v *VoucherBiz) CmbQuery(ctx context.Context, orderNo string) (resp *v1.CmbQueryReply, err error) {

	c := vo.CmbQueryLockKey.BuildCache([]string{orderNo})

	err = lock.NewMutex(v.rdb.Rdb, c.TTL).Lock(ctx, c.Key, func(ctx context.Context) error {

		order, err3 := v.OrderRepo.GetByOrderNo(ctx, orderNo)
		if err3 != nil {
			return err3
		}

		if err = v.Query(ctx, order); err != nil {
			return err
		}

		status, err3 := order.Status.GetCmbStatusText()
		if err3 != nil {
			return err3
		}

		resp = &v1.CmbQueryReply{
			Ticket:    order.OrderNo,
			Status:    status.GetValue(),
			TransDate: time.Now().Format("20060102150405"),
			OrgNo:     v.bc.Cmb.OrgNo,
			Ext:       "",
		}

		return nil
	})

	return
}

func (v *VoucherBiz) Query(ctx context.Context, order *bo.OrderBo) error {

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

	if order.Status == status {
		log.Warnf("券状态未改变:%s，忽略不处理,orderNo:%s", order.Status.GetText(), order.OrderNo)
		return nil
	}

	if err = v.UpdateOrderStatus(ctx, order.ID, status); err != nil {
		return err
	}

	order.Status = status

	return nil
}

func (v *VoucherBiz) QueryOrder(ctx context.Context, orderNo string) (string, error) {

	order, err3 := v.OrderRepo.GetByOrderNo(ctx, orderNo)
	if err3 != nil {
		return "", err3
	}

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

	return fmt.Sprintf("orderNo:%s,订单状态:%s,微信查询返回状态:%s", orderNo, order.Status.GetText(), status.GetText()), nil
}
