package service

import (
	"context"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"voucher/internal/pkg/rdsmq"
)

func (s *VoucherService) GetWechatQueryConfig() *rdsmq.ConsumeConfig {

	queue := s.bc.RdsMQ.GetWechatQuery()
	if queue == nil {
		return nil
	}

	if !queue.GetIsOpen() {
		log.Warn(fmt.Sprintf("[%s]RdsMQ is not open", queue.Name))
		return nil
	}

	return &rdsmq.ConsumeConfig{
		Rdb:        s.rdb.Rdb,
		QueueName:  queue.Name,
		NumWorkers: queue.NumWorkers,
		WaitTime:   queue.GetWaitTime().AsDuration(),
		RetryNum:   queue.RetryNum,
		Fn:         s.WechatQueryHandle,
		Logger:     s.logHelper,
	}
}

func (s *VoucherService) WechatQueryHandle(ctx context.Context, msg string) error {

	if msg == "" {
		s.logHelper.Errorf("wechat query error: batchNo is empty")
		return nil
	}

	if err := s.VoucherBiz.WechatQuery(ctx, msg); err != nil {
		s.logHelper.Errorf("wechat query error: %v", err)
	}

	return nil
}

func (s *VoucherService) GetWechatTimeSliceQueryConfig() *rdsmq.ConsumeConfig {

	queue := s.bc.RdsMQ.GetWechatTimeSliceQuery()
	if queue == nil {
		return nil
	}

	if !queue.GetIsOpen() {
		log.Warn(fmt.Sprintf("[%s]RdsMQ is not open", queue.Name))
		return nil
	}

	return &rdsmq.ConsumeConfig{
		Rdb:        s.rdb.Rdb,
		QueueName:  queue.Name,
		NumWorkers: queue.NumWorkers,
		WaitTime:   queue.GetWaitTime().AsDuration(),
		RetryNum:   queue.RetryNum,
		Fn:         s.WechatTimeSliceQueryHandle,
		Logger:     s.logHelper,
	}
}

func (s *VoucherService) WechatTimeSliceQueryHandle(ctx context.Context, msg string) error {

	if msg == "" {
		s.logHelper.Errorf("wechat TimeSlice query error: batchNo is empty")
		return nil
	}

	if err := s.timeSliceQuery.Consumer(ctx, msg); err != nil {
		s.logHelper.Errorf("wechat TimeSlice query msg:%s error: %v", msg, err)
	}

	return nil
}

func (s *VoucherService) GetRetryQueryNoticeConfig() *rdsmq.ConsumeConfig {

	return &rdsmq.ConsumeConfig{
		Rdb:        s.rdb.Rdb,
		QueueName:  "retryQueryNotice",
		NumWorkers: 1,
		WaitTime:   30,
		RetryNum:   1,
		Fn:         s.RetryQueryNotice,
		Logger:     s.logHelper,
	}
}

func (s *VoucherService) RetryQueryNotice(ctx context.Context, msg string) error {

	if msg == "" {
		s.logHelper.Errorf("wechat TimeSlice query error: batchNo is empty")
		return nil
	}

	if err := s.timeSliceQuery.RetryQueryNotice(ctx, msg); err != nil {
		s.logHelper.Errorf("retry query notice msg:%s error: %v", msg, err)
	}

	return nil
}
