package weaver.interfaces.htsc.payment.common.pdfprocess;

import com.engine.htsc.payment.log.PaymentLogger;
import com.engine.htsc.payment.log.PaymentLoggerFactory;
import com.engine.htsc.payment.util.AssertUtil;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * pdf生产线程
 *
 * 中间表 uf_SyncGalaxy 生产数据
 *
 * @author K1810012
 */
public class PdfProducer implements Runnable {
  private static final PaymentLogger LOGGER = PaymentLoggerFactory.getLogger(PdfProducer.class);
  private PDFBizProcessor bizProcessor;
  private LinkedBlockingDeque<Runnable> consumer;
  private ThreadPoolExecutor executor;

  public PdfProducer(PDFBizProcessor bizProcessor, LinkedBlockingDeque<Runnable> consumer, ThreadPoolExecutor executor) {
    this.bizProcessor = bizProcessor;
    this.consumer = consumer;
    this.executor = executor;
  }

  @Override
  public void run() {
    while (true) {
      List<SyncPdf> syncPDFs = bizProcessor.queryUnSyncPdfList(10);
      try {
        if (AssertUtil.isNotEmpty(syncPDFs)) {
          //更改状态数据为处理中
          String ids = syncPDFs.stream().map(SyncPdf::getId).collect(Collectors.joining("','"));
          bizProcessor.modifySyncStatus(PdfStatusEnum.SYNCING, ids);
          PdfConsumer pdfConsumer = (PdfConsumer) consumer.take();
          pdfConsumer.setData(syncPDFs);
          executor.execute(pdfConsumer);
        } else {
          //没有数据,睡眠10s
          TimeUnit.SECONDS.sleep(10);
        }
      } catch (Exception e) {
        LOGGER.error("生产者异常===>" + e);
      }
    }
  }

}
