package service

import (
	"fmt"
	"time"

	"github.com/tsmask/go-oam"

	"be.ems/src/modules/ne_data/model"
	"be.ems/src/modules/ne_data/repository"
)

// 实例化数据层 AlarmEvent 结构体
var NewAlarmEvent = &AlarmEvent{
	alarmEventRepository: repository.NewAlarmEvent,
}

// AlarmEvent 告警 服务层处理
type AlarmEvent struct {
	alarmEventRepository *repository.AlarmEvent // 告警数据信息
}

// FindByPage 根据条件分页查询
func (r AlarmEvent) FindByPage(query model.AlarmEventQuery) ([]model.AlarmEvent, int64) {
	return r.alarmEventRepository.SelectByPage(query)
}

// Find 查询
func (r AlarmEvent) Find(param model.AlarmEvent) []model.AlarmEvent {
	return r.alarmEventRepository.Select(param)
}

// Insert 新增信息
func (s AlarmEvent) Insert(param model.AlarmEvent) int64 {
	return s.alarmEventRepository.Insert(param)
}

// Update 修改信息
func (s AlarmEvent) Update(param model.AlarmEvent) int64 {
	return s.alarmEventRepository.Update(param)
}

// DeleteByIds 批量删除信息
func (r AlarmEvent) DeleteByIds(ids []int64) (int64, error) {
	// 检查是否存在
	data := r.alarmEventRepository.SelectByIds(ids)
	if len(data) <= 0 {
		return 0, fmt.Errorf("no data")
	}

	if len(data) == len(ids) {
		rows := r.alarmEventRepository.DeleteByIds(ids)
		return rows, nil
	}
	// 删除信息失败！
	return 0, fmt.Errorf("delete fail")
}

// FindAlarmEventSeqLast 查询网元告警最后一条序号
func (s AlarmEvent) FindAlarmEventSeqLast(neType, neId string) int64 {
	return s.alarmEventRepository.SelectAlarmEventSeqLast(neType, neId)
}

// ClearByIds 批量清除告警信息
func (r AlarmEvent) ClearByIds(ids []int64, clearUser, clearType string) (int64, error) {
	// 检查是否存在
	arr := r.alarmEventRepository.SelectByIds(ids)
	if len(arr) <= 0 {
		return 0, fmt.Errorf("no data")
	}

	if len(arr) == len(ids) {
		var rows int64 = 0
		for _, v := range arr {
			v.AlarmStatus = oam.ALARM_STATUS_CLEAR
			// 告警清除
			v.ClearType = clearType
			v.ClearUser = clearUser
			v.ClearTime = time.Now().UnixMilli()
			rows += r.alarmEventRepository.Update(v)
		}
		return rows, nil
	}
	return 0, fmt.Errorf("clear fail")
}
