package models

import (
	"bwallet/pkg/setting"
	"bwallet/pkg/util"
	"time"
)

type OperationLog struct {
	Model

	Id         uint64 `json:"primary_key, id,omitempty"`
	UserId     int    `json:"user_id"`
	UserName   string `json:"user_name"`
	PlatformId int    `json:"platform_id"`
	Ip         uint   `json:"ip"`
	Operation  string `json:"operation"`
	Business   string `json:"business"`
	Table      string `json:"table"`
	CreateTime string `json:"create_time"`
}

type OperationLogs struct {
	UserId     int    `json:"user_id"`
	UserName   string `json:"user_name"`
	PlatformId int    `json:"platform_id"`
	Ip         string `json:"ip"`
	Operation  string `json:"operation"`
	Business   string `json:"business"`
	Table      string `json:"table"`
	CreateTime string `json:"create_time"`
}

func (a OperationLog) TableName() string {
	return setting.DatabaseSetting.Name_Sources + ".wallet_operation_log"
}

func GetOperationLogTotal(maps interface{}) (int, error) {
	var count int

	if err := db.Model(&OperationLog{}).Where(maps).Count(&count).Error; err != nil {
		return 0, err
	}

	return count, nil
}

func GetOperationLogs(pageNum, pageSize int, maps interface{}) ([]*OperationLog, error) {
	var operationLogs []*OperationLog
	if err := db.Where(maps).Order("id desc").Offset(pageNum).Limit(pageSize).Find(&operationLogs).Error; err != nil {
		return nil, err
	}

	return operationLogs, nil
}

func AddOperationLog(data map[string]interface{}) error {
	ip, _ := util.IPString2Long(data["ip"].(string))
	operationLog := OperationLog{
		UserId:     data["user_id"].(int),
		UserName:   data["user_name"].(string),
		PlatformId: data["platform_id"].(int),
		Ip:         ip,
		Operation:  data["operation"].(string),
		Business:   data["business"].(string),
		Table:      data["table"].(string),
		CreateTime: time.Now().Format("2006-01-02 15:04:05"),
	}

	if err := db.Create(&operationLog).Error; err != nil {
		return err
	}

	return nil
}
