package service

import (
	"fonchain-fiee/pkg/common"
	"github.com/gin-gonic/gin"
	"net/http"
)

const (
	Failed = 1
	Ok     = 0

	RetryCode = 2
)

// Response 基础序列化器
type Response struct {
	Status int         `json:"status"`
	Data   interface{} `json:"data"`
	Msg    string      `json:"msg"`
	Code   int         `json:"code"`
	Error  error       `json:"error"`
}

// Success Success(c,someMap) datas传结构体中文会有乱码问题
func Success(c *gin.Context, datas ...interface{}) {
	var data interface{}
	if datas != nil {
		data = datas[0]
	} else {
		data = struct{}{}
	}
	c.JSON(http.StatusOK, Response{
		Status: Ok,
		Code:   Ok,
		Data:   data,
		Msg:    "ok",
	})
	c.Abort()
}

func Success1(c *gin.Context, msg string, datas ...interface{}) {
	var data interface{}

	if datas != nil {
		data = datas[0]
	} else {
		data = struct{}{}
	}
	c.JSON(http.StatusOK, Response{
		Status: Ok,
		Code:   Ok,
		Data:   data,
		Msg:    msg,
	})
	c.Abort()
}

// Error 统一错误返回
func Error(c *gin.Context, err error) {

	errMsg := ""
	if err != nil {
		errMsg = translateErrorMessage(c, err.Error())
	}

	c.JSON(http.StatusOK, Response{
		Code:   Failed,
		Status: Failed,
		Msg:    errMsg,
		Data:   struct{}{},
	})

	c.Abort()
}

// Error 统一错误返回
func Error1(c *gin.Context, err error) {

	c.JSON(http.StatusOK, Response{
		Code:   Failed,
		Status: Failed,
		Msg:    err.Error(),
		Data:   struct{}{},
	})

	c.Abort()
}

// 重试
func Retry(c *gin.Context, err error) {
	errMsg := ""
	if err != nil {
		errMsg = err.Error()
	}

	c.JSON(http.StatusOK, Response{
		Code: RetryCode,
		Msg:  errMsg,
		Data: struct{}{},
	})

	c.Abort()
}

func NotLoginError(c *gin.Context, err error) {

	errMsg := ""
	if err != nil {
		errMsg = translateErrorMessage(c, err.Error())
	}

	c.JSON(http.StatusUnauthorized, Response{
		Code: Failed,
		Msg:  errMsg,
		Data: struct{}{},
	})

	c.Abort()
}

func translateErrorMessage(c *gin.Context, message string) string {
	lang := c.GetHeader("Accept-Language")
	switch lang {
	case "zh-CN":
		return message
	case "zh-TW":
		return common.ZhTWMessages[message]
	case "de-DE":
		return common.DeDEMessages[message]
	case "ja-JP":
		return common.JaJPMessages[message]
	default:
		return common.EnMessages[message]
	}
}
