package middleware

import (
	"fmt"
	"iris-demo/library/config"
	"iris-demo/library/logger"
	"iris-demo/library/util"
	"strconv"
	"time"

	"github.com/gogf/guuid"
	"github.com/kataras/iris/v12"
)

func MiddlewareMock(ctx iris.Context) {
	// logger.Error(mock)
	// 处理mock数据
	mock := config.Config.Get("mock")
	if mock != nil {
		mockData := mock.(map[string]interface{})
		if mockData["use"].(bool) == true {
			for k, v := range mockData {
				if k != "use" {
					ctx.Request().Header.Set(k, v.(string)) // request header
					// ctx.Header(k, v.(string)) // response header
				}
			}
		}
	}

	ctx.Next()
}

// 日志追踪
func MiddlewareTrace(ctx iris.Context) {
	ctx.Request().Header.Set("beginTime", strconv.FormatInt(time.Now().UnixNano(), 10))
	// 绑定traceId
	trackId := (guuid.New()).String()
	ctx.Values().Set("trackId", trackId)
	// logger.Info("trackId:", ctx.Values().Get("trackId"))

	requestId := ctx.GetHeader("X-Request-Id")
	if requestId == "" {
		requestId = (guuid.New()).String()
	}
	ctx.Values().Set("requestId", requestId)
	// logger.Info("requestId:", requestId)

	userName := ctx.GetHeader("X-User-Name")
	ctx.Values().Set("userName", userName)
	// logger.Info("userName:", userName)

	userId := ctx.GetHeader("X-User-Id")
	ctx.Values().Set("userId", userId)
	// logger.Info("userId:", userId)

	// 设置Logger和DB
	logger.SetLoggerEntry(ctx)

	clientIp := util.ClientIP(ctx)
	// logger.Info(clientIp)

	clientPublicIp := util.ClientPublicIP(ctx)

	// printBody, _ := ctx.GetBody() // buffer只能取一次
	receiveTemplate := "request[%v]: from %v|%v"
	logger.Info(fmt.Sprintf(receiveTemplate,
		ctx.Request().URL.Path,
		clientIp,
		clientPublicIp))

	ctx.Next()
}

func MiddlewareEnd(ctx iris.Context) {
	ctx.Record()
	ctx.Next()
	resp := string(ctx.Recorder().Body())

	t := time.Now().UnixNano()
	str := ctx.GetHeader("beginTime")
	t1, _ := strconv.ParseInt(str, 10, 64)
	since := (t - t1) / 1000000

	statusCode := ctx.Recorder().StatusCode()

	responseTemplate := "response[%v]: HttpCode=%v time=[%d] [body-raw]=\n%v"
	logger.Info(fmt.Sprintf(responseTemplate,
		ctx.Request().URL.Path, statusCode, since, resp))

}
