package crontab

import (
	"github.com/robfig/cron/v3"
	"github.com/sirupsen/logrus"
	"main/database"
	"main/model"
)

var MyCron *cron.Cron

func InitAllCron() {
	MyCron = cron.New(cron.WithSeconds())
	MyCron.Start()
	db := database.GetInstance().GetMysqlDb()
	var runningCron []model.RunningCrontab
	if err := db.Where("deleted_at is null").Delete(&runningCron).Error; err != nil {
		logrus.Errorln("sql执行失败：", err)
		return
	}
}

func UpdateCronDb(id int, name string, status bool) {
	db := database.GetInstance().GetMysqlDb()
	var runningCron model.RunningCrontab
	if status {
		if err := db.Create(&model.RunningCrontab{
			Name:   name,
			CronId: id,
		}).Error; err != nil {
			logrus.Errorln("sql执行失败：", err)
			return
		}
	} else {
		if err := db.Delete(&runningCron, "cron_id = ?", id).Error; err != nil {
			logrus.Errorln("sql执行失败：", err)
			return
		}
	}
}
