package middleware

import (
	"net/http"
	"server/utility/ecode"
	"server/utility/i18n"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/util/gconv"
)

func Response(r *ghttp.Request) {
	r.Middleware.Next()

	if r.Response.BufferLength() > 0 {
		return
	}

	var (
		msg  string
		err  = r.GetError()
		res  = r.GetHandlerResponse()
		code = gerror.Code(err)
		ctx  = r.GetCtx()
	)
	glog.Debug(gctx.New(), "错误", err)
	if err != nil {
		if gconv.String(code.Detail()) != "customer" && code.Code() != 51 {
			msg = ecode.Fail.MessageI18n(ctx)
		} else if code.Code() == 51 {
			msg = ecode.Params.MessageI18n(ctx)
		} else {
			// 尝试从国际化系统获取消息
			msg = i18n.T(ctx, code.Message())
			if msg == code.Message() {
				// 如果没有找到国际化消息，使用原始消息
				msg = code.Message()
			}
		}
	} else if r.Response.Status > 0 && r.Response.Status != http.StatusOK {
		// HTTP状态码错误消息的国际化
		switch r.Response.Status {
		case http.StatusNotFound:
			code = gcode.CodeNotFound
			msg = i18n.T(ctx, "not_found")
		case http.StatusForbidden:
			code = gcode.CodeNotAuthorized
			msg = i18n.T(ctx, "forbidden")
		case http.StatusUnauthorized:
			code = gcode.CodeNotAuthorized
			msg = i18n.T(ctx, "unauthorized")
		default:
			code = gcode.CodeUnknown
			msg = i18n.T(ctx, "unknown_error")
		}
	} else {
		code = gcode.CodeOK
		msg = i18n.T(ctx, "success")
	}
	r.Response.WriteJson(ghttp.DefaultHandlerResponse{
		Code:    code.Code(),
		Message: msg,
		Data:    res,
	})
}
