package com.bonus.canteen.core.cook.task;

import com.bonus.canteen.core.common.utils.RedisUtil;
import com.bonus.canteen.core.cook.service.ICookRecipeService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;
import java.time.LocalDateTime;

@Component
public class CookRecipeTask {
   private static final Logger logger = LoggerFactory.getLogger(CookRecipeTask.class);
   @Autowired
   private ICookRecipeService cookRecipeService;

   @Autowired
   private TransactionTemplate transactionTemplate;

   //@XxlJob("cookRecipeHandler")
   @Scheduled(fixedDelay = 12*60*60*1000)
   public void cookRecipeHandler() {
      boolean cookRecipeHandler = RedisUtil.setNx("cookRecipeHandler", "1", 3600);
      logger.info("cookRecipeHandler="+cookRecipeHandler);
      if (cookRecipeHandler) {
         transactionTemplate.execute(status -> {
            try {
               // 业务代码
               logger.info("[定时生成菜谱]开始：{},{}", status, LocalDateTime.now());
               this.cookRecipeService.generateRecipe();
               logger.info("[定时生成菜谱]结束：{},{}", status, LocalDateTime.now());
               return null;
            } catch (Exception e) {
               status.setRollbackOnly(); // 标记回滚
               throw e;
            }
         });
      }
   }
}
