package service

import (
	"github.com/robfig/cron/v3"
	log "github.com/sirupsen/logrus"
	"time"
	"youngee_b_api/db"
)

func AutoTask() error {
	c := cron.New(cron.WithSeconds())
	spec := "0 */30 * * * ?" //cron表达式，每半小时执行一次
	//spec := "0 */1 * * * ?" //cron表达式，每1分钟一次
	//spec := "*/10 * * * * ?" //cron表达式，每10秒一次
	_, err1 := c.AddFunc(spec, AutoTaskUpdateStatus)
	if err1 != nil {
		log.Println("service [AutoTaskUpdateStatus] error:", err1)
		return err1
	}
	_, err2 := c.AddFunc("@midnight", AutoTaskUpdateApplyTimes)
	if err2 != nil {
		log.Println("service [AutoTaskUpdateApplyTimes] error:", err2)
		return err2
	}
	_, err3 := c.AddFunc(spec, AutoTaskCompleteSelection)
	if err3 != nil {
		log.Println("service [AutoTaskCompleteSecTask] error:", err2)
		return err3
	}
	c.Start()
	return nil
}

func AutoTaskUpdateStatus() {
	err := db.AutoUpdateStatus()
	log.Println("AutoTaskUpdateStatus is running ,Time :", time.Now())
	if err != nil {
		log.Println("AutoTaskUpdateStatus error : ", err)
	}
}

func AutoTaskUpdateApplyTimes() {
	err := db.AutoUpdateApplyTimes()
	log.Println("AutoUpdateApplyTimes is running ,Time :", time.Now())
	if err != nil {
		log.Println("AutoUpdateApplyTimes error : ", err)
	}
}

func AutoTaskCompleteSelection() {
	err := db.AutoCompleteSelection()
	log.Println("AutoUpdateApplyTimes is running ,Time :", time.Now())
	if err != nil {
		log.Println("AutoUpdateApplyTimes error : ", err)
	}
}
