package weaver.interfaces.htsc.fundbusinesspay;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import weaver.conn.RecordSetTrans;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

/**
 * k1810012
 * 更新流程标题
 * 拼接应付款日期
 */
public class FbpUpdateTitleAction implements Action {

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

  @Override
  public String execute(RequestInfo requestInfo) {
    RequestManager rm = requestInfo.getRequestManager();
    String tableName = rm.getBillTableName();
    if (StringUtils.isEmpty(tableName)) {
      //流程自动流转,不做拦截
      return SUCCESS;
    }
    String rid = requestInfo.getRequestid();
    RecordSetTrans rst = new RecordSetTrans();
    try {
      rst.setAutoCommit(false);
      String ss = "select t2.YFKRQ,t1.REQUESTNAME from WORKFLOW_REQUESTBASE t1\n" +
              "left join " + tableName + " t2\n" +
              "on t1.REQUESTID=t2.REQUESTID\n" +
              "where t1.REQUESTID=?";
      rst.executeQuery(ss, rid);
      String title = "";
      String date = "";
      if (rst.next()) {
        title = rst.getString("REQUESTNAME");
        date = rst.getString("YFKRQ");
      }
      log.info(String.format("requestName=%s;应付款日期=%s", title, date));
      String newTitle = appendPayDate2Title(title, date);
      log.info(String.format("new requestName=%s", newTitle));

      String sql = "update WORKFLOW_REQUESTBASE set REQUESTNAME='" + newTitle + "' where REQUESTID=?";
      rst.executeUpdate(sql, rid);

      log.info(String.format("更新sql:%s", sql));
      rst.commit();
      return SUCCESS;
    } catch (Exception e) {
      rst.rollback();
      rm.setMessageid("500");
      rm.setMessagecontent("流程更新标题提交失败,请联系管理员!原因: " + e.getMessage());
      return FAILURE_AND_CONTINUE;
    }
  }

  private String appendPayDate2Title(String title, String date) throws Exception {
    if (StringUtils.isBlank(date)) {
      return String.join("-", title, "待定");
    }
    DateTime dt = new DateTime(date);
    String dtStr = dt.toString("yyyy年MM月dd日");
    return String.join("-", title, dtStr);
  }

}
