package delete_CDR_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 = &DeleteCDRRecordProcessor{
	count: 0,
}

// DeleteCDRRecordProcessor 删除CDR记录
type DeleteCDRRecordProcessor struct {
	count int // 执行次数
}

func (s *DeleteCDRRecordProcessor) 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)

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

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