package serializer

import (
	"gadmin/internal/admin/consts"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type Response struct {
	Code  int         `json:"code"`
	Data  interface{} `json:"data,omitempty"`
	Msg   string      `json:"msg"`
	Error string      `json:"error,omitempty"`
}

type TrackedErrorResponse struct {
	Response
	TrackID string `json:"track_id"`
}

func CheckLogin() Response {
	return Response{
		Code: consts.CodeCheckLogin,
		Msg:  "未登录",
	}
}

func Suc(data interface{}, msg ...interface{}) Response {
	newMsg := "OK"
	if len(msg) > 0 {
		newMsg = msg[0].(string)
	}
	res := Response{
		Code: consts.CodeSuccess,
		Data: data,
		Msg:  newMsg,
	}
	return res
}

func Err(errCode int, msg string, err error) Response {
	res := Response{
		Code: errCode,
		Msg:  msg,
	}

	// 正式服隐藏详细的报错信息
	//if err != nil && gin.Mode() != gin.ReleaseMode {
	//	res.Error = err.Error()
	//}

	if err != nil {
		res.Error = err.Error()
	}

	logrus.Warnf("serializer.Err msg:%v, err:%+v", msg, err)
	return res
}

func DBErr(msg string, err error) Response {
	if msg == "" {
		msg = "数据库操作失败"
	}
	return Err(consts.CodeDBError, msg, err)
}

func ParamErr(msg string, err error) Response {
	if msg == "" {
		msg = "参数错误"
	}
	return Err(consts.CodeParamErr, msg, err)
}

func JSONErrorExit(c *gin.Context, msg string) {
	logrus.Warnf("serializer.JSONErrorExit msg:%v", msg)
	c.JSON(http.StatusOK, Response{
		Code: consts.CodePanicErr,
		Msg:  msg,
	})
}
