package weaver.interfaces.htsc.payment;

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.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;

/**
 * author: k1810012
 * description:
 * 总部付款流程办结节点前，
 * 流程数据转入建模
 * <p>
 * 总部付款流程: uf_yhlsjl （银行历史记录）
 * 分支机构付款流程: uf_fzjgyhlsjl （银行历史记录）
 * 资金业务付款: uf_zjywyjlsjl （银行历史记录）
 * <p>
 * 维护字段: ufTable 指定银行历史记录建模表
 */
public class EndNodeConvertInfoToCube implements Action {

  /**
   * 默认为总部付款建模表
   */
  private String ufTable = "uf_yhlsjl";

  public String getUfTable() {
    return ufTable;
  }

  public void setUfTable(String ufTable) {
    this.ufTable = ufTable;
  }

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

  @Override
  public String execute(RequestInfo requestInfo) {
    log.info("====总部付款流程办结节点前， EndNodeConvertInfoToCube开始执行==");
    log.info("====当前代转建模表:@" + ufTable + "@");
    RequestManager requestManager = requestInfo.getRequestManager();
    try {
      RecordSet rs = new RecordSet();
      String tableName = requestInfo.getRequestManager().getBillTableName();
      User usr = requestInfo.getRequestManager().getUser();//获取当前操作用户对象
      String requestId = requestInfo.getRequestid();
      //更新建模表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 selectSql = "select t2.ngr,t2.ngrgh,t1.LSJL,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='" + requestId + "'";
      rs.executeQuery(selectSql);
      RecordSet insertRs = new RecordSet();
      String insertSql = "insert into " + ufTable + "(workcode,WLDWID,WLDWMC,YXZH,KHX,SS,SSMC,FORMMODEID,MODEDATACREATER,MODEDATACREATERTYPE,MODEDATACREATEDATE,MODEDATACREATETIME,MODEUUID) \n" +
              "values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
      while (rs.next()) {
        String wldwmc = Util.null2String(rs.getString("SKDW"));
        String ngrId = Util.null2String(rs.getString("ngr"));
        if (isRepeat(wldwmc, ngrId, ufTable)) {
          continue;
        }
        String workcode = Util.null2String(rs.getString("ngrgh"));
        String wldwid = Util.null2String(generateWLDWId(ny));
        String yxzh = Util.null2String(rs.getString("YXZH"));
        String khx = Util.null2String(rs.getString("KHX"));
        String ss = Util.null2String(rs.getString("SS"));
        String ssmc = PayUtil.cityCodeToName(ss);
        String uuid = UUID.randomUUID().toString();
        int uId = rs.getInt("ngr");
        User user = new User(uId);
        insertRs.executeUpdate(insertSql, 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);
      }
      return SUCCESS;
    } catch (Exception e) {
      log.info("异常, " + e);
      requestManager.setMessagecontent("预算接口执行失败!");
      requestManager.setMessageid("5000");
      return FAILURE_AND_CONTINUE;
    }

  }

  /**
   * 生成往来单位id
   *
   * @return string
   */
  public String generateWLDWId(String ny) {
    RecordSet rs = new RecordSet();
    rs.execute("select * from (\n" +
            "select to_number(substr(WLDWID,-4)) id from uf_yhlsjl 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;
  }

  /**
   * 是否重复,SKDW付款单位,创建人,为唯一区别
   *
   * @return boolean
   */
  public boolean isRepeat(String name, String ngrId, String ufTable) {
    boolean flag = false;
    RecordSet rs = new RecordSet();
    rs.execute("select id from " + ufTable + " where WLDWMC='" + name + "' and MODEDATACREATER='" + ngrId + "'");
    if (rs.next()) {
      flag = true;
    }
    return flag;
  }

}
