package log

import (
	"bwallet/pkg/util"
	"bwallet/service/operation_log_service"

	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
)

func LogMiddleware(handlerTableName map[string]string) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var operation string

		// 获取当前用户信息
		token := ctx.Request.Header.Get("Token")
		user, err := util.ParseToken(token)
		if err != nil {
			ctx.Abort()
			return
		}
		user_id := user.UserInfo.Uid
		user_name := user.UserInfo.Username
		platform_id := user.UserInfo.PlatformId

		// 获取表名 这里会把前面 "加载的包名.HandlerName"
		handlerName := strings.Split(ctx.HandlerName(), ".")[1]
		if _, ok := handlerTableName[handlerName]; !ok {
			ctx.Next()
		}

		tableDesc := strings.Split(handlerTableName[handlerName], ",")
		if len(tableDesc) != 2 {
			return // 存在映射，但是不完全则返回
		}
		tableName := tableDesc[0] // 0表名
		desc := tableDesc[1]      // 1业务描述

		switch ctx.Request.Method {
		case "POST":
			operation = "增加"
		case "GET":
			operation = "查询"
		case "PUT":
			operation = "更新"
		case "DELETE":
			operation = "删除"
		default:
			operation = "未知"
		}

		operationLogService := operation_log_service.OperationLog{
			UserId:     user_id,
			UserName:   user_name,
			PlatformId: platform_id,
			Ip:         ctx.ClientIP(),
			Operation:  operation,
			Business:   desc,
			Table:      tableName,
		}

		if err := operationLogService.Add(); err != nil {
			ctx.Abort()
			return
		}

		return
	}
}

func FirstMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		fmt.Println(c.Request.Method, c.ClientIP(), c.Request.Header.Get("Token"))
		fmt.Println("first middleware before next()")
		isAbort := c.Query("isAbort")
		bAbort, err := strconv.ParseBool(isAbort)
		if err != nil {
			fmt.Printf("is abort value err, value %s\n", isAbort)
			c.Next() // (2)
		}
		if bAbort {
			fmt.Println("first middleware abort") //(3)
			c.Abort()
			//c.AbortWithStatusJSON(http.StatusOK, "abort is true")
			return
		} else {
			fmt.Println("first middleware doesnot abort") //(4)
			return
		}

		fmt.Println("first middleware after next()")
	}
}

func SecondMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		fmt.Println("current inside of second middleware")
	}
}
