package delExpiredNeBackup

import (
	"encoding/json"
	"fmt"

	"ems.agt/lib/dborm"
	"ems.agt/lib/global"
	"ems.agt/lib/log"
	"ems.agt/restagent/config"
	"ems.agt/src/framework/cron"
)

var NewProcessor = &BarProcessor{
	progress: 0,
	count:    0,
}

// bar 队列任务处理
type BarProcessor struct {
	// 任务进度
	progress int
	// 执行次数
	count int
}

type BarParams struct {
	Duration int `json:"duration"`
}

func (s *BarProcessor) Execute(data any) (any, error) {
	log.Infof("count: %d ，progress: %d ", s.count, s.progress)
	s.count++

	options := data.(cron.JobData)
	sysJob := options.SysJob
	var params BarParams
	duration := 60

	err := json.Unmarshal([]byte(sysJob.TargetParams), &params)
	if err == nil {
		duration = params.Duration
	}
	log.Infof("Repeat: %v JobID: %s", options.Repeat, sysJob.JobID)

	// // 实现任务处理逻辑
	// i := 0
	// s.progress = i
	// for i < 5 {
	// 	// 获取任务进度
	// 	progress := s.progress
	// 	log.Infof("jonId: %s => 任务进度：%d", sysJob.JobID, progress)
	// 	// 延迟响应
	// 	time.Sleep(time.Second * 2)
	// 	// 程序中途执行错误
	// 	if i == 3 {
	// 		// arr := [1]int{1}
	// 		// arr[i] = 3
	// 		// fmt.Println(arr)
	// 		// return "i = 3"
	// 		panic("程序中途执行错误")
	// 	}
	// 	i++
	// 	// 改变任务进度
	// 	s.progress = i
	// }
	where := fmt.Sprintf("NOW()>ADDDATE(`create_time`,interval %d day)", duration)
	affected, err := dborm.XormDeleteDataByWhere(where, "ne_backup")
	if err != nil {
		//		panic(fmt.Sprintf("Failed to XormDeleteDataByWhere:%v", err))
		return nil, err
	}

	// delete expired files in backup directory
	// todo ...
	// command := fmt.Sprintf("find . -name '*.zip' -mtime +%d -type f -print | xargs rm -rf", duration)

	command := fmt.Sprintf("%s/rmexpfiles.sh %s %d", config.GetYamlConfig().OMC.BinDir, config.GetYamlConfig().OMC.Backup, duration)

	log.Trace("command:", command)
	out, err := global.ExecCmd(command)
	if err != nil {
		log.Error("Faile to exec command:", err)
		return nil, err
	}
	log.Tracef("command output:%s", out)

	// 返回结果，用于记录执行结果
	return map[string]any{
		"msg":       "success",
		"cmdoutput": string(out),
		"affected":  affected,
	}, nil
}
