package weaver.interfaces.htsc.fundbusinesspay;

import com.engine.htsc.payment.util.PayUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.Util;
import weaver.hrm.User;
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.UUID;

/**
 * k1810012
 * 资金业务付款办结节点前
 * 保存 银行历史记录: uf_zjywyjlsjl
 * 保存 明细9银行历史记录: uf_DesPayAcct
 */
public class FbpSaveBankAction implements Action {

  private final Log log = LogFactory.getLog(FbpSaveBankAction.class);

  private final String PAY_HISTORY = "uf_zjywyjlsjl"; //银行历史记录
  private final String PAY_ACCOUNT = "uf_DesPayAcct"; //指定付款历史记录

  @Override
  public String execute(RequestInfo requestInfo) {
    RequestManager rm = requestInfo.getRequestManager();
    String rid = requestInfo.getRequestid();
    String tableName = rm.getBillTableName();

    RecordSetTrans rst = new RecordSetTrans();
    try {
      rst.setAutoCommit(false);

      saveHistoryAccount(tableName, rid, PAY_HISTORY, rst);

//      savePayAccount(tableName, rid, PAY_ACCOUNT, rst);

      rst.commit();
      return SUCCESS;
    } catch (Exception e) {
      rst.rollback();
      rm.setMessageid("500");
      rm.setMessagecontent("流程提交失败,请联系管理员!原因:" + e.getMessage());
      return FAILURE_AND_CONTINUE;
    }
  }

  /**
   * 保存 银行历史记录uf_zjywyjlsjl
   */
  public void saveHistoryAccount(String tableName, String rid, String ufTable, RecordSetTrans rst) throws Exception {
    //更新建模表sql(流程转数据)
    int formModeId = PayUtil.getFormModeIdByCubeName(ufTable);
    LocalDateTime now = LocalDateTime.now();
    String ymd = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    String sfm = now.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
    String ny = now.format(DateTimeFormatter.ofPattern("yyyyMM"));
    String is = "insert into " + PAY_HISTORY + "(workcode,WLDWID,WLDWMC,YXZH,KHX,SS,SSMC," +
            "FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE," +
            "MODEDATACREATETIME,MODEUUID) \n" +
            "values(?,?,?,?,?,?,?,?,?,?,?,?,?)";

    log.info(String.format("插入sql:%s", is));

    String ssql = "select t2.ngr,t2.ngrgh,t1.SKDW,t1.YXZH,t1.KHX,t1.SS from " + tableName + "_dt11 t1\n" +
            "left join " + tableName + " t2\n" +
            "on t1.mainid=t2.id\n" +
            "where t2.requestid='" + rid + "'";
    rst.executeQuery(ssql);
    while (rst.next()) {
      String wldwmc = Util.null2String(rst.getString("SKDW"));
      String ngrId = Util.null2String(rst.getString("ngr"));
      if (isRepeat(wldwmc, ngrId, ufTable, "WLDWMC")) {
        log.info(String.format("WLDWMC重复:%s", wldwmc));
        continue;
      }
      String workcode = Util.null2String(rst.getString("ngrgh"));
      String wldwid = Util.null2String(generateWLDWId(ny, ufTable));
      String yxzh = Util.null2String(rst.getString("YXZH"));
      String khx = Util.null2String(rst.getString("KHX"));
      String ss = Util.null2String(rst.getString("SS"));
      String ssmc = PayUtil.cityCodeToName(ss);
      String uuid = UUID.randomUUID().toString();
      int uId = rst.getInt("ngr");
      User user = new User(uId);
      rst.executeUpdate(is, workcode, wldwid, wldwmc, yxzh, khx, ss, ssmc, formModeId, uId,
              user.getType(), ymd, sfm, uuid);
      //权限重构
      int dataId = PayUtil.getDataIdByUUID(uuid);
      ModeRightInfo modeRightInfo = new ModeRightInfo();
      modeRightInfo.editModeDataShare(1, formModeId, dataId);
    }


  }

  /**
   * 保存 指定银行历史记录
   */
  public void savePayAccount(String tableName, String rid, String ufTable, RecordSetTrans rst) throws Exception {

    //更新建模表sql(流程转数据)
    int formModeId = PayUtil.getFormModeIdByCubeName(ufTable);
    LocalDateTime now = LocalDateTime.now();
    String ymd = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    String sfm = now.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
    String is = "insert into " + PAY_ACCOUNT + "(HM,ZH,KHX,DEZFH,CJR," +
            "FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE," +
            "MODEDATACREATETIME,MODEUUID) \n" +
            "values(?,?,?,?,?,?,?,?,?,?,?)";

    String ss = "select t2.ngr,t2.NGRGH,HM,YXZH,KHX,DEZFH from " + tableName + "_DT9 t1\n" +
            "left join " + tableName + " t2\n" +
            "on t1.MAINID=t2.ID\n" +
            "where t2.REQUESTID='" + rid + "'";
    rst.executeQuery(ss);
    while (rst.next()) {
      String hm = Util.null2String(rst.getString("HM"));
      String ngrId = Util.null2String(rst.getString("ngr"));
      if (isRepeat(hm, ngrId, ufTable, "HM")) {
        continue;
      }
      String workcode = Util.null2String(rst.getString("NGRGH"));
      String yxzh = Util.null2String(rst.getString("YXZH"));
      String khx = Util.null2String(rst.getString("KHX"));
      String dezfh = Util.null2String(rst.getString("DEZFH"));

      String uuid = UUID.randomUUID().toString();
      int uId = rst.getInt("ngr");
      User user = new User(uId);
      rst.executeUpdate(is, hm, yxzh, khx, dezfh, workcode, formModeId, uId,
              user.getType(), ymd, sfm, uuid);
      //权限重构
      int dataId = PayUtil.getDataIdByUUID(uuid);
      ModeRightInfo modeRightInfo = new ModeRightInfo();
      modeRightInfo.editModeDataShare(1, formModeId, dataId);
    }
  }

  /**
   * 是否重复,identity为唯一区别
   *
   * @param identity 用于区分的主键
   * @return boolean
   */
  private boolean isRepeat(String name, String ngrId, String ufTable, String identity) {
    boolean flag = false;
    RecordSet rs = new RecordSet();
    rs.execute("select id from " + ufTable + " where " + identity + "='" + name + "' and MODEDATACREATER='" + ngrId + "'");
    if (rs.next()) {
      flag = true;
    }
    return flag;
  }

  /**
   * 生成往来单位id
   *
   * @return string
   */
  private String generateWLDWId(String ny, String uf) {
    RecordSet rs = new RecordSet();
    rs.execute("select * from (\n" +
            "select to_number(substr(WLDWID,-4)) id from " + uf + " where substr(WLDWID,3,6)='" + ny + "' order by id desc\n" +
            ") where rownum=1");
    int id;
    if (rs.next()) {
      id = Util.getIntValue(rs.getString("id")) + 1;
    } else {
      id = 1;
    }
    String strId = id + "";
    while (strId.length() < 4) {
      strId = "0" + strId;
    }
    return "DW" + ny + strId;
  }

}
