package com.engine.htsc.trip.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * Created by qlk
 */
public class WeaverUtil {

	private final static LogUtil logUtil = new LogUtil();
	private final static Log log = LogFactory.getLog(WeaverUtil.class);
	public final static String BX = "0";
	public final static String CC = "1";

  /**
   * 根据 UnNumber获取 TableName
   * @param unNumber
   * @return
   */
  public static String getTableNameByUnNumber(String unNumber) {
    RecordSet rs = new RecordSet();
    String sql = "select abs(FORMID) as FORMID from WORKFLOW_BASE where ISVALID=1 and UNNUMBER=?";
    rs.executeQuery(sql, unNumber);
    String formId = "";
    if (rs.next()) {
      formId = Util.null2String(rs.getString("FORMID"));
    }
    return String.join("_", "FORMTABLE_MAIN", formId);
  }

  /**
   * 根据流程表单获取投行项目
   *
   * @param reqId 流程id
   * @return map
   */
  public static Map<String, Object> getItItemByReqId(String reqId) {
    Map<String, Object> item = new HashMap<>();
    RecordSet recordSet = new RecordSet();
    String ccsqTable = getTableNameByRequestId(reqId, recordSet);
    if ("".equals(ccsqTable)) {
      return item;
    }
    String thxm_sql = "select xmjc from " + ccsqTable;
    recordSet.executeQuery(thxm_sql);
    recordSet.next();
    String xmjc = Util.null2String(recordSet.getString("xmjc"));
    if ("".equals(xmjc)) {
      Map<String, Object> paras = new HashMap<>();
      paras.put("projectId", xmjc);
      String projectById = new HTUtil().getProjectById(paras);
      if ("".equals(projectById)) {
        return item;
      }
      JSONObject jsonObject = JSONObject.parseObject(projectById);
      String shortName = jsonObject.getString("shortName");
      item.put("id", xmjc);
      item.put("shortName", shortName);
      item.put("isItProj", shortName);
    } else {
      item.put("id", "");
      item.put("shortName", "");
      item.put("isItProj", "否");
    }
    return item;
  }

	/**
	 * 获取插入表中的数据
	 *
	 * @param fname 流程编号
	 * @return map
	 */
	private static Map<String, Object> getBudgetBody(String fname) {
		String unionReWfid = Util.null2String(new PropBean().getPropName("unionReWfid"));
		String unionReWfidstr = Util.null2String(new PropBean().getWorkflowIdsByUnNumber(unionReWfid));
		List<String> unionReWfidWF = Arrays.asList(unionReWfidstr.split(","));
		String mainTable = WeaverUtil.getTableNameByWfid(Util.getIntValue(unionReWfidWF.get(0)));
		String dt8Table = mainTable + "_dt8";
		String dt9Table = mainTable + "_dt9";
		Map<String, Object> body = new HashMap<>();
		RecordSet rs = new RecordSet();
		String mainId = "";
		String main_sql = "select t1.id,t1.lcbh,t2.requestname,t3.lastname,t4.DEPARTMENTCODE " +
				"from " + mainTable + " t1\n" +
				"left join workflow_requestbase t2\n" +
				"on t1.requestid=t2.requestid\n" +
				"left join hrmresource t3\n" +
				"on t1.ngr=t3.id\n" +
				"left join hrmdepartment t4\n" +
				"on t3.departmentid=t4.id\n" +
				"where t1.lcbh='" + fname + "'";
		logUtil.writeLog("main_sql执行, " + main_sql);
		rs.executeQuery(main_sql);
		if (rs.next()) {
			body.put("FNAME", fname);
			body.put("FBILLTITLE", Util.null2String(rs.getString("requestname")));
			body.put("FPESONNAME", rs.getString("lastname"));
			body.put("FDEPTNUMBER", rs.getString("DEPARTMENTCODE"));
			mainId = Util.null2String(rs.getString("id"));
		}
		logUtil.writeLog("body数据主表基本信息, [" + body + "]");
		String dt8_sql = "select fycdr,yskm as km,ccsqlc from " + dt8Table + " where mainid=" + mainId;
		logUtil.writeLog("dt8_sql执行, " + dt8_sql);
		rs.executeQuery(dt8_sql);
		String km = "";
		String ccsqlc = "";
		List<Map<String, Object>> list = new ArrayList<>();
		while (rs.next()) {
			km = Util.null2String(rs.getString("km")); //科目
			ccsqlc = Util.null2String(rs.getString("ccsqlc")); //出差申请流程reqId(获取it项目)
			list.add(getKjKmChargesWithMap(km, dt9Table, ccsqlc, mainId));
		}
		body.put("list", list);
		logUtil.writeLog("list科目信息, [" + list + "]");
		logUtil.writeLog("body完整数据信息, [" + body + "]");
		return body;
	}

