package weaver.interfaces.htsc.payment;

import com.alibaba.fastjson.JSONObject;
import com.engine.htsc.common.utils.DoubleUtil;
import com.engine.htsc.payment.pojo.InvoiceData;
import org.apache.commons.collections4.CollectionUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.util.*;
import java.util.stream.Collectors;


/**
 * k1810012
 * <p>
 * 票据汇总action
 * 提交节点后,数据用后台方式重新计算一次
 */
public class BillSummaryAction extends BaseBean implements Action {

  @Override
  public String execute(RequestInfo requestInfo) {
    String rid = requestInfo.getRequestid();
    RequestManager rm = requestInfo.getRequestManager();
    String tableName = rm.getBillTableName();
    writeLog(String.format("票据汇总,requestid:%s; tableName=%s", rid, tableName));

    RecordSet rs = new RecordSet();


    try {
      String sql = "select t1.mainid,t1.FPLX,t1.JSHJ,t1.SE from " + tableName + "_DT5 t1\n" +
              "left join " + tableName + " t2\n" +
              "on t1.MAINID=t2.ID\n" +
              "where t2.REQUESTID=?";

      rs.executeQuery(sql, rid);

      List<InvoiceData> dataList = new ArrayList<>();
      String mainid = "";
      while (rs.next()) {
        mainid = rs.getString("mainid");
        InvoiceData invoiceData = new InvoiceData();
        invoiceData.setType(Util.null2String(rs.getString("FPLX")));
        invoiceData.setPriceTax(Util.null2String(rs.getString("JSHJ"), "0.00"));
        invoiceData.setTaxes(Util.null2String(rs.getString("SE"), "0.00"));
        dataList.add(invoiceData);
      }

      //表6同步汇总
      sql = "select t1.mainid,t1.FPLX,t1.KPJE,t1.SE from " + tableName + "_DT6 t1\n" +
              "left join " + tableName + " t2\n" +
              "on t1.MAINID=t2.ID\n" +
              "where t2.REQUESTID=?";
      rs.executeQuery(sql, rid);
      while (rs.next()) {
        InvoiceData invoiceData = new InvoiceData();
        invoiceData.setType(Util.null2String(rs.getString("FPLX")));
        invoiceData.setPriceTax(Util.null2String(rs.getString("KPJE"), "0.00"));
        invoiceData.setTaxes(Util.null2String(rs.getString("SE"), "0.00"));
        dataList.add(invoiceData);
      }

      //分组数据
      List<InvoiceData> packetData = dataList.stream().collect(Collectors.groupingBy(InvoiceData::getType,
              Collectors.reducing((sum, data) ->
                      new InvoiceData(sum.getType(),
                              String.valueOf(DoubleUtil.add(sum.getPriceTax(), data.getPriceTax(), 2)),
                              String.valueOf(DoubleUtil.add(sum.getTaxes(), data.getTaxes(), 2))))
      )).values().stream().map(Optional::get).collect(Collectors.toList());

      writeLog(String.format("packetData:%s", JSONObject.toJSONString(packetData)));

      //批量插入
      savePacketData(packetData, tableName, mainid);

      return SUCCESS;
    } catch (Exception e) {
      rm.setMessagecontent("票据汇总信息计算错误,原因:" + e.getMessage());
      rm.setMessageid("500");
      return FAILURE_AND_CONTINUE;

    }

  }

  /**
   * 删除后 批量插入
   *
   * @param packetData 数据
   * @throws Exception 错误信息
   */
  private void savePacketData(List<InvoiceData> packetData, String tableName, String mainId) throws Exception {
    if (CollectionUtils.isNotEmpty(packetData)) {
      RecordSetTrans rst = new RecordSetTrans();
      rst.setAutoCommit(false);
      String save = "insert into " + tableName + "_DT7 (MAINID,JSHJZE,BHSHJ,SJHJ,PJLX)\n" +
              "values(?,?,?,?,?)";
      List<List<Object>> paramList = new ArrayList<>();
      packetData.forEach(item -> {
        List<Object> valueList = new ArrayList<>();
        valueList.add(mainId);
        valueList.add(item.getPriceTax()); //价税
        valueList.add(String.valueOf(DoubleUtil.sub(item.getPriceTax(), item.getTaxes(), 2))); //价
        valueList.add(item.getTaxes()); //税
        valueList.add(item.getType());
        paramList.add(valueList);
      });

      try {
        rst.executeUpdate("delete " + tableName + "_DT7 where MAINID=?", mainId);
        rst.executeBatchSql(save, paramList);
        rst.commit();
      } catch (Exception e) {
        rst.rollback();
        throw new Exception("savePacketData error:" + e.getMessage());
      }

    }

  }
}
