package beego

import (
	"net/http"
	"os"
	"strconv"
	"time"

	"github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/server/web/context"
	"github.com/linmadan/egglib-go/web/beego/filters"

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

func init() {
	web.BConfig.AppName = "allied-creation-cooperation"
	web.BConfig.CopyRequestBody = true
	web.BConfig.RunMode = "dev"
	web.BConfig.Listen.HTTPPort = 8082
	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 = false
	web.BConfig.Listen.HTTPSPort = 443
	web.BConfig.Listen.HTTPSCertFile = "./config/fjmaimaimai.com_bundle.crt"
	web.BConfig.Listen.HTTPSKeyFile = "./config/fjmaimaimai.com.key"
	if os.Getenv("HTTPS_PORT") != "" {
		portStr := os.Getenv("HTTPS_PORT")
		if port, err := strconv.Atoi(portStr); err == nil {
			web.BConfig.Listen.HTTPSPort = port
		}
	}
	web.InsertFilter("/*", web.BeforeRouter, AllowCors())
	web.InsertFilter("/*", web.BeforeExec, filters.AllowCors())
	web.InsertFilter("/*", web.BeforeExec, filters.CreateRequstLogFilter(Logger))
	web.InsertFilter("/*", web.AfterExec, filters.CreateResponseLogFilter(Logger), web.WithReturnOnOutput(false))

	// 默认时区设置
	timeLocal, _ := time.LoadLocation("Asia/Chongqing")
	time.Local = timeLocal
}

func AllowCors() func(ctx *context.Context) {
	return func(ctx *context.Context) {
		ctx.Output.Header("Access-Control-Allow-Methods", "OPTIONS,DELETE,POST,GET,PUT,PATCH")
		ctx.Output.Header("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,X-MMM-DeviceType,X-MMM-Version,X-MMM-Timestamp,X-MMM-Uuid,X-MMM-Sign,X-MMM-AccessToken,X-MMM-AppName,X-MMM-AppProject,Authorization")
		ctx.Output.Header("Access-Control-Allow-Credentials", "true")
		ctx.Output.Header("Access-Control-Allow-Origin", "*")
		if ctx.Input.Method() == http.MethodOptions {
			ctx.Output.SetStatus(http.StatusOK)
			_ = ctx.Output.Body([]byte("options support"))
		}
	}
}