package lxCommon

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type errorCode struct {
	SUCCESS      int
	ERROR        int
	NotFound     int
	LoginError   int
	LoginTimeout int
	InActive     int
}

// ErrorCode 错误码
var ErrorCode = errorCode{
	SUCCESS:      0,
	ERROR:        1,
	NotFound:     404,
	LoginError:   1000, //用户名或密码错误
	LoginTimeout: 1001, //登录超时
	InActive:     1002, //未激活账号
}

func SendErrJSON(msg string, args ...interface{}) {
	if len(args) == 0 {
		panic("缺少 *gin.Context")
	}
	var c *gin.Context
	var errNo = ErrorCode.ERROR
	if len(args) == 1 {
		theCtx, ok := args[0].(*gin.Context)
		if !ok {
			panic("缺少 *gin.Context")
		}
		c = theCtx
	} else if len(args) == 2 {
		theErrNo, ok := args[0].(int)
		if !ok {
			panic("errNo不正确")
		}
		errNo = theErrNo
		theCtx, ok := args[1].(*gin.Context)
		if !ok {
			panic("缺少 *gin.Context")
		}
		c = theCtx
	}
	fmt.Println(msg) // todo for debug, added by leek, 应该放到业务里决定是否打印错误日志 还是统一放到这里?
	c.JSON(http.StatusOK, gin.H{
		"errNo": errNo,
		"msg":   msg,
		"data":  gin.H{},
	})
	// 终止请求链
	c.Abort()
}

func Ok(c *gin.Context, data interface{}) {
	c.JSON(http.StatusOK, gin.H{
		"errNo": ErrorCode.SUCCESS,
		"msg":   "success",
		"data":  data,
	})
}

func HandleParamError(c *gin.Context, err error) bool {
	if err != nil {
		SendErrJSON("参数错误:"+err.Error(), c)
		return true
	}
	return false
}

func HandleError(c *gin.Context, err error) bool {
	if err != nil {
		SendErrJSON(err.Error(), c)
		return true
	}
	return false
}
