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

import com.zswl.cloud.springBtach.server.core.service.JobService;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.job.SimpleJob;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * @author wy
 */
@RestController
public class TestSpringBatch {

    @Resource
    private JobService jobService;

    @Resource
    private StepBuilderFactory stepBuilderFactory;

    @GetMapping("/job/order")
    public ExitStatus startJob1(String name) throws Exception {
        return jobService.orderBatch(name);
    }

    @GetMapping("/job/channelOrder")
    public ExitStatus startJob2(String name) throws Exception {
        return jobService.channelOrderBatch(name);
    }

    public Step stepA(){
        //tasklet 执行step逻辑， 类似 Thread()--->可以执行runable接口
        return stepBuilderFactory.get("stepA")
                .tasklet(new Tasklet() {
                    @Override
                    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
                        System.out.println("----------------hahahaha---------------");
                        return RepeatStatus.FINISHED;
                    }
                })
                .build();
    }

    @GetMapping("/job/restart")
    public ExitStatus restart(String name) throws Exception {
        List<Step> stepsFromJobs = jobService.getStepsFromJob(name);
        SimpleJob job = jobService.getJobByName(name);
        for (Step item : stepsFromJobs) {
            // todo 根据条件判断需不需要对默认job进行step的修改
            if (item.getName().contains("B")) {
                job.addStep(stepA());
            }
        }
        return jobService.restJob(job, name);
    }
}
