package service

import (
	"fmt"
	"time"

	"be.ems/src/framework/constants"
	"be.ems/src/framework/utils/parse"
	"be.ems/src/modules/network_data/model"
	"be.ems/src/modules/network_data/repository"
)

// 实例化数据层 Alarm 结构体
var NewAlarm = &Alarm{
	alarmRepository: repository.NewAlarm,
}

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

// SelectPage 根据条件分页查询
func (r *Alarm) SelectPage(querys model.AlarmQuery) ([]model.Alarm, int64) {
	return r.alarmRepository.SelectByPage(querys)
}

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

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

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

// Insert 新增信息
func (s Alarm) Insert(param model.Alarm) string {
	return s.alarmRepository.Insert(param)
}

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

// FindAlarmSeqLast 查询网元告警最后一条序号
func (s Alarm) FindAlarmSeqLast(neType, neId string) int64 {
	return s.alarmRepository.SelectAlarmSeqLast(neType, neId)
}

// AlarmClearByIds 批量清除告警信息
func (r Alarm) AlarmClearByIds(ids []string, clearUser string) (int64, error) {
	// 检查是否存在
	arr := r.alarmRepository.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 {
			// 状态检查AlarmCode变更告警ID
			alarmCode := parse.Number(v.AlarmCode)
			if alarmCode == constants.ALARM_STATE_CHECK || alarmCode == constants.ALARM_CMD_CHECK || alarmCode == constants.ALARM_LICENSE_CHECK {
				v.AlarmId = fmt.Sprintf("%s%d", v.AlarmCode, v.EventTime.UnixMilli())
			}
			v.AlarmStatus = "0"
			// 告警清除
			clearTime := time.Now()
			v.ClearType = "2"
			v.ClearTime = &clearTime
			v.ClearUser = clearUser
			rows += r.alarmRepository.Update(v)
		}
		return rows, nil
	}
	// 清除失败！
	return 0, fmt.Errorf("clear fail")
}

// AlarmAckByIds 批量确认清除告警信息
func (r Alarm) AlarmAckByIds(ids []string, ackUser string, ackState bool) (int64, error) {
	// 检查是否存在
	arr := r.alarmRepository.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 {
			// 确认清除
			if ackState {
				v.AckState = "1"
			} else {
				v.AckState = "0"
			}
			ackTime := time.Now()
			v.AckTime = &ackTime
			v.AckUser = ackUser
			rows += r.alarmRepository.Update(v)
		}
		return rows, nil
	}
	// 清除失败！
	return 0, fmt.Errorf("ack fail")
}

// InsertAndForword 新增信息并转发通知
func (s Alarm) InsertAndForword(param model.Alarm) string {
	insertId := s.alarmRepository.Insert(param)
	if insertId != "" {
		// 转发通知 TODO
	}
	return insertId
}
