package api

import (
	"crm-api/pkg/lfshook"
	"fmt"
	"net/http"
	"runtime"

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

var resp *Response

func init() {
	resp = NewResponse()
}

type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

func NewResponse() *Response {
	return &Response{}
}

func Success(ctx *gin.Context, data interface{}) { resp.Success(ctx, data) }
func (r *Response) Success(ctx *gin.Context, data interface{}) {
	if data == nil {
		data = gin.H{}
	}

	ctx.JSON(http.StatusOK, Response{
		Code:    0,
		Message: "OK",
		Data:    data,
	})
}

func Error(ctx *gin.Context, code int, message string) { resp.Error(ctx, code, message) }
func (r *Response) Error(ctx *gin.Context, code int, message string) {
	// 调用信息
	msg := fmt.Sprintf("error msg: %s", message)
	pc, fileName, lineNumber, ok := runtime.Caller(2)
	if ok {
		msg = fmt.Sprintf("%s\n%s %s:%d", message, runtime.FuncForPC(pc).Name(), fileName, lineNumber)
	}

	lfshook.NewLogger().Error(msg)
	ctx.JSON(http.StatusOK, Response{
		Code:    code,
		Message: message,
		Data:    nil,
	})
}