	/**
	 * 插入中间表
	 *
	 * @param fname      流程编号
	 * @param billStatus 单据状态
	 * @param rsd        外部数据源
	 * @return 布尔
	 */
	public static boolean insertBudgetMiddleTable(String fname, String billStatus, RecordSetDataSource rsd) {
		Map<String, Object> budgetBody = getBudgetBody(fname);
		logUtil.writeLog("插入预算表insertBudgetMiddleTable开始执行" + budgetBody);
		List<Map<String, Object>> list = (List<Map<String, Object>>) budgetBody.get("list");
		if (list.size() == 0) {
			logUtil.writeLog("插入预算表中止,因为科目信息为空");
			return false;
		}
		DateTimeFormatter dfOnlyDate = DateTimeFormatter.ofPattern("yyyy");
		DateTimeFormatter dfDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		String FBILLTITLE = (String) budgetBody.get("FBILLTITLE");
		String FPESONNAME = (String) budgetBody.get("FPESONNAME");
		int FBILLSTATUS = Integer.parseInt(billStatus);
		String FDEPTNUMBER = (String) budgetBody.get("FDEPTNUMBER");
		String FCOSTITEMNUM = "86010503";
		String YSND = dfOnlyDate.format(LocalDateTime.now());
		String FBIZDATE = dfDateTime.format(LocalDateTime.now());
		String FITEMDETAILNUM;
		double FSJAMOUNT = 0;
		double FNOTAXAMOUNT;
		double FTAXAMOUNT;
		double FACTUALAMOUNT;
		double FSTANDARDAMOUNT;
		String FOVERWEIGHT = "";
		String ISITITEM = "";
		String ITITEMCODE = "";
		String ITITEMNAME = "";
		String insert_sql = "";
		try {
			for (Map<String, Object> item : list) {
				FITEMDETAILNUM = Util.null2String((String) item.get("FITEMDETAILNUM"));
				FNOTAXAMOUNT = Util.getDoubleValue((String) item.get("FNOTAXAMOUNT"));
				FTAXAMOUNT = Util.getDoubleValue((String) item.get("FTAXAMOUNT"));
				FOVERWEIGHT = (String) item.get("FOVERWEIGHT");
				FACTUALAMOUNT = Util.getDoubleValue((String) item.get("FACTUALAMOUNT"));
				FSTANDARDAMOUNT = Util.getDoubleValue((String) item.get("FSTANDARDAMOUNT"));
				String budgetTableName = new PropBean().getPropName("BudgetTableName");
				insert_sql = "insert into " + budgetTableName +
						" (FNAME,FBILLTITLE,FPESONNAME,FBILLSTATUS,FDEPTNUMBER,WDMC,FITEMDETAILNUM,FCOSTITEMNUM,YSND," +
						"FBIZDATE,FSJAMOUNT,FNOTAXAMOUNT,FTAXAMOUNT,FOVERWEIGHT,FACTUALAMOUNT,FSTANDARDAMOUNT,ISITITEM," +
						"ITITEMCODE,ITITEMNAME) " +
						" values('" + fname + "','" + FBILLTITLE + "','" + FPESONNAME + "'," + FBILLSTATUS + ",'" + FDEPTNUMBER + "'," +
						"'','" + FITEMDETAILNUM + "','" + FCOSTITEMNUM + "','" + YSND + "','" + FBIZDATE + "'," + FSJAMOUNT + "," + FNOTAXAMOUNT + "," + FTAXAMOUNT + "," +
						"'" + FOVERWEIGHT + "'," + FACTUALAMOUNT + "," + FSTANDARDAMOUNT + ",'" + ISITITEM + "','" + ITITEMCODE + "','" + ITITEMNAME + "')";

				rsd.executeSql(insert_sql);
				logUtil.writeLog("insert_sql, [" + insert_sql + "]");
			}
			return true;
		} catch (Exception e) {
			logUtil.writeLog("insertBudgetMiddleTable异常, [" + e + "]");
			return false;
		}
	}

