package weaver.interfaces.htsc.financialadjustment;

import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * k1810012
 *
 * 取明细表3的dcbm调出部门、drbm调入部门与uf_cwkhtz表中sdbm匹配,取jhcwbshr字段
 * dcbm调出部门、drbm调入部门需要过滤掉计划财务部(16)
 *
 */
public class ApproveAction implements Action {

  @Override
  public String execute(RequestInfo requestInfo) {
    RecordSet rs = new RecordSet();
    String rid = requestInfo.getRequestid();
    RequestManager rm = requestInfo.getRequestManager();
    String tableName = rm.getBillTableName();
    int billid = rm.getBillid();
    rs.writeLog(String.format("ApproveAction -- requestid:%s; billid:%s;", rid, billid));
    try {
      List<String> departs = new ArrayList<>();
      rs.executeQuery("SELECT DCBM,DRBM FROM "+tableName+"_dt3 where mainid=?", billid);
      while (rs.next()) {
        departs.add(Util.null2String(rs.getString("DCBM")));
        departs.add(Util.null2String(rs.getString("DRBM")));
      }
      String departss = departs.stream()
              .distinct()
              .filter(StringUtils::isNotBlank)
              .filter(d -> !d.equals("16")).collect(Collectors.joining("','"));
      rs.executeQuery("SELECT SDBM,JHCWBSHR FROM uf_cwkhtz WHERE SDBM IN ('"+departss+"')");
      List<String> shrs = new ArrayList<>();
      while (rs.next()) {
        shrs.add(Util.null2String(rs.getString("JHCWBSHR")));
      }
      String shrss = shrs.stream()
              .distinct()
              .filter(StringUtils::isNotBlank)
              .collect(Collectors.joining(","));
      rs.writeLog(String.format("查询审核人,SDBM:%s; shrs:%s", departss, shrss));
      boolean b = rs.executeUpdate(
              "UPDATE " + tableName + " set jhcwbshr='" + shrss + "' WHERE ID =?", billid);
      
      rs.writeLog("更新审批链:" + b);
      return SUCCESS;
    } catch (Exception e) {
      rm.setMessagecontent( "节点任务,ApproveAction出现异常,请联系管理员!");
      rs.errorLog("节点任务,ApproveAction出现异常", e);
      return FAILURE_AND_CONTINUE;
    }
  }
}
