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

import com.bonus.canteen.core.common.utils.RedisUtil;
import com.bonus.canteen.core.menu.service.IMenuRecipeService;
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 MenuRecipeTask {
   private static final Logger log = LoggerFactory.getLogger(MenuRecipeTask.class);
   @Autowired
   private IMenuRecipeService menuRecipeService;

   @Autowired
   private TransactionTemplate transactionTemplate;

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

}
