package repository

import (
	"strings"
	"time"

	"be.ems/src/framework/datasource"
	"be.ems/src/framework/logger"
	"be.ems/src/modules/network_data/model"
)

// 实例化数据层 Alarm 结构体
var NewAlarm = &Alarm{}

// Alarm 告警 数据层处理
type Alarm struct{}

// SelectByPage 分页查询集合
func (r Alarm) SelectByPage(querys model.AlarmQuery) ([]model.Alarm, int64) {
	tx := datasource.DB("").Model(&model.Alarm{})
	// 查询条件拼接
	if querys.NeType != "" {
		tx = tx.Where("ne_type = ?", querys.NeType)
	}
	if querys.RmUID != "" {
		tx = tx.Where("rm_uid = ?", querys.RmUID)
	}
	if querys.StartTime != "" {
		startTime := querys.StartTime
		if len(startTime) == 13 {
			startTime = startTime[:10]
		}
		tx = tx.Where("timestamp >= ?", startTime)
	}
	if querys.EndTime != "" {
		endTime := querys.EndTime
		if len(endTime) == 13 {
			endTime = endTime[:10]
		}
		tx = tx.Where("timestamp <= ?", endTime)
	}
	if querys.OrigSeverity != "" {
		eventTypes := strings.Split(querys.OrigSeverity, ",")
		tx = tx.Where("orig_severity in (%s)", eventTypes)
	}

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

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

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

	// 查询数据分页
	pageNum, pageSize := datasource.PageNumSize(querys.PageNum, querys.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
}

// Select 查询集合
func (r Alarm) Select(param model.Alarm) []model.Alarm {
	tx := datasource.DB("").Model(&model.Alarm{})
	// 查询条件拼接
	if param.NeType != "" {
		tx = tx.Where("ne_type = ?", param.NeType)
	}
	if param.NeId != "" {
		tx = tx.Where("ne_id = ?", param.NeId)
	}
	if param.NeName != "" {
		tx = tx.Where("ne_name = ?", param.NeName)
	}
	if param.AlarmCode != "" {
		tx = tx.Where("alarm_code = ?", param.AlarmCode)
	}
	if param.AlarmType != "" {
		tx = tx.Where("alarm_type = ?", param.AlarmType)
	}
	if param.AlarmId != "" {
		tx = tx.Where("alarm_id = ?", param.AlarmId)
	}
	if param.OrigSeverity != "" {
		eventTypes := strings.Split(param.OrigSeverity, ",")
		tx = tx.Where("orig_severity in (%s)", eventTypes)
	}
	if param.PvFlag != "" {
		tx = tx.Where("pv_flag = ?", param.PvFlag)
	}

	// 查询数据
	rows := []model.Alarm{}
	if err := tx.Find(&rows).Error; err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return rows
	}
	return rows
}

// SelectByIds 通过ID查询
func (r *Alarm) SelectByIds(ids []string) []model.Alarm {
	rows := []model.Alarm{}
	if len(ids) <= 0 {
		return rows
	}
	tx := datasource.DB("").Model(&model.Alarm{})
	// 构建查询条件
	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
}

// Insert 新增信息 返回新增数据ID
func (r Alarm) Insert(param model.Alarm) string {
	if param.Timestamp.IsZero() {
		param.Timestamp = time.Now()
	}
	// 执行插入
	if err := datasource.DB("").Create(&param).Error; err != nil {
		logger.Errorf("insert err => %v", err.Error())
		return ""
	}
	return param.ID
}

// Update 修改信息 返回受影响的行数
func (r Alarm) Update(param model.Alarm) int64 {
	if param.ID == "" {
		return 0
	}
	tx := datasource.DB("").Model(&model.Alarm{})
	// 构建查询条件
	tx = tx.Where("id = ?", param.ID)
	tx = tx.Omit("id", "timestamp")
	// 执行更新
	if err := tx.Updates(param).Error; err != nil {
		logger.Errorf("update err => %v", err.Error())
		return 0
	}
	return tx.RowsAffected
}

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

// SelectAlarmSeqLast 查询网元告警最后一条序号
func (r Alarm) SelectAlarmSeqLast(neType, neId string) int64 {
	tx := datasource.DB("").Model(&model.Alarm{})
	tx = tx.Where("ne_type=? and ne_id=?", neType, neId)
	tx = tx.Select("alarm_seq").Order("alarm_seq DESC")
	// 查询数据
	var alarmSeq int64 = 0
	if err := tx.Limit(1).Find(&alarmSeq).Error; err != nil {
		logger.Errorf("query find err => %v", err.Error())
		return alarmSeq
	}
	return alarmSeq
}
