package cn.datax.service.data.quality.schedule.task;

import cn.datax.common.core.DataConstant;
import cn.datax.service.data.quality.api.entity.CheckRuleEntity;
import cn.datax.service.data.quality.service.CheckRuleService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component("qualityTask")
public class QualityTask {

    @Autowired
    private CheckRuleService checkRuleService;

    public void task(Map map) {
        System.out.println("执行批次：" + map);
        // 获取可执行的核查规则
        List<CheckRuleEntity> list = checkRuleService.list(Wrappers.<CheckRuleEntity>lambdaQuery().eq(CheckRuleEntity::getStatus, DataConstant.TrueOrFalse.TRUE.getKey()));
        int poolSize = list.size();
        // 定义固定长度的线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(poolSize, poolSize, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>(16),
                new BasicThreadFactory.Builder().namingPattern("executor-schedule-pool-%d").daemon(true).build());
        // 定义计数器
        final CountDownLatch latch = new CountDownLatch(poolSize);
        list.stream().forEach(s -> {
            threadPoolExecutor.execute(() -> {
                log.info(s.getRuleName() + ":" + LocalDateTime.now());
                latch.countDown();
            });
        });
        // 主线程阻塞，等待所有子线程执行完成
        try {
            latch.await();
        } catch (InterruptedException e) {}
        // 关闭线程池
        threadPoolExecutor.shutdown();
    }
}
