package operation_log_service

import (
	"bwallet/models"
	"bwallet/pkg/util"
)

type OperationLog struct {
	UserId     int
	UserName   string
	PlatformId int
	Ip         string
	Operation  string
	Business   string
	Table      string

	PageNum  int
	PageSize int
}

func (ol *OperationLog) Add() error {
	operationLog := map[string]interface{}{
		"user_id":     ol.UserId,
		"user_name":   ol.UserName,
		"platform_id": ol.PlatformId,
		"ip":          ol.Ip,
		"operation":   ol.Operation,
		"business":    ol.Business,
		"table":       ol.Table,
	}

	if err := models.AddOperationLog(operationLog); err != nil {
		return err
	}

	return nil
}

func (ol *OperationLog) GetAll() ([]*models.OperationLogs, error) {
	var operationLog []*models.OperationLog

	operationLog, err := models.GetOperationLogs(ol.PageNum, ol.PageSize, ol.getMaps())
	if err != nil {
		return nil, err
	}

	var operationLogs []*models.OperationLogs

	for _, value := range operationLog {
		op := &models.OperationLogs{}
		ip, _ := util.Long2IPString(value.Ip)
		op.UserId = value.UserId
		op.UserName = value.UserName
		op.PlatformId = value.PlatformId
		op.Ip = ip
		op.Operation = value.Operation
		op.Business = value.Business
		op.Table = value.Table
		operationLogs = append(operationLogs, op)
	}

	return operationLogs, nil
}

func (ol *OperationLog) Count() (int, error) {
	return models.GetOperationLogTotal(ol.getMaps())
}

func (ol *OperationLog) getMaps() (map[string]interface{}) {
	maps := make(map[string]interface{})

	if ol.UserId != 0 {
		maps["user_id"] = ol.UserId
	}

	if ol.UserName != "" {
		maps["user_name"] = ol.UserName
	}

	if ol.PlatformId != 0 {
		maps["platform_id"] = ol.PlatformId
	}

	if ol.Ip != "" {
		ip, _ := util.IPString2Long(ol.Ip)
		maps["ip"] = ip
	}

	return maps
}