	/**
	 * 更新预算表
	 *
	 * @param fname      流程编号
	 * @param billStatus 单据状态
	 * @param rsd        外部数据源
	 * @return 布尔
	 */
	public static boolean updateBudgetMiddleTable(String fname, String billStatus, RecordSetDataSource rsd) {
		Map<String, Object> budgetBody = getBudgetBody(fname);
		logUtil.writeLog("更新预算表updateBudgetMiddleTable开始执行" + budgetBody);
		List<Map<String, Object>> list = (List<Map<String, Object>>) budgetBody.get("list");
		if (list.size() == 0) {
			logUtil.writeLog("更新预算表中止,因为科目信息为空");
			return false;
		}
		DateTimeFormatter dfOnlyDate = DateTimeFormatter.ofPattern("yyyy");
		DateTimeFormatter dfDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		String FBILLTITLE = (String) budgetBody.get("FBILLTITLE");
		String FPESONNAME = (String) budgetBody.get("FPESONNAME");
		int FBILLSTATUS = Integer.parseInt(billStatus);
		String FDEPTNUMBER = (String) budgetBody.get("FDEPTNUMBER");
		String FCOSTITEMNUM = "86010503";
		String YSND = dfOnlyDate.format(LocalDateTime.now());
		String FBIZDATE = dfDateTime.format(LocalDateTime.now());
		String FITEMDETAILNUM;
		double FSJAMOUNT = 0;
		double FNOTAXAMOUNT;
		double FTAXAMOUNT;
		double FACTUALAMOUNT;
		double FSTANDARDAMOUNT;
		String FOVERWEIGHT = "";
		String ISITITEM = "";
		String ITITEMCODE = "";
		String ITITEMNAME = "";
		String update_sql = "";
		try {
			for (Map<String, Object> item : list) {
				FITEMDETAILNUM = Util.null2String((String) item.get("FITEMDETAILNUM"));
				FNOTAXAMOUNT = Util.getDoubleValue((String) item.get("FNOTAXAMOUNT"));
				FTAXAMOUNT = Util.getDoubleValue((String) item.get("FTAXAMOUNT"));
				FOVERWEIGHT = (String) item.get("FOVERWEIGHT");
				FACTUALAMOUNT = Util.getDoubleValue((String) item.get("FACTUALAMOUNT"));
				FSTANDARDAMOUNT = Util.getDoubleValue((String) item.get("FSTANDARDAMOUNT"));
				String budgetTableName = new PropBean().getPropName("BudgetTableName");
				update_sql = "UPDATE " + budgetTableName + " SET " +
						"FBILLSTATUS=" + FBILLSTATUS + ",FCOSTITEMNUM='" + FCOSTITEMNUM + "',YSND='" + YSND + "'," +
						"FBIZDATE='" + FBIZDATE + "',FSJAMOUNT=" + FSJAMOUNT + ",FNOTAXAMOUNT=" + FNOTAXAMOUNT + ",FTAXAMOUNT=" + FTAXAMOUNT + "," +
						"FOVERWEIGHT='" + FOVERWEIGHT + "',FACTUALAMOUNT=" + FACTUALAMOUNT + ",FSTANDARDAMOUNT=" + FSTANDARDAMOUNT +
						"WHERE FNAME = '" + fname + "' and FITEMDETAILNUM='" + FITEMDETAILNUM + "'";
				rsd.executeSql(update_sql);
				logUtil.writeLog("insert_sql, [" + update_sql + "]");
			}
			return true;
		} catch (Exception e) {
			logUtil.writeLog("updateBudgetMiddleTable异常, [" + e + "]");
			return false;
		}
	}

	/**
	 * 转换人员id为登录id
	 *
	 * @param hrmId 人员id
	 * @param rs    sql执行器
	 * @return 人员登录id
	 */
	public static String convertIdToLoginId(String hrmId, RecordSet rs) {
		String sql = "select loginid from hrmresource where id='" + hrmId + "'";
		rs.execute(sql);
		return rs.next() ? rs.getString("loginid") : "";
	}

