package com.engine.htsc.payment.model;

import com.alibaba.fastjson.JSON;
import com.engine.htsc.meeting.util.Common;
import com.engine.htsc.payment.log.PaymentLogger;
import com.engine.htsc.payment.log.PaymentLoggerFactory;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.Validate;
import weaver.general.BaseBean;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.cus.HTUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.RecursiveAction;
import java.util.function.Predicate;

public class SendPDFTask extends RecursiveAction {

  private static final PaymentLogger logger = PaymentLoggerFactory.getLogger(SendPDFTask.class);

  private static final int THRESHOLD = 50;
  private int start;
  private int end;
  private ResourceComInfo rc = new ResourceComInfo();
  private WfParams wfParams;
  HTUtil htUtil = new HTUtil();


  public SendPDFTask(int start, int end, WfParams wfParams) throws Exception {
    this.start = start;
    this.end = end;
    this.wfParams = wfParams;
  }

  @Override
  protected void compute() {
    try {
      Validate.notNull(wfParams, "WfParams is null or empty");
      Validate.notEmpty(wfParams.getRequestInfos(), "WfParams.requestInfos list is null or empty,continue...");
      if (end - start < THRESHOLD) {
        logger.info(String.format("[start,end]=[%d,%d] start...", start, end));
        List<Map<String, String>> requestInfos = wfParams.getRequestInfos().subList(start, end);
        requestInfos.parallelStream().distinct().filter(WfParams::qualifyRequestInfo).forEach(requestInfo -> {
          //生成审批单PDF
          String path = Common.saveProcessPDFWithReturnFilePath(wfParams.getModeid(),
              requestInfo.get(WfParams.REQUEST_ID),
              requestInfo.get(WfParams.REQUEST_MARK));
          //浪潮
          Map<String, Object> paras = new HashMap<>();
          paras.put("billid", requestInfo.get(WfParams.REQUEST_MARK));
          paras.put("workcode", rc.getWorkcode(requestInfo.get(WfParams.CREATE)));
          paras.put("filePath", path);
          logger.info(String.format("langChao in: %s", JSON.toJSONString(paras)));
          String langChaoResponse = htUtil.SendImageWithInputStream(paras);
          logger.info(String.format("langChao out: %s", JSON.toJSONString(langChaoResponse)));

        });

      } else {
        // 如果当end与start之间的差大于THRESHOLD时,任务分解
        int middle = (start + end) / 2;
        //捕获异常
        invokeAll(new SendPDFTask(start, middle, wfParams), new SendPDFTask(middle, end, wfParams));
      }

    } catch (Exception e) {
      logger.error(String.format("[start,end]=[%d,%d] occur error", start, end), e);
    }

  }

  private static <T> Predicate<T> not(Predicate<T> t) {
    return t.negate();
  }
}
