package ne_alarm_state_check

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/tsmask/go-oam"

	"be.ems/src/framework/constants"
	"be.ems/src/framework/cron"
	"be.ems/src/framework/logger"
	"be.ems/src/framework/utils/parse"
	neModel "be.ems/src/modules/ne/model"
	neService "be.ems/src/modules/ne/service"
	oamService "be.ems/src/modules/oam/service"
)

var NewProcessor = &NeAlarmStateCheckProcessor{
	neInfoService: neService.NewNeInfo,
	count:         0,
}

// NeAlarmStateCheckProcessor 网元告警状态检查
type NeAlarmStateCheckProcessor struct {
	neInfoService *neService.NeInfo // 网元信息服务
	count         int               // 执行次数
}

// alarmParams 告警参数
type alarmParams struct {
	AlarmTitle        string `json:"alarmTitle"`        // NE State Check Alarm
	AlarmType         string `json:"alarmType"`         // EquipmentAlarm=2
	OrigSeverity      string `json:"origSeverity"`      // Major=2
	SpecificProblem   string `json:"specificProblem"`   // alarm cause: the system state of target NE has not been received
	SpecificProblemID string `json:"specificProblemId"` // AC10000
	AddInfo           string `json:"addInfo"`

	// === 非参数字段 ===
	AlarmId string // 告警ID
}

func (s *NeAlarmStateCheckProcessor) Execute(data any) (any, error) {
	s.count++ // 执行次数加一
	options := data.(cron.JobData)
	sysJob := options.SysJob
	logger.Infof("重复:%v 任务ID:%d  执行次数:%d", options.Repeat, sysJob.JobId, s.count)
	// 返回结果，用于记录执行结果
	result := map[string]any{
		"count": s.count,
	}

	// 读取参数值
	var params alarmParams
	err := json.Unmarshal([]byte(sysJob.TargetParams), &params)
	if err != nil {
		return nil, fmt.Errorf("json params err: %v", err)
	}

	neList := s.neInfoService.Find(neModel.NeInfo{}, true, false)
	for _, neInfo := range neList {
		if neInfo.CreateTime == 0 {
			continue
		}

		// 网元在线状态
		isOnline := parse.Boolean(neInfo.ServerState["online"])
		// 告警ID
		params.AlarmId = fmt.Sprintf("%d%d", constants.ALARM_STATE_CHECK, neInfo.CreateTime)

		// 告警状态
		alarmStatus := oam.ALARM_STATUS_ACTIVE
		if isOnline {
			alarmStatus = oam.ALARM_STATUS_CLEAR
		}
		// 创建告警
		alarm := oam.Alarm{
			NeUid:             neInfo.RmUID,                // 网元唯一标识
			AlarmTime:         time.Now().UnixMilli(),      // 事件产生时间
			AlarmId:           params.AlarmId,              // 告警ID 唯一，清除时对应
			AlarmCode:         constants.ALARM_STATE_CHECK, // 告警状态码
			AlarmType:         params.AlarmType,            // 告警类型
			AlarmTitle:        params.AlarmTitle,           // 告警标题
			PerceivedSeverity: params.OrigSeverity,         // 告警级别
			AlarmStatus:       alarmStatus,                 // 告警状态
			SpecificProblem:   params.SpecificProblem,      // 告警问题原因
			SpecificProblemID: params.SpecificProblemID,    // 告警问题原因ID
			AddInfo:           params.AddInfo,              // 告警辅助信息
			LocationInfo:      "NE State: Heartbeat",       // 告警定位信息
		}
		if err = oamService.NewAlarm.Resolve(alarm); err == nil {
			result[neInfo.RmUID] = "state alarm"
		}
	}

	// 返回结果，用于记录执行结果
	return result, nil
}
