package service

import (
	"encoding/json"
	"fmt"
	"github.com/go-kratos/kratos/v2/transport/http"
	"io"
	http2 "net/http"
	"strconv"
	"voucher/internal/biz/do"
)

func (this *CmbService) NotifyRetry(ctx http.Context) error {
	id := ctx.Vars().Get("id")
	if id == "" {
		return fmt.Errorf("id is empty")
	}

	orderNotifyId, err := strconv.ParseUint(id, 10, 64)
	if err != nil {
		return err
	}

	return this.VoucherBiz.PushNotifyRetryDelayMQ(ctx, 1, orderNotifyId)
}

func (this *CmbService) QueryOrder(ctx http.Context) error {

	orderNo := ctx.Vars().Get("order_no")
	if orderNo == "" {
		return fmt.Errorf("orderNo is empty")
	}

	str, err := this.VoucherBiz.QueryOrder(ctx, orderNo)
	if err != nil {
		return err
	}

	return ctx.JSON(http2.StatusOK, map[string]interface{}{
		"data": str,
	})
}

func (this *CmbService) PushWechatQuery(ctx http.Context) error {

	bodyBytes, err := io.ReadAll(ctx.Request().Body)
	if err != nil {
		return err
	}

	var req *do.WechatQuery
	if err = json.Unmarshal(bodyBytes, &req); err != nil {
		return err
	}

	if req == nil {
		return fmt.Errorf("req is empty")
	}

	if req.StartTime == "" || req.EndTime == "" {
		return fmt.Errorf("start_time or end_time is empty")
	}

	if err = this.VoucherBiz.PushWechatQuery(ctx, req); err != nil {
		return err
	}

	return ctx.JSON(http2.StatusOK, map[string]interface{}{
		"data": req,
	})
}

func (this *CmbService) TimeSliceQueryPush(ctx http.Context) error {

	bodyBytes, err := io.ReadAll(ctx.Request().Body)
	if err != nil {
		return err
	}

	var req *do.RdsWechatQuery
	if err = json.Unmarshal(bodyBytes, &req); err != nil {
		return err
	}

	if req == nil {
		return fmt.Errorf("req is empty")
	}

	if req.StartTime == "" || req.EndTime == "" {
		return fmt.Errorf("start_time or end_time is empty")
	}

	if req.GoNum > 10 {
		return fmt.Errorf("协程数量不能大于10")
	}

	_, err = this.timeSliceQuery.Push(ctx, req)
	if err != nil {
		return err
	}

	return ctx.JSON(http2.StatusOK, req)
}

func (this *CmbService) PushWechatRetry(ctx http.Context) error {

	productNo := ctx.Vars().Get("product_no")
	if productNo == "" {
		return fmt.Errorf("product_no is empty")
	}

	err := this.VoucherBiz.PushWechatRetry(ctx, productNo)
	if err != nil {
		return err
	}

	return ctx.JSON(http2.StatusOK, map[string]interface{}{
		"data": productNo,
	})
}
