package dao

import (
	"time"
)

// OperationHistory 操作记录
type OperationHistory struct {
	ID            int       `gorm:"primary_key" json:"id"`            //编号
	OperationType int       `gorm:"type:int" json:"operationType"`    //操作类型
	ModuleType    int       `gorm:"type:int" json:"moduleType"`       //操作模块
	DeviceType    int       `gorm:"type:int" json:"deviceType"`       //操作模块
	Object        string    `gorm:"type:varchar(48)" json:"object"`   //操作对象 一般为设备ID+Name
	Result        int       `gorm:"type:int" json:"result"`           //0 成功 1失败
	HandleUserId  int64     `gorm:"type:bigint" json:"handleUserId"`  //操作用户ID
	HandleTime    time.Time `gorm:"type:timestamp" json:"handleTime"` //操作时间
	TenantId      string    `gorm:"type:varchar(12)" json:"tenantId"` //租户ID
}

func (OperationHistory) TableName() string {
	return "operation_history"
}

func (c *OperationHistory) Create() error {
	return Db.Debug().Model(&c).Save(&c).Error
}

func (c OperationHistory) GetHistories(offset, limit int) ([]OperationHistory, int64, error) {
	var list []OperationHistory
	var counts int64
	db := Db.Debug().Model(&c)

	if c.OperationType > 0 {
		db = db.Where("operation_type = ?", c.OperationType)
	}
	if c.ModuleType > 0 {
		db = db.Where("module_type = ?", c.ModuleType)
	}
	if c.Object != "" {
		db = db.Where("object like ?", "%"+c.Object+"%")
	}

	err := db.Order("handle_time DESC").Offset(offset).Limit(limit).Find(&list).Error
	db1 := Db.Debug().Model(&c)
	db1.Count(&counts)
	return list, counts, err
}
