package task

import (
	"encoding/json"
	"time"

	"gd_management_gateway/common.in/jsonrpc2"
	"gd_management_gateway/common.in/span"
	"github.com/astaxie/beego/context"
)

type Task func() error

func Do(er Recoverer, ctx *context.Context, tasks ...Task) {
	// task执行返回的error
	var taskErr error

	// 植入跟踪日志id信息
	spanID := span.NewRootSpanID()
	ctx.Input.Context.Request.Header.Add("span", spanID.String())
	// 开始时间
	startTime := uint64(time.Now().UnixNano())

	// 抓异常代码
	defer func() {
		status := "SUCCESS"
		// 捕获到panic
		if r := recover(); r != nil {
			er.Recover(r)
			status = "FAIL"
		}

		// task返回失败
		if taskErr != nil {
			e := &jsonrpc2.Error{}
			if err := json.Unmarshal([]byte(taskErr.Error()), e); err != nil {
				ctx.Output.JSON(Response{Code: 10001, Msg: "系统错误"}, false, false)
			} else {
				ctx.Output.JSON(Response{Code: e.Code, Msg: e.Message}, false, false)
			}
			status = "FAIL"
		}
		printAccessLog(ctx, startTime, status, spanID)
	}()

	for _, task := range tasks {
		if task != nil {
			if err := task(); err != nil {
				taskErr = err
				return
			}
		}
	}
}
