package weaver.interfaces.htsc.payment;

import weaver.conn.RecordSet;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.util.Arrays;

/**
 * k1810012
 * 发票关联记录
 * 1) 拟稿提交时，新增； 0
 * 2）退回拟稿节点，删除； 1
 * 3）废弃、终止，删除；(同上)
 */
public class PaymentInvoiceRecordAction implements Action {

  //配置,当前状态为提交; 0或空, 提交; 1, 退回到拟稿前;
  private String status;

  //发票记录表
  private final String TABLE = "UF_PJXXGL";
  //需要关联的明细表
  private final String dts = "5,6";

  @Override
  public String execute(RequestInfo requestInfo) {
    RecordSet rs = new RecordSet();
    RequestManager requestManager = requestInfo.getRequestManager();
    String requestId = requestInfo.getRequestid();
    String tableName = requestManager.getBillTableName();
    rs.writeLog(String.format("发票关联记录@reqeustid: %s; status: %s", requestId, status));

    try {
      if ("1".equals(status)) {
        rs.writeLog("回退,去除已关联的发票");
        String delSql = "delete from " + TABLE + " where REQUESTID=?";
        rs.executeUpdate(delSql, requestId);
      } else {
        rs.writeLog("提交,关联发票");
        for (String num : dts.split(",")) {
          String saveSql = "insert into uf_pjxxgl (FPHM,FPDM,FPMC,LCBM,REQUESTID) select t1.FPHM,t1.FPDM,t1.WJID,t2.LCBH,t2.REQUESTID\n" +
                  "from " + tableName + "_DT" + num + " t1\n" +
                  "left join " + tableName + " t2\n" +
                  "on t1.MAINID=t2.ID\n" +
                  "where t2.REQUESTID=?";
          rs.executeUpdate(saveSql, requestId);
        }
      }
      return SUCCESS;
    } catch (Exception e) {
      requestManager.setMessagecontent("节点操作发票关联发生异常!请联系管理员处理,error:" + e);
      requestManager.setMessageid("500");
      return FAILURE_AND_CONTINUE;
    }

  }

  public String getStatus() {
    return status;
  }

  public void setStatus(String status) {
    this.status = status;
  }
}
