package task

import (
	"fmt"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/services/alarm_msg"
	"hongze/hongze_yb/utils"
	"os"
	"runtime"
	"sync"
	"time"
)

type TaskFunc func(params ...interface{})

var taskList chan *Executor  //任务列表

var once sync.Once
func GetTaskList() chan *Executor {
	once.Do(func() {
		taskList = make(chan *Executor, 1000)
	})
	return taskList
}

type Executor struct {
	f TaskFunc
	params []interface{}
}

func (e *Executor) Exec()  {       //执行任务
	go func() {
		defer func() {
			if err := recover(); err !=nil {
				stack := ""
				msg := fmt.Sprintf("当前进程pid：%d; 父进程ppid：%d", os.Getpid(), os.Getppid())
				stack += msg + "</br>"
				global.LOG.Critical(msg)
				msg = fmt.Sprintf("The params data is %v", e.params)
				stack += msg + "</br>"
				global.LOG.Critical(msg)
				msg = fmt.Sprintf("Handler crashed with error %v", err)
				stack += msg + "</br>"
				global.LOG.Critical(msg)
				for i := 1; ; i++ {
					_, file, line, ok := runtime.Caller(i)
					if !ok {
						break
					}
					global.LOG.Critical(fmt.Sprintf("%s:%d", file, line))
					stack = stack + fmt.Sprintln(fmt.Sprintf("%s:%d</br>", file, line))
				}
				fmt.Println("stack:", stack)
				//go services.SendEmail(utils.APPNAME+"崩了"+time.Now().Format("2006-01-02 15:04:05"), stack, utils.EmailSendToUsers)
				go alarm_msg.SendAlarmMsg(utils.APPNAME+"崩了"+time.Now().Format("2006-01-02 15:04:05")+";Msg:"+stack, 2)
			}
		}()
		//time.Sleep(60*time.Second)
		//fmt.Println("i am here new")
		e.f(e.params...)
	}()

}

func NewExecutor(f TaskFunc, params []interface{}) *Executor {
	return &Executor{f: f, params: params}
}

func Task(f TaskFunc, params ...interface{})  {
	taskList <- NewExecutor(f, params)
}
