package initialize

import (
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/robfig/cron/v3"
	"github.com/towgo/towgo/errors/tcode"
	"sync"
	g "tgk-touch/internal/global"
	m9zTtyApi "tgk-touch/internal/module/m9zTtyApi"
)

func timer() {
	go func() {
		AddTaskByFunc("ScanM9z", "ScanM9z", "@every 10m", m9zTtyApi.ScanM9z)

	}()
}

var cronTaskNameMap = map[string]cron.EntryID{}
var cronLock = sync.Mutex{}

func AddTaskByFunc(cronName string, taskName string, spec string, task func()) {
	cronLock.Lock()
	defer cronLock.Unlock()
	cronTaskName := cronName + "-" + taskName
	_, ok := cronTaskNameMap[cronTaskName]
	if ok {
		panic(gerror.New("定时任务名称重复 " + cronTaskName))
	}
	var option []cron.Option
	option = append(option, cron.WithSeconds(), cron.WithChain(cron.SkipIfStillRunning(cron.DefaultLogger)))
	cronEnterId, err := g.Timer().AddTaskByFunc(cronName, spec, func() {
		defer func() {
			if exception := recover(); exception != nil {
				if errv, ok := exception.(error); ok {
					g.GVA_LOG.Sugar().Errorf("corn recovered panic err task [%s] sepc [%s] err:%+v \n", taskName, spec, gerror.NewCodef(tcode.CodeInternalPanic, "%+v", errv))
				}
			}
		}()

		task()

	}, taskName, option...)
	if err != nil {
		g.Log().Panicf("add timer error: [%s]", err.Error())
	}
	cronTaskNameMap[cronTaskName] = cronEnterId
	g.GVA_LOG.Sugar().Infof("add timer success: cronName [%s] task [%s] sepc [%s]", cronName, taskName, spec)
}
