package performance

import (
	"encoding/json"
	"fmt"
	"nms_nbi/src/framework/cron"
	"nms_nbi/src/framework/logger"
	"nms_nbi/src/framework/utils/date"
	"nms_nbi/src/modules/nms_cxy/service"
	"time"
)

var NewProcessor = &PerformanceProcessor{
	count:              0,
	performanceService: service.NewPerformanceImpl,
}

// 性能指标 队列任务处理
type PerformanceProcessor struct {
	// 执行次数
	count int
	// 性能数据处理服务
	performanceService service.IPerformance
}

func (s *PerformanceProcessor) Execute(data any) (any, error) {
	logger.Infof("执行 %d 次", s.count)
	s.count++

	options := data.(cron.JobData)
	sysJob := options.SysJob
	logger.Infof("重复 %v 任务ID %s", options.Repeat, sysJob.JobID)

	// 读取参数值
	var params struct {
		NeTypes  []string `json:"neTypes"`
		Interval int      `json:"interval"`
	}
	err := json.Unmarshal([]byte(sysJob.TargetParams), &params)
	if err != nil {
		return nil, fmt.Errorf("json params 'interval' err: %v", err)
	}

	// 当前时间减去周期时间
	currentTime := time.Now()
	currentTimeStr := date.ParseDateToStr(currentTime, date.YYYY_MM_DD_HH_MM_SS)
	minus15Minutes := currentTime.Add(-time.Duration(params.Interval) * time.Minute)
	minus15MinutesStr := date.ParseDateToStr(minus15Minutes, date.YYYY_MM_DD_HH_MM_SS)
	// 遍历网元
	for _, neType := range params.NeTypes {
		err = s.performanceService.PerformanceUploadOSS(neType, minus15MinutesStr, currentTimeStr)
		if err != nil {
			return nil, err
		}
	}

	// 返回结果，用于记录执行结果
	result := map[string]any{
		"repeat":  options.Repeat,
		"count":   s.count,
		"jobName": sysJob.JobName,
	}
	return result, nil
}
