package com.zswl.cloud.springBtach.server.core.service;

import cn.hutool.core.collection.CollectionUtil;
import org.springframework.batch.core.*;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.job.SimpleJob;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author wy
 */
@Service
public class JobService {

    @Resource
    private JobLauncher jobLauncher;

    @Resource
    private Job orderJob;

    @Resource
    private Job chanelOrderJob;

    @Resource
    private JobExplorer jobExplorer;

    @Resource
    private JobRegisterService jobRegisterService;

//    @Autowired
//    public void jobLauncherService(JobLauncher jobLauncher, Job orderJob, Job chanelOrderJob) {
//        this.jobLauncher = jobLauncher;
//        this.orderJob = orderJob;
//        this.chanelOrderJob = chanelOrderJob;
//    }

    public ExitStatus orderBatch(String name) throws Exception {
        JobParameters parameters = new JobParametersBuilder(jobExplorer)
                .getNextJobParameters(orderJob)
                .addString("name", name)
                .toJobParameters();
        jobRegisterService.registerJob("orderBatch", orderJob);
        return jobLauncher.run(orderJob, parameters).getExitStatus();
    }

    public ExitStatus channelOrderBatch(String name) throws Exception {
        JobParameters parameters = new JobParametersBuilder(jobExplorer)
                .getNextJobParameters(chanelOrderJob)
                .addString("name", name)
                .toJobParameters();
        jobRegisterService.registerJob("channelOrderBatch", chanelOrderJob);
        return jobLauncher.run(chanelOrderJob, parameters).getExitStatus();
    }

    public ExitStatus restJob(Job job, String name) throws Exception {
        JobParameters parameters = new JobParametersBuilder(jobExplorer)
                .getNextJobParameters(job)
                .addString("name", name)
                .toJobParameters();
        jobRegisterService.registerJob("restJob", job);
        return jobLauncher.run(job, parameters).getExitStatus();
    }

    public SimpleJob getJobByName(String name) {
        return (SimpleJob) jobRegisterService.getJob(name);
    }

    public List<Step> getStepsFromJob(String name) {
        List<Step> steps = new ArrayList<>();
        SimpleJob simpleJob = getJobByName(name);
        Collection<String> stepNames = simpleJob.getStepNames();
        if (CollectionUtil.isNotEmpty(stepNames)) {
            for (String item : stepNames) {
                steps.add(simpleJob.getStep(item));
            }
        }
        return steps;
    }

}
