package biz

import (
	"context"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"time"
	v1 "voucher/api/v1"
	"voucher/internal/biz/bo"
	"voucher/internal/biz/vo"
	"voucher/internal/pkg/lock"
)

func (v *VoucherBiz) CmbOrder(ctx context.Context, req *bo.OrderCreateReqBo) (orderNo string, err error) {

	err = lock.NewMutex(v.rdb.Rdb, time.Second*30).Lock(ctx, fmt.Sprintf("cmb_order_%s", req.OutBizNo), func(ctx context.Context) error {

		order, err := v.OrderRepo.GetByOutBizNo(ctx, req.OutBizNo)

		if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
			return err
		}

		if order != nil {
			orderNo = order.OrderNo
			return nil
		}

		product, err := v.ProductRepo.GetByPNO(ctx, req.ProductNo)
		if err != nil {
			return err
		}

		if !product.Channel.IsWeChat() {
			return fmt.Errorf("只支持微信")
		}

		if orderNo, err = v.Cmb.Order(ctx, req, product); err != nil {
			return err
		}

		return v.PushOrderMQ(ctx, orderNo)
	})

	return
}

func (v *VoucherBiz) CmbProductQuery(ctx context.Context, productNo string) (reps *v1.CmbQueryProductReply, err error) {

	err = lock.NewMutex(v.rdb.Rdb, time.Second*30).Lock(ctx, fmt.Sprintf("cmb_product_query_%s", productNo), func(ctx context.Context) error {

		product, err := v.ProductRepo.GetByPNO(ctx, productNo)
		if err != nil {
			return err
		}

		if !product.Channel.IsWeChat() {
			return fmt.Errorf("只支持微信")
		}

		wechatResp, err := v.WechatCpnRepo.QueryProduct(ctx, product.BatchNo, product.MchId)
		if err != nil {
			return err
		}

		reps = &v1.CmbQueryProductReply{
			ActivityName: product.Name,
			ActivityId:   product.ProductNo,

			StartTime: *wechatResp.AvailableBeginTime,
			EndTime:   *wechatResp.AvailableEndTime,
			Detail:    *wechatResp.Description,

			Amount:    "",
			MinAmount: "",

			AvailableStock: "",
			AvailableType:  "",
			AvailableDays:  "", // 动态有效期天数
		}

		reps.Amount = fmt.Sprintf("%d", *wechatResp.StockUseRule.FixedNormalCoupon.CouponAmount)
		reps.MinAmount = fmt.Sprintf("%d", *wechatResp.StockUseRule.FixedNormalCoupon.TransactionMinimum)

		availableStock := *wechatResp.StockUseRule.MaxCoupons - *wechatResp.DistributedCoupons
		reps.AvailableStock = fmt.Sprintf("%d", availableStock)

		reps.AvailableType = vo.CmbAvailableTypeFixed.GetValue()
		reps.AvailableDays = fmt.Sprintf("%d", *wechatResp.StockUseRule.FixedNormalCoupon.CouponAmount)

		return nil
	})

	return
}
