package com.engine.htsc.payment.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import com.engine.htsc.payment.enums.Sequences;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;

public class CoWfUtil extends BaseBean {

  /**
   * 从序列中获取流水号
   *
   * @param sequences {@link Sequences}
   * @return 流水号(000001-999999)
   */
  private static String getSerialNoFromSequence(Sequences sequences) throws Exception {
    RecordSet rs = new RecordSet();
    rs.executeQuery(String.format("select %s.nextval from DUAL", sequences.toString()));
    String serialNo = "";
    if (rs.next()) {
      serialNo = rs.getString("nextval");
    }
    StringBuffer mark = new StringBuffer(serialNo);
    while (mark.length() < 6) {
      mark.insert(0, "0");
    }
    return mark.toString();

  }

  /**
   * 网报流程通用流程编号
   * 序列实现: NET_REI_WORKFLOW_SEQ
   *
   * @param unNumber 流程简称 如:总部通用付款-zbtyfk
   * @return 流程中文名称+yyyyMM+流水号(000001-999999)
   */
  public static String getRequestMarkByUnNumber(String unNumber, Sequences sequences) throws Exception {
    Assert.notBlank(unNumber, "unNumber为空,流程编号生成失败");

    String workFlowName = "";
    RecordSet rs = new RecordSet();
    String sql = "select WORKFLOWNAME from workflow_base where ISVALID=1 and UNNUMBER=?";
    rs.executeQuery(sql, unNumber.toLowerCase());
    if (rs.next()) {
      workFlowName = Util.null2String(rs.getString("WORKFLOWNAME"));
    }
    Assert.notBlank(workFlowName, "workFlowName为空,流程编号生成失败");
    String ym = DateUtil.format(new Date(), "yyyyMM");

    return String.join("", workFlowName, ym, getSerialNoFromSequence(sequences));


  }

  /**
   * 生成网报流程编号
   *
   * @param workFlowId 流程id
   * @return 流程编号
   */
  public synchronized String createFundBusinessPayRequestMark(String workFlowId) throws Exception {
    try {
      if (StringUtils.isBlank(workFlowId)) {
        throw new Exception("参数workFlowId为空");
      }

      RecordSet rs = new RecordSet();
      int formModeId = PayUtil.getFormModeIdByCubeName("uf_fklcbh");
      String sql = "select WORKFLOWNAME,UNNUMBER from workflow_base where isvalid=1 and ID=?";
      rs.executeQuery(sql, workFlowId);
      String name = ""; //流程中文名称
      String unNumber = ""; //流程唯一字符标识
      if (rs.next()) {
        name = rs.getString("WORKFLOWNAME");
        unNumber = rs.getString("UNNUMBER");
      }

      if (StringUtils.isBlank(name)) {
        throw new Exception("workFlowId没有对应的流程标题");
      }

      StringBuilder mark = new StringBuilder(); //流程编码
      String modeUuid = ""; //建模同步uuid

      LocalDateTime now = LocalDateTime.now();
      String yM = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
      rs.executeQuery("select id,lsh,MODEUUID from uf_fklcbh where ny = '" + yM + "' and LCLX='" + unNumber + "'");
      if (rs.next()) {
        //更新
        int num = Util.getIntValue(rs.getString("lsh")) + 1;
        int id = Util.getIntValue(rs.getString("id"));
        modeUuid = Util.null2String(rs.getString("MODEUUID"));
        String updateSql = "update uf_fklcbh set lsh=? where id=?";
        rs.executeUpdate(updateSql, num, id);
        mark = new StringBuilder(num + "");
        while (mark.length() < 6) {
          mark.insert(0, "0");
        }
        mark = new StringBuilder(name + now.format(DateTimeFormatter.ofPattern("yyyyMM")) + mark);
      } else {
        String userId = "";
        String userType = "0";
        String createDate = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String createTime = now.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
        String insertSql = "insert into uf_fklcbh" +
                "(FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE," +
                "MODEDATACREATETIME,MODEUUID,LSH,NY,LCLX) \n" +
                "values(?,?,?,?,?,?,?,?,?)";
        String uuid = UUID.randomUUID().toString();
        modeUuid = uuid;
        rs.executeUpdate(insertSql, formModeId, userId, userType,
                createDate, createTime, uuid, "1", yM, unNumber);
        mark = new StringBuilder(name + now.format(DateTimeFormatter.ofPattern("yyyyMM")) + "000001");
      }

      //建模权限重构
      int dataId = PayUtil.getDataIdByUUID(modeUuid);
      ModeRightInfo modeRightInfo = new ModeRightInfo();
      modeRightInfo.editModeDataShare(1, formModeId, dataId);

      return mark.toString();
    } catch (Exception e) {
      writeLog("生成流程编号失败,catch:" + e.getMessage());
      throw new Exception(e.getMessage());
    }

  }
}
