package service

import (
	"context"
	"fmt"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/redis/go-redis/v9"
	"time"
	"voucher/internal/biz/vo"
)

func (s *VoucherService) CronWarningBudget(ctx context.Context) error {

	c, ok := s.bc.Cron.CommandMap["warningBudget"]

	if !ok {
		log.Error("warningBudget定时任务未找到")
		return nil
	}

	if !c.IsOpen {
		log.Warn("warningBudget定时任务未开启")
		return nil
	}

	if len(c.Command) == 0 {
		log.Error("warningBudget定时任务 command is empty")
		return nil
	}

	cv := vo.WarningBudgetCron.BuildCache([]string{"YJ"})

	cacheValue, err2 := s.rdb.Rdb.Get(ctx, cv.Key).Result()

	if err2 != nil && err2 != redis.Nil {
		return fmt.Errorf(fmt.Sprintf("warningBudget定时任务,获取redis缓存%s异常:%v", cv.Key, err2))
	}

	if len(cacheValue) > 0 {
		log.Warnf("warningBudget定时任务,获取redis缓存存在,本台服务不做执行")
		return nil
	}

	if err := s.rdb.Rdb.Set(ctx, cv.Key, time.Now().Format(time.DateTime), cv.TTL).Err(); err != nil {
		return fmt.Errorf(fmt.Sprintf("warningBudget定时任务 设置redis缓存%s异常:%v", cv.Key, err))
	}

	log.Warnf("warningBudget定时任务,获取redis缓存不存在,本台服务执行")

	return s.cron.AddFunc(c.Command, func() {

		s.VoucherBiz.CronWarningBudget(ctx)

	})

}
