package org.jeecg.modules.ctop.job;

import cn.com.ctop.common.module.utils.LoadFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;

@Slf4j
public class BakDataBaseJob implements Job {
    @Value("${spring.datasource.username}")
    private String userName;
    @Value("${spring.datasource.password}")
    private String password;
    @Value("${jeecg.path.bak-database-file}")
    private String filePath;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String currentFileName = filePath + "db-" + DateUtils.formatDate(new Date()) + ".sql";
        String historyFileName = filePath + "db-" + DateUtils.formatDate(DateUtils.addDay(new Date(), -4)) + ".sql";
        String command = "mysqldump jeecg-boot -h 127.0.0.1 -u" + userName + " -p" + password + " --default-character-set=utf8mb4 --result-file=" + currentFileName;
        //1:删除历史数据
        LoadFileUtil.delFile(historyFileName);
        //2:导出当天数据
        Runtime runtime = Runtime.getRuntime();
        Process pro = null;
        try {
            pro = runtime.exec(command);
            int status = pro.waitFor();
            if (status == 0) {
                log.info("数据备份shell脚本执行成功");
            } else {
                log.info("数据备份shell脚本执行失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
