package backend

import (
	"bwallet/pkg/errno"
	"bwallet/pkg/handler"
	"bwallet/pkg/util"
	"bwallet/service/operation_log_service"
	"bwallet/validate_service"
	"github.com/Unknwon/com"
	"github.com/gin-gonic/gin"
)

func GetOperationLogs(c *gin.Context) {
	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)
	group := user.UserInfo.Group
	var platform_id, user_id int
	if ("administrator" == group) {
		platform_id = com.StrTo(c.DefaultQuery("platform_id", "1")).MustInt()
	} else {
		platform_id = user.UserInfo.PlatformId
	}

	if arg := c.Query("user_id"); arg != "" {
		user_id = com.StrTo(c.Query("user_id")).MustInt()
	}

	var user_name string
	if arg := c.Query("user_name"); arg != "" {
		user_name = c.Query("user_name")
	}

	operationLogService := operation_log_service.OperationLog{
		UserId:     user_id,
		UserName:   user_name,
		PlatformId: platform_id,
		PageNum:    util.GetPage(c),
		PageSize:   util.GetLimit(c),
	}

	total, err := operationLogService.Count()
	if err != nil {
		handler.SendResponse(c, errno.ErrCountRecommendCategory, nil)
		return
	}

	operation_logs, err := operationLogService.GetAll()
	if err != nil {
		handler.SendResponse(c, errno.InternalServerError, nil)
		return
	}

	data := make(map[string]interface{})
	data["items"] = operation_logs
	data["total"] = total

	handler.SendResponse(c, nil, data)
}

func AddOperationLog(c *gin.Context) {
	token := c.Request.Header.Get("Token")
	user, _ := util.ParseToken(token)

	operation_log := validate_service.OperationLog{}
	c.ShouldBindJSON(&operation_log)

	operationLogService := operation_log_service.OperationLog{
		UserId:     user.UserInfo.Uid,
		UserName:   user.UserInfo.Username,
		PlatformId: user.UserInfo.PlatformId,
		Ip:         operation_log.Ip,
		Operation:  operation_log.Operation,
		Business:   operation_log.Business,
		Table:      operation_log.Table,
	}

	if err := operationLogService.Add(); err != nil {
		handler.SendResponse(c, errno.ErrAddOperationLog, nil)
		return
	}

	handler.SendResponse(c, nil, nil)
}
