package weaver.interfaces.htsc.cus.optimization;

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


/**
 * k1810012
 * 生产实际行程
 * <p>
 * 反馈节点前,将明细3数据同步到明细4中 type = 1
 * <p>
 * 退回拟稿时,清空明细4 type = 0
 */
public class GenerateActualTripAction implements Action {

  private String type = "";

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

  @Override
  public String execute(RequestInfo requestInfo) {
    RequestManager rm = requestInfo.getRequestManager();
    String status = rm.getStatus();
    String tableName = rm.getBillTableName();
    String rid = requestInfo.getRequestid();
    log.info(String.format("生成实际行程: requestid:%s; status:%s; type:%s", rid, status, type));

    RecordSet rs = new RecordSet();
    RecordSetTrans rst = new RecordSetTrans();
    rst.setAutoCommit(false);
    try {
      rs.executeQuery("select ID,XDFHSJ from " + tableName + " where REQUESTID=?", rid);
      String mainid = "";
      String backTime = "";
      if (rs.next()) {
        mainid = rs.getString("ID");
        backTime = rs.getString("XDFHSJ");
      }

      if ("".equals(type)) {
        throw new Exception("提交类型type未维护,请联系管理员!");
      }

      if (StringUtils.isBlank(mainid)) {
        throw new Exception("明细数据异常,请联系管理员!");
      }

      //退回
      if ("0".equals(type)) {
        log.info(String.format("流程退回,清空明细4; mainid=%s", mainid));
        rs.executeUpdate("delete " + tableName + "_DT4 where MAINID=?", mainid);
      }

      //反馈节点前
      if ("1".equals(type)) {
        //先删除再新增
        rs.executeUpdate("delete " + tableName + "_DT4 where MAINID=?", mainid);
        rst.executeUpdate("INSERT INTO " + tableName + "_DT4\n" +
                "(MAINID,CFDGN,MDDGN,CFDHW,MDDHW,CFSJ,FHSJ,CFDBB,MDDBB,SFBC)\n" +
                "SELECT MAINID,CFDGN,MDDGN,CFDHW,MDDHW,CFSJ,FHSJ,CFDBB,MDDBB,SFBC\n" +
                "FROM " + tableName + "_DT3 where MAINID=?", mainid);
        rst.commit();
      }
      return SUCCESS;
    } catch (Exception e) {
      rst.rollback();
      rm.setMessagecontent("在处理实际行程表单时发生错误! 原因:" + e.getMessage());
      rm.setMessageid("500");
      return FAILURE_AND_CONTINUE;
    }

  }

  public String getType() {
    return type;
  }

  public void setType(String type) {
    this.type = type;
  }

  public Log getLog() {
    return log;
  }
}