	/**
	 * get请求
	 *
	 * @param url
	 * @param headers
	 * @param encode
	 * @return
	 */
	public static String httpGetRaw(String url, Map<String, String> headers, String encode) {
		if (encode == null) {
			encode = "utf-8";
		}
		String content = null;
		CloseableHttpResponse httpResponse = null;
		CloseableHttpClient closeableHttpClient = null;
		try {
			//HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
			closeableHttpClient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(url);
			//设置header
			httpGet.setHeader("Content-type", "application/json");
			if (headers != null && headers.size() > 0) {
				for (Map.Entry<String, String> entry : headers.entrySet()) {
					httpGet.setHeader(entry.getKey(), entry.getValue());
				}
			}
			//响应信息
			httpResponse = closeableHttpClient.execute(httpGet);
			HttpEntity entity = httpResponse.getEntity();
			content = EntityUtils.toString(entity, encode);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpResponse.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {  //关闭连接、释放资源
			closeableHttpClient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}

	/**
	 * 根据 流程ID获取主表名
	 *
	 * @param wfid 流程id
	 * @return 表名
	 */
	public static String getTableNameByWfid(int wfid) {
		String tableName = "";
		try {
			if (!"".equals(wfid)) {
				String sql = "select t1.tablename from workflow_bill t1,workflow_base t2 where t1.id = t2.formid and t2.id = " + wfid;
				RecordSet rs = new RecordSet();
				rs.execute(sql);
				if (rs.next()) {
					tableName = Util.null2String(rs.getString("tablename"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tableName;
	}

	/**
	 * 根据流程号获取表名
	 *
	 * @param requestId
	 * @param rs
	 * @return
	 */
	public static String getTableNameByRequestId(String requestId, RecordSet rs) {
		String sql = "select t1.tablename from workflow_bill t1\n" +
				" left join workflow_base t2\n" +
				" on t1.id =t2.formid\n" +
				" left join workflow_requestbase t3\n" +
				" on t2.id = t3.workflowid\n" +
				" where t3.requestid=" + requestId;
		rs.writeLog("根据流程号获取表名@" + sql + "@");
		rs.execute(sql);
		if (rs.next()) {
			return Util.null2String(rs.getString("tablename"));
		} else {
			return "";
		}
	}

	/**
	 * 获取流程当前状态
	 *
	 * @param requestId 流程id
	 * @return String 流程status
	 */
	public static String getWorkflowStatus(String requestId) {
		String statusSQL = String.format("select status from workflow_requestbase where requestid='%s'", requestId);
		RecordSet recordSet = new RecordSet();
		recordSet.execute(statusSQL);
		String status = "";
		if (recordSet.next()) {
			status = Util.null2String(recordSet.getString("status"));
		}
		return status;
	}

	/**
	 * 根据流程id查询流程编号
	 *
	 * @param requestIds 流程id
	 * @return String 流程编号
	 */
	public static String getLcBhbyrequestId(String requestIds) {
		String unionwfid = Util.null2String(new PropBean().getPropName("unionwfid"));
		String wfidstr = Util.null2String(new PropBean().getWorkflowIdsByUnNumber(unionwfid));
		List<String> lisWF = Arrays.asList(wfidstr.split(","));
		HTUtil htUtil = new HTUtil();
		String tableName = htUtil.getTableNameByWfid(Util.getIntValue(lisWF.get(0))); //获取表单名
		String bhbySQL = "select lcbh from " + tableName + " where requestid in(" + requestIds + ")";
		RecordSet recordSet = new RecordSet();
		recordSet.execute(bhbySQL);
		List<String> lcbhs = new ArrayList();
		while (recordSet.next()) {
			lcbhs.add(Util.null2String(recordSet.getString("lcbh")));
		}
		return String.join(",", lcbhs);
	}

	/**
	 * 明细表14取科目对应数据
	 * 金额,是否超标,实际金额,标准金额,不含税价金额,税金
	 *
	 * @param km           科目code
	 * @param dt9TableName 明细表9
	 * @param ccsqlc       出差申请流程
	 * @param mainId       流程id
	 * @return JSONObject
	 */
	public static JSONObject getKjKmCharges(String km, String dt9TableName, String ccsqlc, String mainId) {
		RecordSet rs = new RecordSet();
		LogUtil logUtil = new LogUtil();
		logUtil.writeLog("[执行getKjKmCharges方法]");
		JSONObject subParam = new JSONObject();
		String dt9_sql = "select qzzsbhsje as zsbhs,zssj,sfcb,zscb,lkysbhsje as lkysbhs,lkyssj,qt from " + dt9TableName + " where mainid=" + mainId + " and ccsqlc=" + ccsqlc;
		rs.execute(dt9_sql);
		logUtil.writeLog("[执行dt9_sql]: [" + dt9_sql + "]");
		if (rs.next()) {
			logUtil.writeLog("[km]: [" + km + "]");
			if ("8601050302".equals(km)) { // 其他
				String qt = Util.null2String(rs.getString("qt"), "0.00");
				subParam.put("amount", qt); // 金额
				subParam.put("overweight", "否"); // 是否超标
				subParam.put("actualAmount", qt); // 实际金额
				subParam.put("standardAmount", "0.00"); // 标准金额
				subParam.put("notaxAmount", qt); // 不含价税金额
				subParam.put("taxAmount", "0.00"); //税金

			} else if ("8601050301".equals(km)) { // 交通费 (默认)
				String lkysbhs = Util.null2String(rs.getString("lkysbhs"), "0.00");
				String lkyssj = Util.null2String(rs.getString("lkyssj"), "0.00");
				subParam.put("amount", lkyssj);
				subParam.put("overweight", "否");
				subParam.put("actualAmount", lkyssj);
				subParam.put("standardAmount", "0.00");
				subParam.put("notaxAmount", lkysbhs);
				subParam.put("taxAmount", "0.00");

			} else if ("8601050303".equals(km)) { // 住宿费
				String zsbhs = Util.null2String(rs.getString("zsbhs"), "0.00");
				String zssj = Util.null2String(rs.getString("zssj"), "0.00");
				String zscb = Util.null2String(rs.getString("zscb"), "0.00"); //住宿标准值
				subParam.put("amount", zssj);
				subParam.put("overweight", Util.null2String(rs.getString("sfcb"), "否"));
				subParam.put("actualAmount", zssj);
				subParam.put("standardAmount", zscb);
				subParam.put("notaxAmount", zsbhs);
				subParam.put("taxAmount", "0.00");

			} else {
				subParam.put("amount", "0.00");
				subParam.put("overweight", "否");
				subParam.put("actualAmount", "0.00");
				subParam.put("standardAmount", "0.00");
				subParam.put("notaxAmount", "0.00");
				subParam.put("taxAmount", "0.00");
			}

		}

		logUtil.writeLog("===getKjKmCharges===, subParam: " + subParam);
		return subParam;
	}

	/**
	 * 明细表9取科目对应数据
	 * 价税合计金额,未税金额,税金,是否超标,实际金额,标准金额,是否it项目,it编码,it名称
	 *
	 * @param km       科目code
	 * @param dt9Table 明细表9
	 * @param ccsqlc   出差申请流程 (获取投行项目)
	 * @param mainId   流程mainid
	 * @return map
	 */
	public static Map<String, Object> getKjKmChargesWithMap(String km, String dt9Table, String ccsqlc, String mainId) {
		RecordSet rs = new RecordSet();
		LogUtil logUtil = new LogUtil();
		logUtil.writeLog("[执行getKjKmChargesWithMap方法]");
		Map<String, Object> subParam = new HashMap<>();
		Map<String, Object> itItemByReqId = getItItemByReqId(ccsqlc); //获取投行项目
		if (itItemByReqId.containsKey("id")) {
			subParam.putAll(itItemByReqId);
		}
		String dt9_sql = "select qzzsbhsje as zsbhs,zssj,sfcb,zscb,lkysbhsje as lkysbhs,lkyssj,qt from " + dt9Table + " where mainid=" + mainId + " and ccsqlc=" + ccsqlc;
		rs.execute(dt9_sql);
		logUtil.writeLog("[执行dt9_sql]: [" + dt9_sql + "]");
		if (rs.next()) {
			logUtil.writeLog("[km]: [" + km + "]");
			if ("8601050302".equals(km)) { // 其他
				String qt = Util.null2String(rs.getString("qt"), "0.00");
				subParam.put("FITEMDETAILNUM", km); // 科目
				subParam.put("FSJAMOUNT", qt); // 金额
				subParam.put("FOVERWEIGHT", "否"); // 是否超标
				subParam.put("FACTUALAMOUNT", qt); // 实际金额
				subParam.put("FSTANDARDAMOUNT", "0.00"); // 标准金额
				subParam.put("FNOTAXAMOUNT", qt); // 不含价税金额
				subParam.put("FTAXAMOUNT", "0.00"); //税金

			} else if ("8601050301".equals(km)) { // 交通费 (默认)
				String lkysbhs = Util.null2String(rs.getString("lkysbhs"), "0.00");
				String lkyssj = Util.null2String(rs.getString("lkyssj"), "0.00");
				subParam.put("FITEMDETAILNUM", km); // 科目
				subParam.put("FSJAMOUNT", lkyssj);
				subParam.put("FOVERWEIGHT", "否");
				subParam.put("FACTUALAMOUNT", lkyssj);
				subParam.put("FSTANDARDAMOUNT", "0.00");
				subParam.put("FNOTAXAMOUNT", lkysbhs);
				subParam.put("FTAXAMOUNT", "0.00");

			} else if ("8601050303".equals(km)) { // 住宿费
				String zsbhs = Util.null2String(rs.getString("zsbhs"), "0.00");
				String zssj = Util.null2String(rs.getString("zssj"), "0.00");
				String zscb = Util.null2String(rs.getString("zscb"), "0.00"); //住宿标准值
				subParam.put("FITEMDETAILNUM", km); // 科目
				subParam.put("FSJAMOUNT", zssj);
				subParam.put("FOVERWEIGHT", Util.null2String(rs.getString("sfcb"), "否"));
				subParam.put("FACTUALAMOUNT", zssj);
				subParam.put("FSTANDARDAMOUNT", zscb);
				subParam.put("FNOTAXAMOUNT", zsbhs);
				subParam.put("FTAXAMOUNT", "0.00");

			} else {
				subParam.put("FSJAMOUNT", "0.00");
				subParam.put("FOVERWEIGHT", "否");
				subParam.put("FACTUALAMOUNT", "0.00");
				subParam.put("FSTANDARDAMOUNT", "0.00");
				subParam.put("FNOTAXAMOUNT", "0.00");
				subParam.put("FTAXAMOUNT", "0.00");
			}

		}

		logUtil.writeLog("===getKjKmChargesWithMap===, subParam: " + subParam);
		return subParam;
	}

	/**
	 * 配置表获取表明
	 *
	 * @param propName
	 * @return
	 */
	public static String getTableNameByPropName(String propName) {
		String wfidName = Util.null2String(new PropBean().getPropName(propName));
		String wfidNames = Util.null2String(new PropBean().getWorkflowIdsByUnNumber(wfidName));
		List<String> wfidNameList = Arrays.asList(wfidNames.split(","));
		return WeaverUtil.getTableNameByWfid(Util.getIntValue(wfidNameList.get(0)));
	}


	/**
	 * 拟稿人获取银行信息,出差用的工号,报销用的id
	 *
	 * @param ngr 工号
	 * @param type 类型, 0:联合报销; 1:联合出差
	 * @return map
	 */
	public static Map<String, Object> getBankInfoByNgrWorkCode(String ngr, String type) {
		Map<String, Object> bankInfo = new HashMap<>();
		if ("".equals(ngr)) {
			logUtil.writeLog("[方法=WeaverUtil.getBankInfoByNgrWorkCode()], 指定拟稿人为空");
			bankInfo.put("workCode", "");
			bankInfo.put("subCompanyCode", "");
			bankInfo.put("deptCode", "");
			bankInfo.put("bankCardNum", "");
			bankInfo.put("bankOfDeposit", "");
			return bankInfo;
		}
		RecordSet rs = new RecordSet();
		String sql = "";
		if ("1".equals(type)) {
			sql = "select * from (\n" +
					"    select t1.khr,t1.yxkh,t1.yxmc,t2.lastname,t3.DEPARTMENTCODE,t4.SUBCOMPANYCODE,\n" +
					"    to_date((t1.MODEDATACREATEDATE ||' '|| t1.MODEDATACREATETIME),'yyyy-mm-dd hh24:mi:ss') as datetime\n" +
					"    from uf_lhclyxxx t1\n" +
					"    left join hrmresource t2\n" +
					"    on t1.khr=t2.workcode\n" +
					"    left join hrmdepartment t3\n" +
					"    on t2.departmentid=t3.id\n" +
					"    left join hrmsubcompany t4\n" +
					"    on t4.id=t2.SUBCOMPANYID1\n" +
					"    where t2.workcode='" + ngr + "' order by datetime desc \n" +
					") where rownum=1";
		} else {
			sql = "select * from (\n" +
					"    select t1.khr,t1.yxkh,t1.yxmc,t2.lastname,t3.DEPARTMENTCODE,t4.SUBCOMPANYCODE,\n" +
					"    to_date((t1.MODEDATACREATEDATE ||' '|| t1.MODEDATACREATETIME),'yyyy-mm-dd hh24:mi:ss') as datetime\n" +
					"    from uf_lhclyxxx t1\n" +
					"    left join hrmresource t2\n" +
					"    on t1.khr=t2.workcode\n" +
					"    left join hrmdepartment t3\n" +
					"    on t2.departmentid=t3.id\n" +
					"    left join hrmsubcompany t4\n" +
					"    on t4.id=t2.SUBCOMPANYID1\n" +
					"    where t2.id='" + ngr + "' order by datetime desc \n" +
					") where rownum=1";
		}
		logUtil.writeLog("[方法=WeaverUtil.getBankInfoByNgrWorkCode()], " + sql);
		rs.executeQuery(sql);
		if (rs.next()) {
			bankInfo.put("workCode", Util.null2String(rs.getString("khr")));
			bankInfo.put("subCompanyCode", Util.null2String(rs.getString("SUBCOMPANYCODE")));
			bankInfo.put("deptCode", Util.null2String(rs.getString("DEPARTMENTCODE")));
			bankInfo.put("bankCardNum", Util.null2String(rs.getString("yxkh")));
			bankInfo.put("bankOfDeposit", Util.null2String(rs.getString("yxmc")));
			logUtil.writeLog("[方法=WeaverUtil.getBankInfoByNgrWorkCode()], " + bankInfo);
		} else {
			logUtil.writeLog("[方法=WeaverUtil.getBankInfoByNgrWorkCode()], 指定拟稿人银行信息为空");
			bankInfo.put("workCode", "");
			bankInfo.put("subCompanyCode", "");
			bankInfo.put("deptCode", "");
			bankInfo.put("bankCardNum", "");
			bankInfo.put("bankOfDeposit", "");
		}
		return bankInfo;
	}



	public static List<String> getAssociatedBusinessTripMark(String lcs) {
		if ("".equals(lcs)) {
			return new ArrayList<>();
		}
		List<String> glcclc = new ArrayList<>();
		String[] lcArr = lcs.split(",");
		RecordSet rs = new RecordSet();
		for(String lc : lcArr){
			String sql = "select t.requestmark from workflow_requestbase t where t.requestid="+lc;
			rs.executeQuery(sql);
			if(rs.next()){
				glcclc.add(Util.null2String(rs.getString("requestmark")));
			}
		}
		return glcclc;
	}

	/**
	 * 关联出差流程的编号
	 *
	 * @param lcs
	 * @return
	 */
	public static List<Map<String, Object>> getAssociatedBusinessTripMark(String lcs, String refundReqId, String tablename) {
		List<Map<String, Object>> markWithReqId = new ArrayList<>();
		if ("".equals(lcs)) {
			return markWithReqId;
		}
		String[] lcArr = lcs.split(",");
		RecordSet rs = new RecordSet();
		String sqlBx = "select * from " + tablename + "_DT14 t1\n" +
				"left join " + tablename + " t2\n" +
				"on t1.MAINID=t2.ID\n" +
				"where t2.REQUESTID=? and t1.XJ != t1.BT";
		rs.executeQuery(sqlBx, refundReqId);
		//如果存在数据,补贴都赋值为0
		boolean flag = false;
		if (rs.next()) {
			flag = true;
		}
		String sql = "select t1.REQUESTNAME,t1.REQUESTMARK,t2.BT from workflow_requestbase t1\n" +
				"left join " + tablename + "_dt14 t2\n" +
				"on t1.requestid=t2.ccsqlc\n" +
				"left join " + tablename + " t3\n" +
				"on t3.id=t2.mainid\n" +
				"where to_char(t1.requestid)=? and to_char(t3.requestid)=? and t2.XJ=t2.BT and t2.BT != 0";
		Map<String, Object> businessTripMap;
		String bt;
		for (String lc : lcArr) {
			businessTripMap = new HashMap<>();
			rs.executeQuery(sql, lc, refundReqId);
			if (rs.next()) {
				businessTripMap.put("reqId", lc);
				businessTripMap.put("reqMark", Util.null2String(rs.getString("REQUESTMARK")));
				businessTripMap.put("reqTitle", Util.null2String(rs.getString("REQUESTNAME")));
				bt = Util.null2String(rs.getString("BT"));
				if ("".equals(bt)) {
					bt = "0.00";
				}
				//添加出差申请 crmCode..
				if (flag) {
					businessTripMap.put("allowance", Double.parseDouble("0.00"));
				} else {
					businessTripMap.put("allowance", Double.parseDouble(bt));
				}
				Map<String, Object> projOrCrmInfoForSaveJourney = new HTUtil().getProjOrCrmInfoForSaveJourney(lc);
				businessTripMap.putAll(projOrCrmInfoForSaveJourney);
			}
			markWithReqId.add(businessTripMap);
		}
		return markWithReqId;
	}

	/**
	 * 关联出差流程的补贴
	 *
	 * @param lcs
	 * @param refundReqId
	 * @return
	 */
	public static double getAssociatedBusinessAllowance(String lcs, String refundReqId, String tablename) {
		double allowances = 0.0;
		if ("".equals(lcs)) {
			return allowances;
		}
		String[] lcArr = lcs.split(",");
		RecordSet rs = new RecordSet();
		String sqlBx = "select * from " + tablename + "_DT14 t1\n" +
				"left join " + tablename + " t2\n" +
				"on t1.MAINID=t2.ID\n" +
				"where t2.REQUESTID=? and t1.XJ != t1.BT";
		rs.executeQuery(sqlBx, refundReqId);
		if (rs.next()) {
			return 0;
		}
		//明细14，通过补贴和小计判断是否自费; 补贴等于小计即没有自费;取没有自费的补贴
		String sql = "select t1.REQUESTMARK,t2.BT from workflow_requestbase t1\n" +
				"left join " + tablename + "_DT14 t2\n" +
				"on t1.requestid=t2.ccsqlc\n" +
				"left join " + tablename + " t3\n" +
				"on t3.id=t2.mainid\n" +
				"where to_char(t1.requestid)=? and to_char(t3.requestid)=? and t2.XJ=t2.BT and t2.BT != 0";
		for (String lc : lcArr) {
			rs.executeQuery(sql, lc, refundReqId);
			String bt = "0.00";
			if (rs.next()) {
				bt = Util.null2String(rs.getString("spje"));
				if (StringUtils.isBlank(bt)) {
					bt = "0.00";
				}
			}
			allowances += Double.parseDouble(bt);
		}
		return allowances;
	}

	/**
	 * 获取支付单号
	 *
	 * @param nyr
	 * @return
	 */
	public static String getPaymentOrder(String nyr) {
		int lc;
		String dh = "";
		RecordSet rs = new RecordSet();
		rs.executeQuery("select * from (\n" +
				" select to_number(substr(zfdh,-4)) ls,substr(zfdh,1,10) dh \n" +
				" from uf_zfmx where substr(zfdh,-10,6)='" + nyr + "' \n" +
				" order by to_date(MODEDATACREATETIME,'hh24:mi:ss') desc\n" +
				") where rownum=1");
		if (rs.next()) {
			dh = rs.getString("dh");
			lc = Util.getIntValue(rs.getString("lc")) + 1;
		} else {
			dh = "HTLHBX0320";
			lc = 1;
		}
		String ls = lc + "";
		while (ls.length() < 4) {
			ls = "0" + lc;
		}
		return dh + nyr + ls;
	}

	/**
	 * 获取差旅报销费用承担部门code
	 *
	 * @return 部门code
	 */
	public static String getFeeBurdenDept(String main, String reqId) {
		String sql = "select t2.FYCDBM from " + main + " t1\n" +
				" left join " + main + "_dt9 t2\n" +
				" on t1.ID=t2.MAINID\n" +
				" where t1.REQUESTID=" + reqId;
		DepartmentComInfo dc = new DepartmentComInfo();
		RecordSet rs = new RecordSet();
		rs.executeQuery(sql);
		if (rs.next()) {
			String deptId = Util.null2String(rs.getString("FYCDBM"));
			if (StringUtils.isNotEmpty(deptId)) {
				return dc.getDepartmentCode(deptId);
			}
		}
		return "";
	}

	/**
	 * 根据人员id返回差标等级
	 *
	 * @param hrmId        人员id
	 * @param backDeptList 后台部门
	 * @return L1-L5
	 */
	public static String getJobGradeStandard(String hrmId, List<String> backDeptList) {
		//L1 所属部门 (董事会,执行委员会,党委副书记)
		List<String> deptL1 = Arrays.asList("487", "489", "713");
		//L1 所属人员 (合规总监,宁敖)
		List<String> hrmL1 = Arrays.asList("6633", "5891");
		//L2 协管领导 (张冠峰)
		//String hrmL2 = "6483";
		List<String> hrmL2 = Arrays.asList("6483", "6579","2906");
		try {
			PropBean pp = new PropBean();
			RecordSet rs = new RecordSet();
			String sql = "select t1.FIELD9,t2.WORKCODE,t2.DEPARTMENTID from cus_fielddata t1\n" +
					"left join HRMRESOURCE t2\n" +
					"on t1.ID=t2.ID\n" +
					"where t1.scopeid = 1 and t2.id = ?";
			rs.executeQuery(sql, hrmId);
			String field = "";
			String departmentID = "";
			String workCode = "";
			if (rs.next()) {
				field = Util.null2String(rs.getString("field9"));
				departmentID = Util.null2String(rs.getString("DEPARTMENTID"));
				workCode = Util.null2String(rs.getString("WORKCODE"));
			}
			log.info("====hrmId@" + hrmId + "@");
			log.info("====hrmId部门id为@" + departmentID + "@");
			log.info("====hrmId的workCode为@" + workCode + "@");
			Set<String> l3pTravelStandardSet = new HashSet<>(Arrays.asList(pp.getPropName("travel_standard_l3p").split(",")));
			if(l3pTravelStandardSet.contains(workCode)){
				log.info(String.format("return L3P travel standard employee :",workCode));
				return "L3P";
			}
			if (workCode.toUpperCase().startsWith("SX")) {
				log.info("====hrmId为实习生");
				return "L5";
			}
			if (deptL1.contains(departmentID) || hrmL1.contains(hrmId)) {
				return "L1";
			}
			if (hrmL2.contains(hrmId)) {
				return "L2";
			}

			if ("".equals(field)) {
				log.info("====未找到对应的职级");
				return "";
			} else {
				field = field.toUpperCase();
				log.info("====当前人员职级@" + field + "@");
			}
			if (backDeptList.contains(departmentID)) {
				//后台部门
				if ("SD".equals(field) || "D".equals(field)) {
					return "L3";
				} else {
					//除去 sd 及 d 以外都是 ss及以下
					return "L4";
				}
			} else {
				//前台部门
				if ("MD".equals(field) || "ED".equals(field)) {
					return "L3";
				} else {
					return "L4";
				}
			}
		} catch (Exception e) {
			log.info("====getJobGradeStandard异常:" + e);
			return "";
		}

	}

}
