package com.zswl.cloud.springBtach.server.core.job.standard;

import com.github.microservice.auth.client.content.ResultContent;
import com.zhongshu.payment.client.model.payment.CreateResponseModel;
import com.zhongshu.payment.client.model.payment.zswl.CreatePayment2Model;
import com.zhongshu.payment.client.service.v2.PaymentService2;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
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.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;

@Configuration
public class PaymentStep {

    ThreadLocal<ResultContent> resultContent = new ThreadLocal<>();
    ThreadLocal<CreatePayment2Model> parameter = new ThreadLocal<>();
    @Resource
    private JobBuilderFactory jobBuilderFactory;
    @Resource
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    PaymentService2 paymentService2;

    @Lazy
    @Autowired
    PaymentStep paymentStep;

    @Bean
    public Tasklet paymentCommonTasklet() {
        return new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
                resultContent.remove();
                ResultContent<CreateResponseModel> createResponseModelResultContent = paymentService2.creatPayOrder(parameter.get());
                resultContent.set(createResponseModelResultContent);


                return RepeatStatus.FINISHED;
            }
        };
    }

    @Bean
    public Step paymentCommonStep() {
        //tasklet 执行step逻辑， 类似 Thread()--->可以执行runable接口
        return stepBuilderFactory.get("paymentCommonTasklet")
                .tasklet(paymentCommonTasklet())
                .build();
    }

    @Bean
    public Job creatPayment() {
        return jobBuilderFactory
                .get("creatOrder")
                .start(paymentStep.paymentCommonStep())
                .incrementer(new RunIdIncrementer())
                .build();
    }


}
