package ne_config_backup

import (
	"fmt"
	"path/filepath"

	"be.ems/src/framework/cron"
	"be.ems/src/framework/logger"
	neModel "be.ems/src/modules/ne/model"
	neService "be.ems/src/modules/ne/service"
	neDataService "be.ems/src/modules/ne_data/service"
)

var NewProcessor = &NeConfigBackupProcessor{
	neConfigBackupService: neService.NewNeConfigBackup,
	neInfoService:         neService.NewNeInfo,
	backupService:         neDataService.NewBackup,
	count:                 0,
}

// NeConfigBackupProcessor 网元配置文件定期备份
type NeConfigBackupProcessor struct {
	neConfigBackupService *neService.NeConfigBackup // 网元配置文件备份记录服务
	neInfoService         *neService.NeInfo         // 网元信息服务
	backupService         *neDataService.Backup     // 备份相关服务
	count                 int                       // 执行次数
}

func (s *NeConfigBackupProcessor) 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,
	}

	neList := s.neInfoService.Find(neModel.NeInfo{}, false, false)
	for _, neInfo := range neList {
		neTypeAndId := fmt.Sprintf("%s_%s", neInfo.NeType, neInfo.NeId)
		// 将网元文件备份到本地
		zipFilePath, err := s.neConfigBackupService.FileNeToLocal(neInfo)
		if err != nil {
			result[neTypeAndId] = err.Error()
			continue
		}

		// 新增备份记录
		item := neModel.NeConfigBackup{
			NeType:   neInfo.NeType,
			NeId:     neInfo.NeId,
			Name:     filepath.Base(zipFilePath),
			Path:     zipFilePath,
			CreateBy: "system",
		}
		rows := s.neConfigBackupService.Insert(item)
		if rows <= 0 {
			result[neTypeAndId] = "failed"
			continue
		}

		msg := "ok"
		// 上传到FTP服务器
		if err := s.backupService.FTPPushFile(zipFilePath, ""); err != nil {
			result[neTypeAndId] = msg + ", ftp err:" + err.Error()
		}
		result[neTypeAndId] = msg
	}

	return result, nil
}
