package middleware

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	"hongze/hongze_yb/global"
	"hongze/hongze_yb/services/alarm_msg"
	"hongze/hongze_yb/utils"
	"net/http"
	"runtime"
	"time"
)

// Recover 异常处理
func Recover() gin.HandlerFunc {
	return func(c *gin.Context) {
		contentType := c.ContentType()
		// 为 multipart forms 设置较低的内存限制（50M） (默认是 32 MiB)
		if contentType == "multipart/form-data" {
			err := c.Request.ParseMultipartForm(10 << 20)
			if err != nil {
				response.Custom(http.StatusRequestEntityTooLarge, "上传文件太大，err:"+err.Error(), c)
				c.Abort()
				return
			}
		}
		defer func() {
			if err := recover(); err != nil {
				stack := ""

				msg := fmt.Sprintf("The request url is  %v", c.Request.RequestURI)
				stack += msg + "</br>"
				global.LOG.Critical(msg)
				msg = fmt.Sprintf("The request data is %v", c.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)
				response.Custom(http.StatusInternalServerError, "系统异常", c)
				//c.JSON(http.StatusInternalServerError, Err)
				//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")+";Err:"+stack, 3)
				return
			}
		}()
		c.Next()
	}
}
