package beego

import (
	"github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/server/web/context"
	"github.com/linmadan/egglib-go/log"
	"github.com/linmadan/egglib-go/web/beego/filters"
	"os"
	"strconv"

	. "gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/log"
	_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-user/pkg/port/beego/routers"
)

func init() {
	web.BConfig.AppName = "project"
	web.BConfig.CopyRequestBody = true
	web.BConfig.RunMode = "dev"
	web.BConfig.Listen.HTTPPort = 8080
	web.BConfig.Listen.EnableAdmin = false
	web.BConfig.WebConfig.CommentRouterPath = "/pkg/port/beego/routers"
	if os.Getenv("RUN_MODE") != "" {
		web.BConfig.RunMode = os.Getenv("RUN_MODE")
	}
	if os.Getenv("HTTP_PORT") != "" {
		portStr := os.Getenv("HTTP_PORT")
		if port, err := strconv.Atoi(portStr); err == nil {
			web.BConfig.Listen.HTTPPort = port
		}
	}
	web.InsertFilter("/*", web.BeforeRouter, filters.AllowCors())
	web.InsertFilter("/*", web.BeforeExec, CreateRequestLogFilter(Logger))
	web.InsertFilter("/*", web.AfterExec, filters.CreateResponseLogFilter(Logger), web.WithReturnOnOutput(false))
}

func CreateRequestLogFilter(logger log.Logger) func(ctx *context.Context) {
	return func(ctx *context.Context) {
		var append = make(map[string]interface{})
		append["framework"] = "beego"
		append["method"] = ctx.Input.Method()
		append["url"] = ctx.Input.URL()
		logger.Info("http请求", append)
		if ctx.Input.Is("GET") {
			logger.Debug("http请求", append)
		}
		if ctx.Input.Is("POST") || ctx.Input.Is("PUT") {
			append["inputData"] = string(ctx.Input.RequestBody)
			logger.Debug("http请求", append)
		}
	}
}