package repository

import (
	"time"

	"be.ems/src/framework/database/db"
	"be.ems/src/framework/logger"
	"be.ems/src/modules/ne_data/model"
)

// 实例化数据层 AlarmForwardLog 结构体
var NewAlarmForwardLog = &AlarmForwardLog{}

// AlarmForwardLog 告警转发记录表 数据层处理
type AlarmForwardLog struct{}

// SelectByPage 分页查询集合
func (r AlarmForwardLog) SelectByPage(query model.AlarmForwardLogQuery) ([]model.AlarmForwardLog, int64) {
	tx := db.DB("").Model(&model.AlarmForwardLog{})
	// 查询条件拼接
	if query.NeType != "" {
		tx = tx.Where("ne_type = ?", query.NeType)
	}
	if query.NeID != "" {
		tx = tx.Where("ne_id = ?", query.NeID)
	}
	if query.BeginTime != 0 {
		tx = tx.Where("created_at >= ?", query.BeginTime)
	}
	if query.EndTime != 0 {
		tx = tx.Where("created_at <= ?", query.EndTime)
	}

	// 查询结果
	var total int64 = 0
	rows := []model.AlarmForwardLog{}

	// 查询数量为0直接返回
	if err := tx.Count(&total).Error; err != nil || total <= 0 {
		return rows, total
	}

	// 排序
	if query.SortField != "" {
		sortField := query.SortField
		if query.SortOrder == "desc" {
			sortField = sortField + " desc"
		}
		tx = tx.Order(sortField)
	}

	// 查询数据分页
	pageNum, pageSize := db.PageNumSize(query.PageNum, query.PageSize)
	tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
	err := tx.Find(&rows).Error
	if err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows, total
	}
	return rows, total
}

// SelectByIds 通过ID查询
func (r AlarmForwardLog) SelectByIds(ids []int64) []model.AlarmForwardLog {
	rows := []model.AlarmForwardLog{}
	if len(ids) <= 0 {
		return rows
	}
	tx := db.DB("").Model(&model.AlarmForwardLog{})
	// 构建查询条件
	tx = tx.Where("id in ?", ids)
	// 查询数据
	if err := tx.Find(&rows).Error; err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows
	}
	return rows
}

// DeleteByIds 批量删除信息
func (r AlarmForwardLog) DeleteByIds(ids []int64) int64 {
	if len(ids) <= 0 {
		return 0
	}
	tx := db.DB("").Where("id in ?", ids)
	if err := tx.Delete(&model.AlarmForwardLog{}).Error; err != nil {
		logger.Errorf("delete err => %v", err.Error())
		return 0
	}
	return tx.RowsAffected
}

// Insert 新增信息
func (r AlarmForwardLog) Insert(param model.AlarmForwardLog) int64 {
	if param.CreatedAt == 0 {
		param.CreatedAt = time.Now().UnixMilli()
	}
	// 执行插入
	if err := db.DB("").Create(&param).Error; err != nil {
		logger.Errorf("insert err => %v", err.Error())
		return 0
	}
	return param.ID
}
