package models

import (
	"fmt"
	"time"
)

type OperationLog struct {
	From         string      `json:"from"`
	Ip           string      `json:"ip" bson:"ip"`                       // 操作地址Ip
	OperatorId   string      `json:"operator_id" bson:"operator_id"`     // 操作员Id
	OperatorName string      `json:"operator_name" bson:"operator_name"` // 操作员name
	Operation    string      `json:"operation" bson:"operation"`         // 操作 增删改
	Business     string      `json:"business" bson:"business"`           // 业务名称
	Tables       string      `json:"tables" bson:"tables"`               // 直接相关表（一个）
	Data         interface{} `json:"data" bson:"data"`                   // 新数据的保存 只保留主键id
}

type OpLog struct {
	From         string    `json:"from"`
	Ip           string    `json:"ip" bson:"ip"`
	OperatorId   string    `json:"operator_id" bson:"operator_id"`
	OperatorName string    `json:"operator_name" bson:"operator_name"`
	Operation    string    `json:"operation" bson:"operation"`
	Business     string    `json:"business" bson:"business"`
	Tables       string    `json:"tables" bson:"tables"`
	Data         string    `json:"data" bson:"data"`
	CreateTime   time.Time `json:"create_time"`
}

func InsertLog(operation interface{}) (err error) {
	err = db.Create(operation).Error
	return
}

func GetOperatorLog(opType string, opName string, pageNum int, pageSize int) (opLog []OpLog) {
	selectSql := fmt.Sprintf(
		"SELECT * FROM operation_log WHERE id >0 ")

	if opType != "" {
		selectSql += fmt.Sprintf(" AND tables = '%s' ", opType)
	}

	if opName != "" {
		selectSql += fmt.Sprintf(" AND operator_name = '%s' ", opName)
	}

	db.Raw(selectSql).Offset(pageNum).Limit(pageSize).Order("create_time DESC").Scan(&opLog)
	return
}

func GetOperatorLogTotal(opType string, opName string) (count int) {
	selectSql := fmt.Sprintf("SELECT COUNT(*) FROM operation_log WHERE id >0 ")

	if opType != "" {
		selectSql += fmt.Sprintf(" and tables = '%s' ", opType)
	}

	if opName != "" {
		selectSql += fmt.Sprintf(" and operator_name = '%s' ", opName)
	}
	db.Raw(selectSql).Count(&count)
	return
}
