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.lang3.Validate;
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.concurrent.RecursiveAction;
import java.util.function.Predicate;

public class SendAppendicesTask extends RecursiveAction {

  private static final PaymentLogger logger = PaymentLoggerFactory.getLogger(SendAppendicesTask.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 SendAppendicesTask(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.getAppendices(), "WfParams.appendices 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>> appendices = wfParams.getAppendices().subList(start, end);
        appendices.parallelStream().distinct().filter(WfParams::qualifyAppendices).forEach(appendix -> {
          //附件
          Map<String, Object> paras = new HashMap<>();
          paras.put("billid", appendix.get(WfParams.REQUEST_MARK));
          paras.put("workcode", rc.getWorkcode(appendix.get(WfParams.CREATE)));
          paras.put("fileids", appendix.get("appendices"));
          logger.info(String.format("appendices langChao in: %s", JSON.toJSONString(paras)));
          String langChaoResponse = htUtil.SendImageWithAffix(paras);
          logger.info(String.format("appendices langChao out: %s", JSON.toJSONString(langChaoResponse)));

        });

      } else {
        // 如果当end与start之间的差大于THRESHOLD时,任务分解
        int middle = (start + end) / 2;
        //捕获异常
        invokeAll(new SendAppendicesTask(start, middle, wfParams), new SendAppendicesTask(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();
  }
}
