package delete_kpi_record

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

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

var NewProcessor = &DeleteKPIRecordProcessor{
	count: 0,
}

// DeleteKPIRecordProcessor 删除KPI记录
type DeleteKPIRecordProcessor struct {
	count int // 执行次数
}

func (s *DeleteKPIRecordProcessor) 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
		NeList    []string `json:"neList"`    // ne list
	}
	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  ")
	}
	if len(params.NeList) <= 0 {
		return nil, fmt.Errorf("params neList less than 0  ")
	}

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

	for _, neType := range params.NeList {
		neTypeLower := strings.ToLower(neType)

		// KPI数据表
		kpiTableName := fmt.Sprintf("kpi_report_%s", neTypeLower)
		kpiTx := db.DB("").Table(kpiTableName).Where("created_at < ?", ltTime)
		if err := kpiTx.Delete(nil).Error; err != nil {
			result[neTypeLower] = err.Error()
		} else {
			result[neTypeLower] = kpiTx.RowsAffected
		}

		// KPI自定义数据表
		kpicTableName := fmt.Sprintf("kpi_c_report_%s", neTypeLower)
		kpicTx := db.DB("").Table(kpicTableName).Where("created_at < ?", ltTime)
		if err := kpicTx.Delete(nil).Error; err != nil {
			result["c_"+neTypeLower] = err.Error()
		} else {
			result["c_"+neTypeLower] = kpicTx.RowsAffected
		}

	}

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