package weaver.interfaces.htsc.fundtrans;

import com.engine.htsc.payment.util.PayUtil;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.fundbusinesspay.FbpSaveBankAction;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * k1810012
 * 办结节点前
 * 保存 银行历史记录: uf_zjywyjlsjl(同资金业务付款,表数据来源不一致)
 */
public class SaveToBankHistory4FundTrans extends BaseBean implements Action {

  private final String bankRecordTb = "uf_zjywyjlsjl";

  @Override
  public String execute(RequestInfo requestInfo) {
    RequestManager rm = requestInfo.getRequestManager();
    String rid = requestInfo.getRequestid();
    String tableName = rm.getBillTableName();
    int uid = rm.getUserId();
    int userType = rm.getUserType();
    writeLog(String.format("内部资金调拨写入银行历史记录:rid:%s; billId:%s;", rid, tableName));
    try {
      batchSave(tableName, rid, bankRecordTb, uid, userType);
      return SUCCESS;
    } catch (Exception e) {
      rm.setMessageid("500");
      rm.setMessagecontent("流程提交失败,转入银行卡数据表失败!原因:" + e.getMessage());
      return Action.FAILURE_AND_CONTINUE;
    }
  }

  /**
   * 批量插入
   */
  private void batchSave(String tableName, String rid, String ufTableName, int uid, int userType) throws Exception {
    int formModeId = PayUtil.getFormModeIdByCubeName(ufTableName);
    ResourceComInfo rc = new ResourceComInfo();
    LocalDateTime now = LocalDateTime.now();
    String date = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    String time = now.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
    RecordSetTrans rst = new RecordSetTrans();
    rst.setAutoCommit(false);
    String sql = "select t1.HM,t1.ZH,t1.KHX,t2.NGR from " + tableName + "_DT2 t1 \n" +
            "left join " + tableName + " t2\n" +
            "on t1.MAINID=t2.ID\n" +
            "where t2.REQUESTID=?";
    rst.executeQuery(sql, rid);

    List<List<Object>> valueList = new ArrayList<>();
    List<List<Object>> deDuplicationList = new ArrayList<>();
    List<Object> paramList;
    while (rst.next()) {
      paramList = new ArrayList<>();
      String uuid = UUID.randomUUID().toString();
      paramList.add(Util.null2String(rc.getWorkcode(rst.getString("NGR"))));
      paramList.add(Util.null2String(rst.getString("HM")));
      paramList.add(Util.null2String(rst.getString("ZH")));
      paramList.add(Util.null2String(rst.getString("KHX")));
      paramList.add(formModeId);
      paramList.add(uid);
      paramList.add(userType);
      paramList.add(date);
      paramList.add(time);
      paramList.add(uuid);

      valueList.add(paramList);
    }
    valueList = doDeDuplication(valueList, bankRecordTb);

    String updateSql = "insert into " + ufTableName + "(workcode,WLDWMC,YXZH,KHX," +
            "FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE," +
            "MODEDATACREATETIME,MODEUUID) \n" +
            "values(?,?,?,?,?,?,?,?,?,?)";
    rst.executeBatchSql(updateSql, valueList);

    for (List<Object> list : valueList) {
      String uuid = (String) list.get(9);
      int dataId = PayUtil.getDataIdByUUID(uuid);
      ModeRightInfo modeRightInfo = new ModeRightInfo();
      modeRightInfo.editModeDataShare(1, formModeId, dataId);
    }

  }

  /**
   * 去重重复数据
   */
  private List<List<Object>> doDeDuplication(List<List<Object>> valueList, String ufTable) throws Exception {
    List<List<Object>> deDupList = new ArrayList<>();
    RecordSet rs = new RecordSet();
    String sql = String.format("select WORKCODE num from %s where YXZH=? and WORKCODE=?", ufTable);
    for (List<Object> list : valueList) {
      String workCode = (String) list.get(0);
      String account = (String) list.get(2);
      rs.executeQuery(sql, account, workCode);
      if (rs.next() && rs.getCounts() <= 0) {
        deDupList.add(list);
      }
    }
    return deDupList;
  }

}
