package delete_data_record

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

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

var NewProcessor = &DeleteDataRecordProcessor{
	count: 0,
}

// bar 队列任务处理
type DeleteDataRecordProcessor struct {
	count int // 执行次数
}

type optionParams struct {
	TableName string `json:"tableName"` // table name
	ColName   string `json:"colName"`   // column name is timestamp milliseconds
	StoreDays int    `json:"storeDays"` // store days
	WhereSQL  string `json:"whereSQL"`  // extras condition for where
}

func (s *DeleteDataRecordProcessor) 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 optionParams
	err := json.Unmarshal([]byte(sysJob.TargetParams), &params)
	if err != nil {
		return nil, fmt.Errorf("json params err: %v", err)
	}
	if params.TableName == "" {
		return nil, fmt.Errorf("params tableName is empty ")
	}
	if params.ColName == "" {
		return nil, fmt.Errorf("params colName is empty ")
	}
	if params.StoreDays < 0 {
		return nil, fmt.Errorf("params storeDays less than 0  ")
	}
	// 指定表名
	tx := db.DB("").Table(params.TableName)

	if params.StoreDays >= 0 {
		// 计算删除时间
		ltTime := time.Now().AddDate(0, 0, -params.StoreDays).UnixMilli()
		tx = tx.Where(fmt.Sprintf("%s < ?", params.ColName), ltTime)
	}
	if params.WhereSQL != "" {
		tx = tx.Where(params.WhereSQL)
	}

	// 执行删除
	if err := tx.Delete(nil).Error; err != nil {
		return nil, err
	}
	result["affected"] = tx.RowsAffected

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