package delete_alarm_record

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

	"be.ems/src/framework/cron"
	"be.ems/src/framework/database/db"
	"be.ems/src/framework/logger"
)

var NewProcessor = &DeleteAlarmRecordProcessor{
	count: 0,
}

// DeleteAlarmRecordProcessor 删除告警记录
type DeleteAlarmRecordProcessor struct {
	count int // 执行次数
}

func (s *DeleteAlarmRecordProcessor) 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 struct {
		StoreDays int `json:"storeDays"` // store days
	}
	err := json.Unmarshal([]byte(sysJob.TargetParams), &params)
	if err != nil {
		return nil, fmt.Errorf("json params err: %v", err)
	}
	if params.StoreDays < 0 {
		return nil, fmt.Errorf("params storeDays less than 0  ")
	}

	// 计算删除时间
	ltTime := time.Now().AddDate(0, 0, -params.StoreDays).UnixMilli()

	// 告警表
	alarmTx := db.DB("").Table("alarm").Where("timestamp < ?", ltTime)
	if err := alarmTx.Delete(nil).Error; err != nil {
		result["alarm"] = err.Error()
	} else {
		result["alarm"] = alarmTx.RowsAffected
	}

	// 告警事件表
	alarmEventTx := db.DB("").Table("alarm_event").Where("timestamp < ?", ltTime)
	if err := alarmEventTx.Delete(nil).Error; err != nil {
		result["alarm_event"] = err.Error()
	} else {
		result["alarm_event"] = alarmEventTx.RowsAffected
	}

	// 告警日志表
	alarmLogTx := db.DB("").Table("alarm_log").Where("created_at < ?", ltTime)
	if err := alarmLogTx.Delete(nil).Error; err != nil {
		result["alarm_log"] = err.Error()
	} else {
		result["alarm_log"] = alarmLogTx.RowsAffected
	}

	// 告警转发日志表
	alarmForwardLogTx := db.DB("").Table("alarm_forward_log").Where("created_at < ?", ltTime)
	if err := alarmForwardLogTx.Delete(nil).Error; err != nil {
		result["alarm_forward_log"] = err.Error()
	} else {
		result["alarm_forward_log"] = alarmForwardLogTx.RowsAffected
	}

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