package beego

import (
	"github.com/beego/beego/v2/server/web"
	"github.com/linmadan/egglib-go/web/beego/filters"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
	"net/http"
	"net/http/pprof"
	"os"
	"strconv"

	. "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/log"
	_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/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
		}
	}
	//https支持
	web.BConfig.Listen.EnableHTTPS = true
	web.BConfig.Listen.HTTPSPort = 443

	//进程内监控
	//web.BConfig.Listen.EnableAdmin = true
	//web.BConfig.Listen.AdminPort = 8088
	if os.Getenv("HTTPS_PORT") != "" {
		portStr := os.Getenv("HTTPS_PORT")
		if port, err := strconv.Atoi(portStr); err == nil {
			web.BConfig.Listen.HTTPSPort = port
		}
	}

	if constant.PPROF_ON {
		web.Handler("/debug/pprof/", http.HandlerFunc(pprof.Index))
		web.Handler("/debug/cmdline", http.HandlerFunc(pprof.Cmdline))
		web.Handler("/debug/profile", http.HandlerFunc(pprof.Profile))
		web.Handler("/debug/symbol", http.HandlerFunc(pprof.Symbol))
		web.Handler("/debug/trace", http.HandlerFunc(pprof.Trace))

		web.Handler("/debug/allocs", pprof.Handler("allocs"))
		web.Handler("/debug/block", pprof.Handler("block"))
		web.Handler("/debug/goroutine", pprof.Handler("goroutine"))
		web.Handler("/debug/heap", pprof.Handler("heap"))
		web.Handler("/debug/mutex", pprof.Handler("mutex"))
		web.Handler("/debug/threadcreate", pprof.Handler("threadcreate"))
	}

	web.BConfig.Listen.HTTPSCertFile = "./config/fjmaimaimai.com_bundle.crt"
	web.BConfig.Listen.HTTPSKeyFile = "./config/fjmaimaimai.com.key"
	web.InsertFilter("/*", web.BeforeExec, filters.AllowCors())
	web.InsertFilter("/*", web.BeforeExec, filters.CreateRequstLogFilter(Logger))
	web.InsertFilter("/*", web.AfterExec, filters.CreateResponseLogFilter(Logger), web.WithReturnOnOutput(false))
}