package conf

import (
	"LAPP_ACURA_MOM_BACKEND/web/supports"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/logger"
	rcover "github.com/kataras/iris/v12/middleware/recover"
)

var ExampleFile = "http://localhost:9005/public/uploadxlsx/example.xlsx"

var Baseurl = "http://localhost:9005"

//var ExampleFile = "http://localhost:8097/public/uploadxlsx/example.xlsx"
//

//var Baseurl = "http://localhost:8097"

type AppConf struct {
	DisablePathCorrection             bool
	EnablePathEscape                  bool
	FireMethodNotAllowed              bool
	DisableBodyConsumptionOnUnmarshal bool
	TimeFormat                        string
	Charset                           string
	Other                             Other
	PublicRute                        []string
}

type Other struct {
	IgnoreURLs []string
	JWTTimeout int64
	LogLevel   string
	Secret     string
}

var AppConfig AppConf = AppConf{
	DisablePathCorrection:             false,
	EnablePathEscape:                  false,
	FireMethodNotAllowed:              false,
	DisableBodyConsumptionOnUnmarshal: false,
	TimeFormat:                        "Mon, 01 Jan 2006 15:04:05 GMT",
	Charset:                           "UTF-8",
	Other: Other{
		IgnoreURLs: []string{"/", "/user/login", "/user/plants", "/admin/tabnames/download", "/user/getimg", "/admin/api/screw/receive", "/admin/log/artdemandhead/selectlastmodify", "/admin/log/artdemandlst/synchronous", "/admin/log/artdemandlstcache/synchronouscache", "/admin/report/filterdatainfo/display", "/admin/ws", "/admin/pln/custorder/dashboard", "/admin/base/workline/virtual"}, //免token验证路径
		JWTTimeout: 72000,
		LogLevel:   "debug",
		Secret:     "lapp_gaas_gframe",
	},
	PublicRute: []string{"/sysMenu", "/user/getuserinfo", "/user/pwd", "/user/avatar", "/user/profile", "/user/getimg", "/admin/tabnames/list", "/admin/stdeftab/selectarr", "/admin/stdeftab/selectall", "/admin/log/artdemandhead/selectlastmodify", "/admin/log/artdemandlst/synchronous", "/admin/log/artdemandlstcache/synchronouscache", "/admin/pln/custorder/dashboard", "/admin/base/workline/virtual"}, //免权限检查路径
}

var (
	// conf strut
	C iris.Configuration

	// 解析app.yml中的Other项
	O Other
	// app.conf配置项key定义
	ignoreURLs string = "IgnoreURLs"
	jwtTimeout string = "JWTTimeout"
	logLevel   string = "LogLevel"
	secret     string = "Secret"
)

func AppOtherParse() {
	appData := AppConfig
	c := iris.DefaultConfiguration()
	c.DisableBodyConsumptionOnUnmarshal = appData.DisableBodyConsumptionOnUnmarshal
	c.DisablePathCorrection = appData.DisablePathCorrection
	c.EnablePathEscape = appData.EnablePathEscape
	c.FireMethodNotAllowed = appData.FireMethodNotAllowed
	c.TimeFormat = appData.TimeFormat
	c.Charset = appData.Charset
	other := make(map[string]interface{}, 0)
	other["IgnoreURLs"] = appData.Other.IgnoreURLs
	other["JWTTimeout"] = appData.Other.JWTTimeout
	other["LogLevel"] = appData.Other.LogLevel
	other["Secret"] = appData.Other.Secret
	c.Other = other
	C = c

	// 解析other的key
	iURLs := c.GetOther()[ignoreURLs].([]string)
	fmt.Println(iURLs)
	for _, v := range iURLs {
		O.IgnoreURLs = append(O.IgnoreURLs, v)
	}

	jTimeout := c.GetOther()[jwtTimeout].(int64)
	O.JWTTimeout = int64(jTimeout)
	//golog.Info(reflect.TypeOf(O.JWTTimeout))

	O.LogLevel = c.GetOther()[logLevel].(string)

	O.Secret = c.GetOther()[secret].(string)

}

// 注册中间件、定义错误处理
func PreSettring(app *iris.Application) {
	app.Logger().SetLevel(AppConfig.Other.LogLevel)

	customLogger := logger.New(logger.Config{
		//状态显示状态代码
		Status: true,
		// IP显示请求的远程地址
		IP: true,
		//方法显示http方法
		Method: true,
		// Path显示请求路径
		Path: true,
		// Query将url查询附加到Path。
		Query: true,
		//Columns：true，
		// 如果不为空然后它的内容来自`ctx.Values(),Get("logger_message")
		//将添加到日志中。
		MessageContextKeys: []string{"logger_message"},
		//如果不为空然后它的内容来自`ctx.GetHeader（“User-Agent”）
		MessageHeaderKeys: []string{"User-Agent"},
	})
	app.Use(
		rcover.New(),
		customLogger,
		//middleware.ServeHTTP
	)
	// ---------------------- 定义错误处理 ------------------------
	app.OnErrorCode(iris.StatusNotFound, customLogger, func(ctx iris.Context) {
		supports.Error(ctx, iris.StatusNotFound, supports.NotFound, nil)
	})
	//app.OnErrorCode(iris.StatusForbidden, customLogger, func(ctx iris.Context) {
	//	ctx.JSON(utils.Error(iris.StatusForbidden, "权限不足", nil))
	//})
	//捕获所有http错误:
	//app.OnAnyErrorCode(customLogger, func(ctx iris.Context) {
	//	//这应该被添加到日志中，因为`logger.Config＃MessageContextKey`
	//	ctx.Values().Set("logger_message", "a dynamic message passed to the logs")
	//	ctx.JSON(utils.Error(500, "服务器内部错误", nil))
	//})
}
