package com.api.htsc.businessMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ParamUtil;
import com.engine.htsc.payment.enums.BudgetNodeType;
import com.engine.htsc.payment.enums.HsType;
import com.engine.htsc.payment.pojo.CostAccountDto;
import com.engine.htsc.payment.util.BizUtils;
import com.engine.htsc.payment.util.StringUtil;
import com.engine.htsc.seal.web.RedisTools;
import com.engine.htsc.trip.service.impl.BtServiceImpl;
import com.engine.htsc.trip.service.impl.ReimbursementServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import redis.clients.jedis.Jedis;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Author:DTY-PC
 * Date:2020/10/30 15:13
 * Description:
 * Copyright:上海泛微网络科技股份有限公司
 */
@Path("/js")
public class JSUtil {

	private Log log = LogFactory.getLog(this.getClass());
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");

	/**
	 * 1）	循环校验姓名明细字段，如果xm中存在人员在下列范围内：
	 * ①	为部门负责人
	 * ②	为合规专职管理：投资银行业务线/专职合规管理、债券业务线/专职合规管理
	 * ③	属于公司领导：董事会、执行委员会、党委副书记（人员工号：014931）、合规总监（人员工号：009240）、宁敖（人员工号：001781）
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@GET
	@Path("/isSpecialPerson")
	@Produces(MediaType.TEXT_PLAIN)
	public String isSpecialPerson(@Context HttpServletRequest request, @Context HttpServletResponse response) {
		Map<String, Object> apiDatas = new HashMap<>();
		try {
			Map<String, Object> params = ParamUtil.request2Map(request);
			String hrmids = Util.null2String(params.get("hrmids"));
			RecordSet rs = new RecordSet();
			BtServiceImpl btService = new BtServiceImpl();
			apiDatas.put("isExist", btService.checkNames(hrmids));
			apiDatas.put("api_status", true);
		} catch (Exception e) {
			apiDatas.put("api_status", false);
		}
		return JSONObject.toJSONString(apiDatas);
	}

	/**
	 * 获取行程
	 *
	 * @param reqids 出差申请流程
	 * @return
	 */
	@GET
	@Path("/queryJourney")
	@Produces(MediaType.TEXT_PLAIN)
	public String queryjourney(@QueryParam("reqids") String reqids) {
		Map<String, Object> apidatas = new HashMap<>();
		try {
			HTUtil ht = new HTUtil();
			List<String> reqList = Util.splitString2List(reqids, ",");
			Map<String, Object> params = new HashMap<>();
			//联合出差流程的主表名
			String tableName = Util.null2String(ht.getTableNameByRequestid(reqList.get(0), "0"));
			if (StringUtils.isEmpty(tableName)) {
				apidatas.put("api_Status", false);
				return JSONObject.toJSONString(apidatas);
			}
			String tableDt2Name = tableName + "_dt2";//明细2
			String sql = "select m.lcbh,d.xm from " + tableName + " m," + tableDt2Name + " d where m.id" +
					" = d.mainid and m.requestid = ?";
			RecordSet rs = new RecordSet();
			List<String> hrmList = new ArrayList<>();
			ResourceComInfo rc = new ResourceComInfo();
			for (String reqid : reqList) {//流程遍历
				rs.executeQuery(sql, new Object[]{reqid});
				while (rs.next()) {
					String lcbh = Util.null2String(rs.getString("lcbh")).replace("出差申请", "");//流程编号
					String xm = Util.null2String(rs.getString("xm"));//出差人
					hrmList.add(lcbh + "_" + xm + "_" + reqid);
				}
			}
			JSONArray resArr = new JSONArray();//自付信息
			JSONObject payObj = new JSONObject();//代付信息
			JSONArray flightArr = new JSONArray();//飞机代付
			JSONArray hotelArr = new JSONArray();//住宿代付
			JSONArray trainArr = new JSONArray();//火车代付
			JSONArray carArr = new JSONArray();//汽车代付
			JSONArray dfArr = new JSONArray();//代付合计
			for (String hrm : hrmList) {//人员遍历
				String journeyId = hrm.split("_")[0];
				String xm = hrm.split("_")[1];
				String reqid = hrm.split("_")[2];
				String empCode = rc.getWorkcode(xm);
				params.put("journeyId", journeyId);
				params.put("empCode", empCode);
				String res = ht.queryByJourneyId(params);
				JSONObject resObj = JSONObject.parseObject(res);
				if (!"".equals(Util.null2String(resObj.get("journeyId")))) {
					JSONArray arr = resObj.getJSONArray("empOrderSettlementModels");
					for (int i = 0; i < arr.size(); i++) {
						JSONObject obj = arr.getJSONObject(i);
						JSONObject newObj = new JSONObject();
						newObj.put("xm", xm);
						newObj.put("empName", Util.null2String(obj.get("empName")));
						newObj.put("flightCash", Util.null2String(obj.get("flightCash")));
						newObj.put("trainCash", Util.null2String(obj.get("trainCash")));
						newObj.put("hotelCash", Util.null2String(obj.get("hotelCash")));
						newObj.put("carCash", Util.null2String(obj.get("carCash")));
						newObj.put("reqid", reqid);
						resArr.add(newObj);
						//飞机
						JSONObject flight = new JSONObject();
						flight.put("arr", obj.getJSONArray("flightOrderSettlementModels"));
						flight.put("xm", xm);
						flight.put("reqid", reqid);
						flight.put("empName", Util.null2String(obj.get("empName")));
						flightArr.add(flight);
						//飞机
						//住宿
						JSONObject hotel = new JSONObject();
						hotel.put("arr", obj.getJSONArray("hotelOrderSettlementModels"));
						hotel.put("xm", xm);
						hotel.put("reqid", reqid);
						hotel.put("empName", Util.null2String(obj.get("empName")));
						hotelArr.add(hotel);
						//住宿
						//火车
						JSONObject train = new JSONObject();
						train.put("arr", obj.getJSONArray("trainOrderSettlementModels"));
						train.put("xm", xm);
						train.put("reqid", reqid);
						train.put("empName", Util.null2String(obj.get("empName")));
						trainArr.add(train);
						//火车
						//汽车
						JSONObject car = new JSONObject();
						car.put("arr", obj.getJSONArray("carOrderSettlementModels"));
						car.put("xm", xm);
						car.put("reqid", reqid);
						car.put("empName", Util.null2String(obj.get("empName")));
						carArr.add(car);
						//汽车
						JSONObject df = new JSONObject();
						df.put("xm", xm);
						df.put("reqid", reqid);
						df.put("totalMonthly", Util.null2String(obj.get("totalMonthly")));
						//代付
						dfArr.add(df);
						//代付
					}
				}
			}
			payObj.put("flight", flightArr);
			payObj.put("hotel", hotelArr);
			payObj.put("train", trainArr);
			payObj.put("car", carArr);
			payObj.put("df", dfArr);
			apidatas.put("api_Status", true);
			apidatas.put("datas", resArr);
			apidatas.put("pay", payObj);
		} catch (Exception e) {
			e.printStackTrace();
			apidatas.put("api_Status", false);
		}
		return JSONObject.toJSONString(apidatas);
	}

	/**
	 * 当前出差流程在携程中获取的自费信息为空时，需要自动生成空的明细，对应的人和requestid
	 *
	 * @param reqids 请求ID
	 * @return 自费信息
	 */
	@GET
	@Path("/getEmptyZF")
	@Produces(MediaType.TEXT_PLAIN)
	public String getEmpty(@QueryParam("reqids") String reqids) {
		Map<String, Object> apiDatas = new HashMap<>();
		try {
			List<String> reqList = Util.splitString2List(reqids, ",");
			//联合出差流程的主表名
			HTUtil ht = new HTUtil();
			String tableName = Util.null2String(ht.getTableNameByRequestid(reqList.get(0), "0"));
			String tableDt2Name = tableName + "_dt2";//明细2
			String sql = "select d.xm from " + tableName + " m," + tableDt2Name + " d where m.id" +
					" = d.mainid and m.requestid = ?";
			RecordSet rs = new RecordSet();
			JSONArray hrmList = new JSONArray();
			ResourceComInfo rc = new ResourceComInfo();
			for (String reqid : reqList) {//流程遍历
				rs.executeQuery(sql, new Object[]{reqid});
				while (rs.next()) {
					JSONObject obj = new JSONObject();
					String xm = Util.null2String(rs.getString("xm"));//出差人
					obj.put("hrmid", xm);
					obj.put("reqid", reqid);
					obj.put("name", rc.getLastname(xm));
					hrmList.add(obj);
				}
			}
			apiDatas.put("api_Status", true);
			apiDatas.put("datas", hrmList);
		} catch (Exception e) {
			e.printStackTrace();
			apiDatas.put("api_Status", false);
		}

		return JSONObject.toJSONString(apiDatas);
	}

	/**
	 * 钱的代码判断是否特殊人员
	 *
	 * @param names
	 * @param rs
	 * @return
	 */
	private boolean checkNames(String names, RecordSet rs) {
		String[] checkName = names.split(",");
		List<String> nameSpace = new ArrayList<>(); //姓名空间
		//特定人员
		nameSpace.add("18879"); //党委书记,江禹
		nameSpace.add("21749"); //党委副书记
		nameSpace.add("6633"); //合规总监
		nameSpace.add("5891"); //宁敖
		for (String name : checkName) {
			if (nameSpace.contains(name)) {
				return true;
			}
		}
		nameSpace.clear();
		//特定部门(董事会487,执行委员会489,党委713,投资银行业务线/专职合规管理666,债券业务线/专职合规管理667)
		String sql_SpecifyDept = "SELECT DISTINCT id FROM hrmresource WHERE departmentid IN ('666','667','487','489','713') AND id IS NOT NULL";
		rs.execute(sql_SpecifyDept);
		while (rs.next()) {
			nameSpace.add(rs.getString("id"));
		}
		for (String name : checkName) {
			if (nameSpace.contains(name)) {
				return true;
			}
		}
		//部门负责人
		nameSpace.clear();
		String sql_deptDirectors = "SELECT DISTINCT deptDirectors AS id FROM matrixtable_2 WHERE deptDirectors IS NOT NULL";
		rs.execute(sql_deptDirectors);
		while (rs.next()) {
			nameSpace.add(rs.getString("id"));
		}
		for (String name : checkName) {
			if (nameSpace.contains(name)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取人员的默认工作地点，这里是在差旅报销中使用的报销地
	 *
	 * @param userid 人员ID
	 * @return 工作地
	 */
	@GET
	@Path("/getWorkAddress")
	@Produces(MediaType.TEXT_PLAIN)
	public String getWorkAddress(@QueryParam("userid") String userid) {
		log.info("获取报销地的接口入参是：" + userid);
		Map<String, String> apiData = new HashMap<>();
		try {
			if ("".equals(userid)) {
				return "";
			}
			RecordSet rs = new RecordSet();
			String sql = " select case field0\n" +
					" when '北京市' then '2'\n" +
					" when '上海市' then '1'\n" +
					" when '深圳市' then '0'\n" +
					" when '南京市' then '3'\n" +
					" else '' \n" +
					" end area from cus_fielddata where\n" +
					" scope = 'HrmCustomFieldByInfoType' and id = ?";
			rs.executeQuery(sql, new Object[]{userid});
			rs.next();
			apiData.put("address", Util.null2String(rs.getString(1)));
		} catch (Exception e) {
			log.error("获取报销地捕获异常：" + e.getMessage());
			apiData.put("address", "");
		}
		return JSONObject.toJSONString(apiData);
	}

	/**
	 * "出纳付款"功能的  【付款】 按钮  接口
	 *
	 * @param request  request
	 * @param response response
	 * @return return
	 */
	@POST
	@Path("/totalpay")
	@Produces(MediaType.TEXT_PLAIN)
	public String doTotalPay(@Context HttpServletRequest request, @Context HttpServletResponse response) {
		Map<String, Object> apiDatas = new HashMap<>();
		apiDatas.put("api_status", true);
		apiDatas.put("msg", "成功");
		try {
			Map<String, Object> params = ParamUtil.request2Map(request);
			String dataids = Util.null2String(params.get("dataids"));
			BaseBean bb = new BaseBean();
			RecordSet rs = new RecordSet();
			RecordSet rs_up = new RecordSet();
			RecordSet rs_Prepay =new RecordSet();
			RecordSet rs_midtab = new RecordSet();
			RecordSet rs_m = new RecordSet();
			RecordSet rs_dt11 = new RecordSet();
			RecordSet rs_dt10 = new RecordSet();
			ResourceComInfo rc = new ResourceComInfo();
			DepartmentComInfo dc = new DepartmentComInfo();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			RecordSetDataSource rsdM = new RecordSetDataSource("FinanceM");
			RecordSet rs_lclx = new RecordSet();
			HTUtil ht = new HTUtil();
			ReimbursementServiceImpl rei = new ReimbursementServiceImpl();
			List<String> idsList = Arrays.asList(dataids.split(","));//转换成list
			if (!"".equals(dataids)) {//存在ids为空，idsList.size() > 0 的特殊情况
				for (String id : idsList) {
					boolean isYS = false;//预算是否成功
					boolean isHS = false;//核算是否成功
					JSONObject obj = new JSONObject();//最外层对象
//					obj.put("lb", "lhcl"); //添加流程标识
					String sqlQuery = "select reqid,tyzfdh,fksj,dq,lcbm,ngr,ngbm,lcbt,zfdh,fkzt,tbhs from uf_zfmx where id = ?";
					rs.executeQuery(sqlQuery, new Object[]{id});
					if (rs.next()) {
						String reqid = Util.null2String(rs.getString("reqid"));//流程请求ID
						obj.put("djid", reqid);
						String lcbm = Util.null2String(rs.getString("lcbm"));//流程编码
						obj.put("bxbh", lcbm);
						String ngrName = rc.getLastname(Util.null2String(rs.getString("ngr")));//拟稿人姓名
						obj.put("bxr", ngrName);
						String depName = dc.getDepartmentmark(Util.null2String(rs.getString("ngbm")));//拟稿人部门
						obj.put("bxbm", depName);
						String lcbt = Util.null2String(rs.getString("lcbt"));//流程标题
						obj.put("zy", lcbt);
						String fkdh = Util.null2String(rs.getString("zfdh"));//支付单号
						if ("".equals(fkdh)) { //支付单号
							apiDatas.put("api_status", false);
							apiDatas.put("msg", "【" + lcbm + "】的【支付单号】为空，不允许付款！");
							return JSONObject.toJSONString(apiDatas);
						}
						if(SubUnionBizUtil.equalsTableName(reqid, SubUnionBizUtil.LHTYFK)) {
							//联合通用付款
							obj.put("lb", "lhfk"); //添加流程标识
						}else{
							obj.put("lb", "lhcl"); //添加流程标识
						}


						Jedis jedis = RedisTools.GetJedis();
						String rediskey="cxOrder_redis_key";
						PropBean pb = new PropBean();
						try{
							int counts=0;
							int expireTime=Util.getIntValue(Util.null2String(pb.getPropName("RedisExpiretime")));
							boolean redisfalg=RedisTools.TryGetDistributedLock(jedis,rediskey,lcbm,expireTime);
							JAVATools.SetCmdwritelog("refreshOrderNo开始状态:"+redisfalg+"lcbm:"+lcbm);
							while (redisfalg==false && counts<10) {
								Thread.sleep(500);
								counts++;
								redisfalg=RedisTools.TryGetDistributedLock(jedis,rediskey,lcbm,expireTime);
							}
							JAVATools.SetCmdwritelog("refreshOrderNo结束状态:"+redisfalg+"lcbm:"+lcbm);
							if(redisfalg){
								// 支付单号更新,点击计算时,更新年月日和序号
								String newOrderNo = refreshOrderNo(fkdh, lcbm,reqid);
								log.info("旧的支付单号@" + fkdh + "@");
								log.info("新的支付单号@" + newOrderNo + "@");
								obj.put("fkdh", newOrderNo);
								obj.put("bxfs", "");
								String fkzt = Util.null2String(rs.getString("fkzt"));
								String tbhs = Util.null2String(rs.getString("tbhs"));//同步核算
								/*
								 * 需求修改
								 * 日期: 20210325
								 * 内容: 允许出纳付款管理员重复点击付款按钮, 已废弃状态不允许
								 */
//						if (!"1".equals(fkzt)) {//0：已付款，1：未付款，2：已废弃
//							apiDatas.put("api_status", false);
//							apiDatas.put("msg", "【" + lcbm + "】的【付款状态】不符合要求，不允许付款！");
//							return JSONObject.toJSONString(apiDatas);
//						}
								if ("2".equals(fkzt)) {//0：已付款，1：未付款，2：已废弃
									apiDatas.put("api_status", false);
									apiDatas.put("msg", "【" + lcbm + "】的【付款状态】不符合要求，不允许付款！");
									return JSONObject.toJSONString(apiDatas);
								}
								if (!"".equals(reqid)) {
									//处理预算START
									// 联合子公司通用报销,判断requestId是否属于该流程,true走通用报销逻辑;false走原逻辑
									String ysRes = "";
									if (SubUnionBizUtil.equalsTableName(reqid, SubUnionBizUtil.LHTYBX)) {
										ysRes = SubUnionBizUtil.doBudgetCommit4Union(reqid, BudgetNodeType.FINISH.getValue());
									} else {
										//原逻辑
										ysRes = rei.doBudgetCommit(reqid, "1");
									}

									if ("F1001".equals(ysRes)) {
										isYS = true;
									} else {
										apiDatas.put("api_status", false);
										apiDatas.put("msg", "【" + lcbm + "】的同步预算失败！");
										return JSONObject.toJSONString(apiDatas);
									}
									//处理预算END
								} else {
									apiDatas.put("api_status", false);
									apiDatas.put("msg", "【" + lcbm + "】--请求ID为空，付款失败！");
									return JSONObject.toJSONString(apiDatas);
								}

								//核算入参
								Map<String, Object> jsonMap;

								// 判断是并构造联合通用报销核算数据
								if (SubUnionBizUtil.equalsTableName(reqid, SubUnionBizUtil.LHTYBX)) {
									CostAccountDto costAccountDto = SubUnionBizUtil.generateUnionReiData(reqid,
											HsType.LHPTBX.getType(), newOrderNo);
									String costAccountDtoJsonStr = JSON.toJSONString(costAccountDto);
									jsonMap = JSONObject.parseObject(costAccountDtoJsonStr, Map.class);
								} else if(SubUnionBizUtil.equalsTableName(reqid, SubUnionBizUtil.LHTYFK)) {
									//判断是联合通用付款核算数据
									//主表
									//处理核算START
									String tableName = Util.null2String(ht.getTableNameByRequestid(reqid, "0"));
									String tableDt12Name = tableName + "_dt12";//明细12
									String tableDt11Name = tableName + "_dt11";//明细11
									String sql_m = "select id,case sqdd  when 2 then '北京' when 1 then '上海'" +
											" when 0 then '深圳'  when 3 then '南京'" +
											" else ''   end dq,djzs from " + tableName + " where requestid = ? ";
									rs_m.executeQuery(sql_m, new Object[]{reqid});
									rs_m.next();
									int mainid = Util.getIntValue(rs_m.getString("id"));
									String dq = Util.null2String(rs_m.getString("dq"));//地区  报销地
									obj.put("dq", dq);
									String djzs = Util.null2String(rs_m.getString("djzs"));//单据张数
									obj.put("fjzs", djzs);
									String sql_dt12 = "select je,gsxm,zhrmb,fysjcdbm,hjkm from " + tableDt12Name + " where mainid = ?";
									rs_dt11.executeQuery(sql_dt12, new Object[]{mainid});
									JSONArray kjmxArr = new JSONArray();//会计明细
									while (rs_dt11.next()) {
										JSONObject kjmxObj = new JSONObject();
										//分摊部门名称
										String fycdbmName = Util.null2String(dc.getDepartmentmark(rs_dt11.getString("fysjcdbm")));
										kjmxObj.put("expenseDept", fycdbmName);
										//分摊部门编码
										String fycdbmCode = Util.null2String(dc.getDepartmentCode(rs_dt11.getString("fysjcdbm")));
										kjmxObj.put("expenseDeptCode", fycdbmCode);
										//金额
										String je = Util.null2String(rs_dt11.getString("je"));
										kjmxObj.put("money", je);
										//预算项目
										String gsxm = Util.null2String(rs_dt11.getString("gsxm"));
										Map<String, Object> project = new HashMap<>();
										project.put("projectId", gsxm);
										String res = ht.getProjectById(project);
										if (!"".equals(res)) {
											JSONObject jsonObject = JSONObject.parseObject(res);
											kjmxObj.put("projectCode", Util.null2String(jsonObject.get("code")));
											kjmxObj.put("project", Util.null2String(jsonObject.get("shortName")));
										} else {
											kjmxObj.put("projectCode", "");
											kjmxObj.put("project", "");
										}
										kjmxObj.put("reason", "");//预算是由
										//折合人民币金额
										String zhrmb = Util.null2String(rs_dt11.getString("zhrmb"));
										kjmxObj.put("priceRMB", zhrmb);
										JSONObject subjectData = new JSONObject();
										String ejkjkmbm = Util.null2String(rs_dt11.getString("hjkm"));//二级会计科目编码
										subjectData.put("itemCode", ejkjkmbm);
										String ejkjkmmc = getEJKJKMMC(ejkjkmbm);//二级会计科目名称
										subjectData.put("itemName", ejkjkmmc);
										//预算科目
										JSONObject yssuanData = new JSONObject();
										Map<String, String> map = new HashMap<>(getYSKM(ejkjkmbm));
										String ejyskmbm = map.isEmpty() ? "" : map.get("code");
										String ejyskmmc = map.isEmpty() ? "" : map.get("name");
										yssuanData.put("itemCode", ejyskmbm);
										yssuanData.put("itemName", ejyskmmc);
										yssuanData.put("relationCode", ejkjkmbm);
										kjmxObj.put("yssuanData", yssuanData);
										kjmxObj.put("subjectData", subjectData);
										kjmxArr.add(kjmxObj);
									}

									obj.put("kjmx", kjmxArr);
									String sql_dt11 = "select skdw,yxzfje,xjzfje,khx,yxzh from " + tableDt11Name + " where mainid = ?";
									rs_dt10.executeQuery(sql_dt11, new Object[]{mainid});
									JSONArray zfmxArr = new JSONArray();
									while (rs_dt10.next()) {
										JSONObject zfmxObj = new JSONObject();
										//收款单位
										String skdw = Util.null2String(rs_dt10.getString("skdw"));
										zfmxObj.put("employeeDept", skdw);
										//银行支付
										String yxzfje = Util.null2String(rs_dt10.getString("yxzfje"));
										zfmxObj.put("payByBank", yxzfje);
										//现金支付
										String xjzfje = Util.null2String(rs_dt10.getString("xjzfje"));
										zfmxObj.put("payByCash", xjzfje);
										//开户行
										String khx = Util.null2String(rs_dt10.getString("khx"));
										zfmxObj.put("bankName", getKHXMC(khx));
										//银行账户
										String yxzh = Util.null2String(rs_dt10.getString("yxzh"));
										zfmxObj.put("bankAccount", yxzh);
										zfmxArr.add(zfmxObj);
									}
										obj.put("zfmx", zfmxArr);
										bb.writeLog("联合通用付款支付明细：" + obj.toJSONString());
									    jsonMap = JSONObject.toJavaObject(obj, Map.class);
								} else {
									//主表
									//处理核算START
									String tableName = Util.null2String(ht.getTableNameByRequestid(reqid, "0"));
									String tableDt11Name = tableName + "_dt11";//明细8
									String tableDt10Name = tableName + "_dt10";//明细10
									String tableDt19Name = tableName + "_dt19";//明细19
									String sql_m = "select id,case sjbxd  when 2 then '北京' when 1 then '上海'" +
											" when 0 then '深圳'  when 3 then '南京'" +
											" else ''   end dq,djzs from " + tableName + " where requestid = ? ";
									rs_m.executeQuery(sql_m, new Object[]{reqid});
									rs_m.next();
									int mainid = Util.getIntValue(rs_m.getString("id"));
									String dq = Util.null2String(rs_m.getString("dq"));//地区  报销地
									obj.put("dq", dq);
									String djzs = Util.null2String(rs_m.getString("djzs"));//单据张数
									obj.put("fjzs", djzs);
									String sql_dt11 = "select fycdr,je,gsxm,zhrmb,fycdbm,hjkm from " + tableDt11Name + " where mainid = ?";
									rs_dt11.executeQuery(sql_dt11, new Object[]{mainid});
									JSONArray kjmxArr = new JSONArray();//会计明细
									while (rs_dt11.next()) {
										JSONObject kjmxObj = new JSONObject();
										//分摊人姓名
										String fycdrName = Util.null2String(rc.getLastname(rs_dt11.getString("fycdr")));
										kjmxObj.put("expensePerson", fycdrName);
										//分摊人工号
										String fycdrCode = Util.null2String(rc.getWorkcode(rs_dt11.getString("fycdr")));
										kjmxObj.put("expenseBadge", fycdrCode);
										//分摊部门名称
										String fycdbmName = Util.null2String(dc.getDepartmentmark(rs_dt11.getString("fycdbm")));
										kjmxObj.put("expenseDept", fycdbmName);
										//分摊部门编码
										String fycdbmCode = Util.null2String(dc.getDepartmentCode(rs_dt11.getString("fycdbm")));
										kjmxObj.put("expenseDeptCode", fycdbmCode);
										//金额
										String je = Util.null2String(rs_dt11.getString("je"));
										kjmxObj.put("money", je);
										//预算项目
										String gsxm = Util.null2String(rs_dt11.getString("gsxm"));
										Map<String, Object> project = new HashMap<>();
										project.put("projectId", gsxm);
										String res = ht.getProjectById(project);
										if (!"".equals(res)) {
											JSONObject jsonObject = JSONObject.parseObject(res);
											kjmxObj.put("projectCode", Util.null2String(jsonObject.get("code")));
											kjmxObj.put("project", Util.null2String(jsonObject.get("shortName")));
										} else {
											kjmxObj.put("projectCode", "");
											kjmxObj.put("project", "");
										}
										kjmxObj.put("reason", "");//预算是由
										//折合人民币金额
										String zhrmb = Util.null2String(rs_dt11.getString("zhrmb"));
										kjmxObj.put("priceRMB", zhrmb);
										JSONObject subjectData = new JSONObject();
										String ejkjkmbm = Util.null2String(rs_dt11.getString("hjkm"));//二级会计科目编码
										subjectData.put("itemCode", ejkjkmbm);
										String ejkjkmmc = getEJKJKMMC(ejkjkmbm);//二级会计科目名称
										subjectData.put("itemName", ejkjkmmc);
										//预算科目
										JSONObject yssuanData = new JSONObject();
										Map<String, String> map = new HashMap<>(getYSKM(ejkjkmbm));
										String ejyskmbm = map.isEmpty() ? "" : map.get("code");
										String ejyskmmc = map.isEmpty() ? "" : map.get("name");
										yssuanData.put("itemCode", ejyskmbm);
										yssuanData.put("itemName", ejyskmmc);
										yssuanData.put("relationCode", ejkjkmbm);
										kjmxObj.put("yssuanData", yssuanData);
										kjmxObj.put("subjectData", subjectData);
										kjmxArr.add(kjmxObj);
									}

									obj.put("kjmx", kjmxArr);
									String sql_dt10 = "select t.yxzfje,t.xjzfje,t.khx,h.yxmc,t.yxzh,t.bm,t.bxr from " + tableDt10Name + " t left  join uf_khh h on t.khx=h.lxh where mainid = ?";
									rs_dt10.executeQuery(sql_dt10, new Object[]{mainid});
									JSONArray zfmxArr = new JSONArray();
									while (rs_dt10.next()) {
										JSONObject zfmxObj = new JSONObject();
										//银行支付金额
										String yxzfje = Util.null2String(rs_dt10.getString("yxzfje"));
										zfmxObj.put("payByBank", yxzfje);
										//现金支付金额
										String xjzfje = Util.null2String(rs_dt10.getString("xjzfje"));
										zfmxObj.put("payByCash", xjzfje);
										//开户行
										String khx = Util.null2String(rs_dt10.getString("yxmc"));
										zfmxObj.put("bankName", khx);
										//银行账户
										String yxzh = Util.null2String(rs_dt10.getString("yxzh"));
										zfmxObj.put("bankAccount", yxzh);
										//部门名称
										String bm = Util.null2String(rs_dt10.getString("bm"));
										zfmxObj.put("employeeDept", dc.getDepartmentmark(bm));
										//员工姓名
										String bxr = Util.null2String(rs_dt10.getString("bxr"));
										zfmxObj.put("employeeName", rc.getLastname(bxr));
										zfmxArr.add(zfmxObj);
									}
									//月结对公支付明细
									RecordSet rs_dt19 = new RecordSet();
									String sql_dt19 = "SELECT t.skdw,t.khx,h.yxmc,t.skzh,t.zffs,t.zfje FROM "+ tableDt19Name +" t left  join uf_khh h on t.khx=h.lxh  WHERE mainid = ?";
									rs_dt19.executeQuery(sql_dt19, new Object[]{mainid});
									JSONArray yjZfmxArr = new JSONArray();
									while (rs_dt19.next()) {
										JSONObject yjZfmxObj = new JSONObject();
										//收款单位
										String skdw = Util.null2String(rs_dt19.getString("skdw"));
										yjZfmxObj.put("employeeDept", skdw);
										//开户行
										String khx = Util.null2String(rs_dt19.getString("yxmc"));
										yjZfmxObj.put("bankName", khx);
										//收款账户
										String skzh = Util.null2String(rs_dt19.getString("skzh"));
										yjZfmxObj.put("bankAccount", skzh);
										//支付方式
										String zffs = Util.null2String(rs_dt19.getString("zffs"));
										//支付金额
										String zfje = Util.null2String(rs_dt19.getString("zfje"));
										if ("0".equals(zffs)){
											//银行支付
											yjZfmxObj.put("payByBank", zfje);
										}else if("1".equals(zffs)){
											//现金支付
											yjZfmxObj.put("payByCash", zfje);
										}else{
											//支票支付
											yjZfmxObj.put("payByZhiPiao",zfje);
										}
										yjZfmxArr.add(yjZfmxObj);
									}

									//获取报销方式
									BizUtils bizUtils = new BizUtils();
									String tableNameNew = bizUtils.getTableNameByRequestId(reqid);
									RecordSet sqlFindbxfs = new RecordSet();
									Integer bxfsNew = 0;
									sqlFindbxfs.execute("SELECT bxfs FROM "+tableNameNew+" WHERE REQUESTID = "+reqid);
									if(sqlFindbxfs.next()){
										bxfsNew = Util.getIntValue(sqlFindbxfs.getString("bxfs"));
									}
									if(bxfsNew == 1){
										obj.put("bxfs","月结对公");
										obj.put("zfmx", yjZfmxArr);
										bb.writeLog("是月结对公：" + obj.toJSONString());
									}else{
										obj.put("zfmx", zfmxArr);
										bb.writeLog("不是月结对公：" + obj.toJSONString());
									}
									jsonMap = JSONObject.toJavaObject(obj, Map.class);
								}

								bb.writeLog("付款开始调用核算接口：" + obj.toJSONString());
								String res = "";
								if(StringUtil.isNotEmpty(Util.null2String(obj.get("fkdh")))){
									res = Util.null2String(ht.saveFydj(jsonMap));
								}
								bb.writeLog("付款核算接口响应结果：" + res);
								if (!"".equals(res)) {
									if ("success".equals(res) || "master_success".equals(res) || "slave_success".equals(res)) {//成功
										//更新【同步核算】字段值为已同步
//                                    rs_up.execute("update uf_zfmx set tbhs = '0' where id = "+id);
										isHS = true;
									} else {
										apiDatas.put("api_status", false);
										apiDatas.put("msg", "【" + lcbm + "】--核算返回错误！--->" + res);
										return JSONObject.toJSONString(apiDatas);
									}
								} else {
									apiDatas.put("api_status", false);
									apiDatas.put("msg", "【" + lcbm + "】--核算响应为空！");
									return JSONObject.toJSONString(apiDatas);
								}
								//处理核算END
								bb.writeLog("付款的结果：", isHS + "+" + isYS);
								if (!isHS && !isYS) {//当两个都失败的时候
									bb.writeLog("编码：" + lcbm + "更新预算与核算均失败！");
								} else {
									String sqlupString = "";
									if (isYS) {
										sqlupString += ",tbys = 0";
									}
									if (isHS) {
										//核算更新支付单号
										sqlupString += ",tbhs = 0,ZFDH='" + newOrderNo + "'";

									}
									String sqlup = "update uf_zfmx set fkzt = 0 ,fksj = '" + sdf.format(new Date()) + "' where id = " + id;
									if (!"".equals(sqlupString)) {
										sqlup = "update uf_zfmx set fkzt = 0 ,fksj = '" + sdf.format(new Date()) + "'" + sqlupString + " where id = " + id;
									}
									rs_up.execute(sqlup);
									JAVATools.SetCmdwritelog("更新支付单号:sqlup"+sqlup+"id:"+id);

									String updateMiddleTab = "update uf_lhyfkmiddle set sffkqr = 1 where reqid = " + reqid;
									rs_midtab.execute(updateMiddleTab);
									JAVATools.SetCmdwritelog("更新预付款管理台账:updateMiddleTab"+updateMiddleTab+" reqid:"+reqid);

									//已付款 预付款管理台账（联合通用、工会）
									String updatePrepay ="update uf_PrepayMageAccRep set FKZT= 0 where REQUTID = " + reqid;
									rs_Prepay.execute(updatePrepay);
									JAVATools.SetCmdwritelog("预付款管理台账付款状态：已付款"+updatePrepay+"reqid："+reqid);

									//#HTO-13508# 【财务】联合流程同步资金中间表逻辑优化
									try {
										JAVATools.SetCmdwritelog("===============更新联合流程同步资金中间表===============");
										JAVATools.SetCmdwritelog("流程编码：" + lcbm);
										String mainTableName = ht.getTableNameByRequestid(reqid, "0");
										JAVATools.SetCmdwritelog("流程主表名：" + mainTableName);

										String sqlLclx = "select b.unnumber as lclx from workflow_requestbase a join workflow_base b on a.WORKFLOWID = b.id where a.REQUESTID = ?";
										String lclx = "";
										rs_lclx.executeQuery(sqlLclx, reqid);
										if (rs_lclx.next()) {
											lclx = Util.null2String(rs_lclx.getString("lclx"));
										}
										if ("".equals(lclx)) {
											JAVATools.SetCmdwritelog("流程类型为空");
											return JSONObject.toJSONString(apiDatas);
										}
										if ("clbx".equals(lclx) || "lhtyfk".equals(lclx) || "lhtybx".equals(lclx) || "lhghfk".equals(lclx)) {
											if ("clbx".equals(lclx)) {
												//联合差旅报销
												String detailTableName = mainTableName + "_dt10";
												if (isFZF(reqid, mainTableName)) {
													JAVATools.SetCmdwritelog("requestId:" + reqid + " 全是非自付费用 不写资金表");
													return JSONObject.toJSONString(apiDatas);
												}
												JAVATools.SetCmdwritelog("requestId:" + reqid + " 开始写入资金系统表,差旅报销名:" + mainTableName);
												Map<String, Object> map = getOAMainData(reqid, mainTableName, id, newOrderNo);

												String str = "select * from OAFKZJB t where t.OAFKZJB_OAID = '" + map.get("OAFKZJB_OAID") + "'";
												rsdM.execute(str);
												if (rsdM.next()) {
													JAVATools.SetCmdwritelog("资金中间表存在本条流程数据: " + map.get("OAFKZJB_OAID"));
													return JSONObject.toJSONString(apiDatas);
												}

												innserttable(map, "OAFKZJB");
												JAVATools.SetCmdwritelog("requestId:" + reqid + " 写入资金中间表主表完成");

												List<List<Object>> insertList = getOADetailData(reqid, mainTableName, detailTableName, newOrderNo);
												String sqlTable = "OAFKZJBMX_OABH,OAFKZJBMX_DFDWMC,OAFKZJBMX_DFYHZH,OAFKZJBMX_DFHM,OAFKZJBMX_BXRGH," +
														"OAFKZJBMX_DFKHH,OAFKZJBMX_DFSF,OAFKZJBMX_DFCS,OAFKZJBMX_JE,OAFKZJBMX_JSZT,OAFKZJBMX_DATE";
												String sqlTableE = "?,?,?,?,?,?,?,?,?,?,to_date(?, 'yyyy-MM-dd HH24:mi:ss')";
												insertList(sqlTable, sqlTableE, insertList, "FinanceM", "OAFKZJBMX");
												JAVATools.SetCmdwritelog("requestId:" + reqid + " 写入资金中间表明细表完成");
											} else if ("lhtyfk".equals(lclx) || "lhghfk".equals(lclx)) {
												//联合通用付款，联合工会付款
												RecordSet rs_fk = new RecordSet();
												SimpleDateFormat sdfBJRQ = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
												SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

												String tableNameDt = mainTableName + "_dt11";
												//工会付款时存在dt13表
												String tableNameDt13 = mainTableName + "_dt13";

												JAVATools.SetCmdwritelog("写入资金系统表", "主表为" + mainTableName);
												String sqlMain = "select r.id ,r.requestid,r.lcbh,r.requestId,r.szbm,r.bz,r.ngsj,r.ngr ,d.DEPARTMENTNAME,d.DEPARTMENTCODE,s.LASTNAME,s.workcode from " + mainTableName + " r,hrmdepartment d,hrmresource s where r.szbm = d.id and s.id = r.ngr  and REQUESTID = " + reqid + "";
												rs_fk.execute(sqlMain);
												JAVATools.SetCmdwritelog("查询" + mainTableName + "语句:" + sqlMain);
												Map<String, Object> map = new HashMap<>();
												String mainId = "";
												if (rs_fk.next()) {
													mainId = Util.null2String(rs_fk.getString("id"));
													map.put("OAFKZJB_OAID", Util.null2String(rs_fk.getString("lcbh")));
													map.put("OAFKZJB_ZDDW", Util.null2String(rs_fk.getString("DEPARTMENTCODE")));
													map.put("OAFKZJB_DWBH", Util.null2String(rs_fk.getString("DEPARTMENTCODE")));
													map.put("OAFKZJB_FKBMMC", Util.null2String(rs_fk.getString("DEPARTMENTNAME")));
													map.put("OAFKZJB_BZ", Util.null2String(rs_fk.getString("bz")));
													String timeStr = Util.null2String(rs_fk.getString("ngsj"));
													timeStr = timeStr + ":00";
													String[] timeStrs = timeStr.split(" ");
													String[] dataStrs = timeStrs[0].split("-");
													map.put("OAFKZJB_SQRQ", dataStrs[0] + dataStrs[1] + dataStrs[2]);
													map.put("OAFKZJB_SQSJ", timeStrs[1]);
													map.put("OAFKZJB_JSZT", "0");
													//拟稿人
													map.put("OAFKZJB_SQR", Util.null2String(rs_fk.getString("LASTNAME")));
													//拟稿人工号
													map.put("OAFKZJB_SQRGH", Util.null2String(rs_fk.getString("workcode")));
													String date = sdfBJRQ.format(new Date());
													String[] newDates = date.split(" ");
													map.put("OAFKZJB_BJRQ", newDates[0]);
													map.put("OAFKZJB_BJSJ", newDates[1]);
												}

												String str = "select * from OAFKZJB t where t.OAFKZJB_OAID = '" + map.get("OAFKZJB_OAID") + "'";
												rsdM.execute(str);
												if (rsdM.next()) {
													JAVATools.SetCmdwritelog("资金中间表存在本条流程数据: " + map.get("OAFKZJB_OAID"));
													return JSONObject.toJSONString(apiDatas);
												}

												String sqlUf = "select tyzfdh,fksj,dq from uf_zfmx where id = ?";
												rs_fk.executeQuery(sqlUf, id);
												if (rs_fk.next()) {
													map.put("OAFKZJB_OABH", newOrderNo);
													map.put("OAFKZJB_DATE", sdfDate.format(new Date()));
													String bxd = Util.null2String(Util.null2String(rs_fk.getString("dq")));
													switch (bxd) {
														case "0":
															map.put("OAFKZJB_BY4", 3);
															break;
														case "1":
															map.put("OAFKZJB_BY4", 2);
															break;
														case "2":
															map.put("OAFKZJB_BY4", 1);
															break;
														case "3":
															map.put("OAFKZJB_BY4", 4);
															break;
														default:
															map.put("OAFKZJB_BY4", 5);
															break;
													}
												}

												innserttable(map, "OAFKZJB");
												JAVATools.SetCmdwritelog("requestId:" + reqid + " 写入资金中间表主表完成");

												String sqlDetail = "select d.skdw,d.yxzh,d.khx,d.ss,d.dfkje,d.khxmc,d.yxzfje,d.fkfy from " + tableNameDt + " d where mainid = " + mainId + " and d.yxzh is not null and d.yxzfje !=0 and d.yxzfje !=0.00";
												JAVATools.SetCmdwritelog("查询" + tableNameDt + "语句:" + sqlDetail);
												rs_fk.execute(sqlDetail);
												List<List<Object>> insertList = new ArrayList<>();
												while (rs_fk.next()) {
													List<Object> list = new ArrayList<>();

													list.add(newOrderNo);
													//对skdw 进行格式化处理去除<br>
													String skdw = Util.null2String(rs_fk.getString("skdw")).replace("<br>", "");
													skdw = skdw.replace("&nbsp;", "");
													list.add(skdw);
													String regEx = "[^(0-9)]";
													Pattern p = Pattern.compile(regEx);
													Matcher m = p.matcher(Util.null2String(rs_fk.getString("yxzh")));
													list.add(m.replaceAll("").trim());
													list.add(skdw);
													list.add("");
													list.add(Util.null2String(rs_fk.getString("khxmc")));
													String area = Util.null2String(rs_fk.getString("ss"));
													List<String> areaArray = cityCodeToName(area);
													if (null != areaArray && areaArray.size() > 0) {
														list.add(areaArray.get(0));
														if (areaArray.size() > 1) {
															list.add(areaArray.get(1));
														} else {
															list.add("");
														}
													} else {
														list.add("");
														list.add("");
													}
													list.add(Util.null2String(rs_fk.getString("yxzfje")));
													list.add("0");
													list.add("0");
													list.add(Util.null2String(rs_fk.getString("fkfy")));
													list.add(sdfDate.format(new Date()));
													insertList.add(list);
												}

												String sqlIsGH = "select * from workflow_base t1 where t1.formid in (" +
														" select t2.id from workflow_bill t2 where tablename = '" + mainTableName.toLowerCase(Locale.ROOT) + "' ) " +
														" and t1.unnumber = 'lhghfk'";
												rs_fk.execute(sqlIsGH);
												if (rs_fk.next()) {
													String sqlDetail13 = "select s.lastname,d.yxzh,d.khx,d.ss,d.yxkzfje,d.fkfy from " + tableNameDt13 + " d ," +
															" hrmresource s where d.ygxm=s.id and d.mainid = " + mainId + " and d.yxkzfje !=0";
													JAVATools.SetCmdwritelog("查询" + tableNameDt13 + "语句:" + sqlDetail13);
													rs_fk.execute(sqlDetail13);
													while (rs_fk.next()) {
														List<Object> list = new ArrayList<>();
														list.add(newOrderNo);
														list.add(Util.null2String(rs_fk.getString("lastname")));
														//2021-9-8yxzh只保留数字
														String regEx = "[^(0-9)]";
														Pattern p = Pattern.compile(regEx);
														Matcher m = p.matcher(Util.null2String(rs_fk.getString("yxzh")));
														list.add(m.replaceAll("").trim());
														list.add(Util.null2String(rs_fk.getString("lastname")));
														list.add("");
														list.add(Util.null2String(rs_fk.getString("khx")));
														String area = Util.null2String(rs_fk.getString("ss"));
														List<String> areaArray = cityCodeToName(area);
														if (null != areaArray && areaArray.size() > 0) {
															list.add(areaArray.get(0));
															if (areaArray.size() > 1) {
																list.add(areaArray.get(1));
															} else {
																list.add("");
															}
														} else {
															list.add("");
															list.add("");
														}
														list.add(Util.null2String(rs_fk.getString("yxkzfje")));
														list.add("0");
														list.add("0");
														list.add(Util.null2String(rs_fk.getString("fkfy")));
														list.add(sdfDate.format(new Date()));
														insertList.add(list);
													}
												}
												String sqlTable = "OAFKZJBMX_OABH,OAFKZJBMX_DFDWMC,OAFKZJBMX_DFYHZH,OAFKZJBMX_DFHM,OAFKZJBMX_BXRGH," +
														"OAFKZJBMX_DFKHH,OAFKZJBMX_DFSF,OAFKZJBMX_DFCS,OAFKZJBMX_JE,OAFKZJBMX_DJZT,OAFKZJBMX_JSZT,OAFKZJBMX_YHBZ,OAFKZJBMX_DATE";
												String sqlTableE = "?,?,?,?,?,?,?,?,?,?,?,?,to_date(?, 'yyyy-MM-dd HH24:mi:ss')";
												insertList(sqlTable, sqlTableE, insertList, "FinanceM", "OAFKZJBMX");
												JAVATools.SetCmdwritelog("requestId:" + reqid + " 写入资金中间表明细表完成");
											} else {
												//联合通用报销
												String detailTableName = mainTableName + "_dt11";
												JAVATools.SetCmdwritelog("requestId:" + reqid + " 开始写入资金系统表,通用报销主表名:" + mainTableName);
												Map<String, Object> map = getOAMainData(reqid, mainTableName, id, newOrderNo);

												String str = "select * from OAFKZJB t where t.OAFKZJB_OAID = '" + map.get("OAFKZJB_OAID") + "'";
												rsdM.execute(str);
												if (rsdM.next()) {
													JAVATools.SetCmdwritelog("资金中间表存在本条流程数据: " + map.get("OAFKZJB_OAID"));
													return JSONObject.toJSONString(apiDatas);
												}
												innserttable(map, "OAFKZJB");
												JAVATools.SetCmdwritelog("requestId:" + reqid + " 写入资金中间表主表完成");

												List<List<Object>> insertList = getOADetailData(reqid, mainTableName, detailTableName, newOrderNo);
												String sqlTable = "OAFKZJBMX_OABH,OAFKZJBMX_DFDWMC,OAFKZJBMX_DFYHZH,OAFKZJBMX_DFHM,OAFKZJBMX_BXRGH," +
														"OAFKZJBMX_DFKHH,OAFKZJBMX_DFSF,OAFKZJBMX_DFCS,OAFKZJBMX_JE,OAFKZJBMX_JSZT,OAFKZJBMX_DATE";
												String sqlTableE = "?,?,?,?,?,?,?,?,?,?,to_date(?, 'yyyy-MM-dd HH24:mi:ss')";
												insertList(sqlTable, sqlTableE, insertList, "FinanceM", "OAFKZJBMX");
												JAVATools.SetCmdwritelog("requestId:" + reqid + " 写入资金中间表明细表完成");
											}
										}
									} catch (Exception e) {
										JAVATools.SetCmdwritelog("更新联合流程同步资金中间表失败：" + e.getMessage());
									}
								}
							}else{
								apiDatas.put("api_status", false);
								apiDatas.put("msg", "获取失败");
								return JSONObject.toJSONString(apiDatas);
							}
						}catch (Exception exo){
							JAVATools.SetCmdwritelog("更新到核算接口的付款单号获取失败"+exo.getMessage());
						}finally {
							JAVATools.SetCmdwritelog("付款单号获取解锁开始");
							RedisTools.releaseDistributedLock(jedis,rediskey,lcbm);
							JAVATools.SetCmdwritelog("付款单号获取解锁结束");
							JAVATools.SetCmdwritelog("付款单号获取释放锁开始");
							jedis.close();
							JAVATools.SetCmdwritelog("付款单号获取释放锁结束");
						}
					}
				}
			}

		} catch (Exception e) {
			apiDatas.put("api_status", false);
			apiDatas.put("msg", "失败");
			return JSONObject.toJSONString(apiDatas);
		}
		return JSONObject.toJSONString(apiDatas);
	}

	/**
	 * 获取二级会计科目名称
	 *
	 * @param code 二级会计科目编码
	 * @return 名称
	 */
	private String getEJKJKMMC(String code) {
		RecordSet rs = new RecordSet();
		if ("".equals(code)) {
			return "";
		}
		rs.executeQuery("select ejhjkmmc from uf_kjkm where ejhjkmbm = ?", new Object[]{code});
		rs.next();
		return Util.null2String(rs.getString(1));
	}

	/**
	 * 根据二级会计编码或取对应的二级预算科目编码和名称
	 *
	 * @param kjkmbm 二级会计编码
	 * @return 二级预算科目编码和名称
	 */
	private Map<String, String> getYSKM(String kjkmbm) {
		Map<String, String> result = new HashMap<>();
		if ("".equals(kjkmbm)) {
			return result;
		}
		String sql = "select ejyskmbm,ejyskmmc from uf_lhkm where ejhjkmbm = ? ";
		RecordSet rs = new RecordSet();
		rs.executeQuery(sql, new Object[]{kjkmbm});
		rs.next();
		result.put("code", Util.null2String(rs.getString("ejyskmbm")));//二级预算科目编码
		result.put("name", Util.null2String(rs.getString("ejyskmmc")));//二级预算科目名称
		return result;
	}

	/**
	 * 更新到核算接口的付款单号
	 * 点击核算时,更新年月日和四位序号
	 * 四位序号从数据库中获取
	 *
	 * @param oldOrderNo 转建模的系统序号
	 * @param lcbm 流程编码去匹配是否已成功同步
	 * @return 新的orderNo
	 */
	public String refreshOrderNo(String oldOrderNo, String lcbm,String reqid) throws Exception {
		try {
			RecordSet rs = new RecordSet();
			//支付单号已存在,且状态为已付款,直接返回该单号
			rs.executeQuery("select ID,REQID from UF_ZFMX where tbhs=0 AND lcbm='" + lcbm + "'");
			if (rs.next()) {
				log.info("支付单号已存在支付成功的,直接返回:@" + oldOrderNo + "@");
				return oldOrderNo;
			}
			if ("".equals(oldOrderNo)) {
				log.info("支付单号为空");
				return oldOrderNo;
			}
			DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyMMdd");
			String yyMMdd = LocalDate.now().format(ofPattern);
			StringBuilder newOrderNoBuilder = new StringBuilder(oldOrderNo);
			//替换当前年月日
			newOrderNoBuilder.replace(10, 16, yyMMdd);
			//联合通用付款前面替换为HTLHFK
			if(SubUnionBizUtil.equalsTableName(reqid, SubUnionBizUtil.LHTYFK)){
				newOrderNoBuilder.replace(0, 6, "HTLHFK");
			}
			//替换序号为%, 带入sql查询当前日期最新的序号
			newOrderNoBuilder.replace(16, oldOrderNo.length(), "%");
			String sql = "select ZFDH,to_number(substr(ZFDH, -4, 4)) as xh,substr(ZFDH, -8, 4) as yr from (\n" +
					"    select reqid,zfdh from uf_zfmx where TBHS=0 and zfdh LIKE '" + newOrderNoBuilder.toString() + "'\n" +
					"    ORDER BY zfdh DESC\n" +
					") where ROWNUM=1";
			rs.executeQuery(sql);
			StringBuilder order = new StringBuilder();
			if (rs.next()) {
				order = new StringBuilder((rs.getInt("xh") + 1) + "");
			} else {
				order = new StringBuilder("1");
			}
			//拼接字符串0
			while (order.length() < 4) {
				order.insert(0, "0");
			}
			return newOrderNoBuilder.toString().replace("%", order);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}
	}

	/**
	 * 获取开户行名称
	 * @param khx
	 * @return
	 */
	public String getKHXMC(String khx){
		String name = "";
		RecordSet rs = new RecordSet();
		String sql = String.format("select yxmc from %s where lxh = ?", "uf_khh");
		rs.executeQuery(sql, khx);
		while (rs.next()) {
			name = rs.getString("yxmc");
			break;
		}
		return name;
	}

	/**
	 * 判断是是否是非自付（非自付不写资金表）
	 *
	 * @param requestId
	 * @param mainTableName
	 */
	public boolean isFZF(String requestId, String mainTableName) {
		RecordSet rs = new RecordSet();
		String querySql = " select t.xj from " + mainTableName + "_dt12 t where t.mainid in ( select id from " + mainTableName + "  t where t.requestid = '" + requestId + "' )";
		JAVATools.SetCmdwritelog("requestId:" + requestId + " 查询是否为全部非自付SQL:" + querySql);
		BigDecimal totalZFB = new BigDecimal("0.00");
		rs.executeQuery(querySql);
		while (rs.next()) {
			BigDecimal tempB = (new BigDecimal(com.engine.integration.util.StringUtils.isEmpty(rs.getString("xj")) ? 0.00 : Double.parseDouble(rs.getString("xj")))).setScale(2, BigDecimal.ROUND_HALF_UP);
			JAVATools.SetCmdwritelog("requestId:" + requestId + " 查询是否为全部非自付小计金额tempB:" + tempB);
			totalZFB = (totalZFB.add(tempB).setScale(2, BigDecimal.ROUND_HALF_UP));
		}
		JAVATools.SetCmdwritelog("requestId:" + requestId + " 自付费用汇总金额 totalZFB:" + totalZFB);
		if (totalZFB.compareTo(BigDecimal.ZERO) == 0) {
			return true;//没有自付费用
		}
		return false;
	}

	/**
	 * 获取资金表主表数据
	 *
	 * @param requestId
	 * @param mainTableName
	 * @return
	 */
	Map<String, Object> getOAMainData(String requestId, String mainTableName, String id, String newOrderNo) {
		SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		RecordSet rs = new RecordSet();
		Map<String, Object> map = new HashMap<>();
		String lclx = "";
		String sqlMain = "";
		String sqlLclx = "select b.unnumber as lclx from workflow_requestbase a join workflow_base b on a.WORKFLOWID = b.id where a.REQUESTID = ?";
		rs.executeQuery(sqlLclx, requestId);
		if (rs.next()) {
			lclx = Util.null2String(rs.getString("lclx"));
		}
		if ("".equals(lclx)) {
			return map;
		}
		if (!"clbx".equals(lclx)) {
			sqlMain = " select r.id ,r.requestid,r.lcbh,r.requestId,r.szbm,r.bz,r.ngsj,r.ngr ,d.DEPARTMENTNAME,d.DEPARTMENTCODE,s.LASTNAME,s.workcode " +
					" from "+mainTableName+" r,hrmdepartment d,hrmresource s where r.szbm = d.id and s.id = r.ngr  and REQUESTID = '"+requestId+"'";
		} else {
			sqlMain = " select r.id ,r.requestid,r.lcbh,r.requestId,r.szbm,r.bz,r.ngrq as ngsj,r.ngr, r.bxd as dq,d.DEPARTMENTNAME,d.DEPARTMENTCODE,s.LASTNAME,s.workcode " +
					" from " + mainTableName + " r,hrmdepartment d,hrmresource s where r.szbm = d.id and s.id = r.ngr  and REQUESTID = '" + requestId + "'";
		}
		JAVATools.SetCmdwritelog("requestId:" + requestId + " 关联查询查询主表sql:" + sqlMain);
		rs.execute(sqlMain);
		if (rs.next()) {
			String lcbh = Util.null2String(rs.getString("lcbh"));
			String mainId = Util.null2String(rs.getString("id"));
			map.put("OAFKZJB_OAID", lcbh.startsWith("联合") ? lcbh : ("联合" + lcbh));
			map.put("OAFKZJB_ZDDW", Util.null2String(rs.getString("DEPARTMENTCODE")));
			map.put("OAFKZJB_DWBH", Util.null2String(rs.getString("DEPARTMENTCODE")));
			map.put("OAFKZJB_FKBMMC", Util.null2String(rs.getString("DEPARTMENTNAME")));
			map.put("OAFKZJB_BZ", Util.null2String(rs.getString("bz")));
			String timeStr = Util.null2String(rs.getString("ngsj"));
			timeStr = timeStr + ":00";
			String[] timeStrs = timeStr.split(" ");
			String[] dataStrs = timeStrs[0].split("-");
			map.put("OAFKZJB_SQRQ", dataStrs[0] + dataStrs[1] + dataStrs[2]);
			map.put("OAFKZJB_SQSJ", timeStrs[1]);
			map.put("OAFKZJB_JSZT", "0");
			map.put("OAFKZJB_SQR", Util.null2String(rs.getString("LASTNAME")));
			map.put("OAFKZJB_SQRGH", Util.null2String(rs.getString("workcode")));
			String date = sdf.format(new Date());
			String[] newDates = date.split(" ");
			map.put("OAFKZJB_BJRQ", newDates[0]);
			map.put("OAFKZJB_BJSJ", newDates[1]);
		}

		String sqlUf = "select tyzfdh,fksj,dq from uf_zfmx where id = ?";
		rs.executeQuery(sqlUf, id);
		if (rs.next()) {
			map.put("OAFKZJB_OABH", newOrderNo);
			map.put("OAFKZJB_DATE", sdfDate.format(new Date()));
			String bxd = Util.null2String(Util.null2String(rs.getString("dq")));
			switch (bxd) {
				case "0":
					map.put("OAFKZJB_BY4", 3);
					break;
				case "1":
					map.put("OAFKZJB_BY4", 2);
					break;
				case "2":
					map.put("OAFKZJB_BY4", 1);
					break;
				case "3":
					map.put("OAFKZJB_BY4", 4);
					break;
				default:
					map.put("OAFKZJB_BY4", 5);
					break;
			}
		}
		return map;
	}

	/**
	 * 获取资金表明细表数据
	 *
	 * @param requestId
	 * @param mainTableName
	 * @param dtTableName
	 * @return
	 */
	List<List<Object>> getOADetailData(String requestId, String mainTableName, String dtTableName, String newOrderNo) {
		SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		RecordSet rs = new RecordSet();
		List<List<Object>> insertList = new ArrayList<>();

		String lclx = "";
		String sqlDetail = "";
		String sqlLclx = "select b.unnumber as lclx from workflow_requestbase a join workflow_base b on a.WORKFLOWID = b.id where a.REQUESTID = ?";
		rs.executeQuery(sqlLclx, requestId);
		if (rs.next()) {
			lclx = Util.null2String(rs.getString("lclx"));
		}
		if (!"clbx".equals(lclx)) {
			sqlDetail = " select t0.requestid,t1.lastname,d.yxzh,t1.lastname,d.khxmc,d.ss,t1.workcode, d.yxzfje,d.xjzfje,t0.lcbh "+
					" from "+dtTableName+" d, "+ mainTableName +" t0,hrmresource t1 where t0.id = d.mainid and d.ygxm = t1.id and t0.requestid = '"+requestId+"'";
		} else {
			sqlDetail = "  select t0.requestid,t1.lastname,d.yxzh,t1.lastname,d.khxmc,d.ss,t1.workcode, d.yxzfje,d.xjzfje,t0.lcbh " +
					"  from "+dtTableName + " d,"+ mainTableName +" t0,hrmresource t1 where t0.id = d.mainid and d.bxr = t1.id and t0.requestid = '"+requestId+"'";
		}

		JAVATools.SetCmdwritelog("requestId:" + requestId + " 关联查询查询明细表sql:" + sqlDetail);
		rs.execute(sqlDetail);
		while (rs.next()) {
			List<Object> list = new ArrayList<>();
			list.add(newOrderNo);
			list.add(Util.null2String(rs.getString("lastname")));
			String regEx = "[^(0-9)]";
			Pattern p = Pattern.compile(regEx);
			Matcher m = p.matcher(Util.null2String(rs.getString("yxzh")));
			list.add(m.replaceAll("").trim());
			list.add(Util.null2String(rs.getString("lastname")));
			list.add(Util.null2String(rs.getString("workcode")));
			list.add(Util.null2String(rs.getString("khxmc")));
			String area = Util.null2String(rs.getString("ss"));
			List<String> areaArray = cityCodeToName(area);
			if (null != areaArray && areaArray.size() > 0) {
				list.add(areaArray.get(0));
				if (areaArray.size() > 1) {
					list.add(areaArray.get(1));
				} else {
					list.add("");
				}
			} else {
				list.add("");
				list.add("");
			}
			BigDecimal b = BigDecimal.valueOf(com.engine.integration.util.StringUtils.isEmpty(rs.getString("yxzfje")) ? 0.00 : Double.parseDouble(rs.getString("yxzfje")));
			list.add(b.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
			list.add("0");
			list.add(sdfDate.format(new Date()));
			//金额为0的情况不写入资金明细表 且 银行账户不为空
			if (b.compareTo(BigDecimal.ZERO) > 0 && null != rs.getString("yxzh") && org.apache.commons.lang.StringUtils.isNotEmpty(rs.getString("yxzh"))) {
				insertList.add(list);
			}
		}
		return insertList;
	}

	//插入表
	public static boolean innserttable(Map<String, Object> mapvalue, String tablename) {
		boolean flag = true;
		String dttablename = "";
		String dttablenvalue = "";
		List<String> list = new ArrayList<>();
		JAVATools.SetCmdwritelog("新表插入:", "表名" + tablename);
		for (Map.Entry<String, Object> entry : mapvalue.entrySet()) {
			String fieldname = Util.null2String(entry.getKey());
			String fieldvalue = Util.null2String(entry.getValue());
			JAVATools.SetCmdwritelog(" key: " + fieldname + " value:" + fieldvalue);
			dttablename += dttablename == "" ? fieldname : "," + fieldname;
			//为了解决文字与格式字符串不匹配
			switch (fieldname) {
				case "OAFKZJB_BY4":
					dttablenvalue += dttablenvalue == "" ? Lengthmax(fieldvalue.replace("\r\n", ""), 150) : "," + Lengthmax(fieldvalue.replace("\r\n", ""), 150);
					break;

				case "OAFKZJB_DATE":
					dttablenvalue += dttablenvalue == "" ? "to_date('" + Lengthmax(fieldvalue.replace("\r\n", ""), 150) + "', 'yyyy-MM-dd HH24:mi:ss')" : ",to_date('" + Lengthmax(fieldvalue.replace("\r\n", ""), 150) + "', 'yyyy-MM-dd HH24:mi:ss')";
					break;

				default:
					dttablenvalue += dttablenvalue == "" ? "'" + Lengthmax(fieldvalue.replace("\r\n", ""), 150) + "'" : ",'" + Lengthmax(fieldvalue.replace("\r\n", ""), 150) + "'";
					break;
			}
		}
		String sql = "insert into " + tablename + "(" + dttablename + ") values(" + dttablenvalue + ")";
		JAVATools.SetCmdwritelog(" sql: " + sql);
		JAVATools.SetCmdwritelog(" sql: " + list.toString());
		try {
			RecordSetDataSource rsdM = new RecordSetDataSource("FinanceM");
			flag = rsdM.execute(sql);
		} catch (Exception exo) {
			flag = false;
			exo.printStackTrace();
			new BaseBean().writeLog("插入明细表失败:" + exo.getMessage());
		}
		return flag;
	}

	//批量插入表单，切换数据源
	public boolean insertList(String sqlTableS, String sqlTableE, List<List<Object>> insertList, String sqlData, String tablename) {
		boolean flag = true;
		try {
			RecordSet rs = new RecordSet();
			JAVATools.SetCmdwritelog("新表插入:", "表名" + tablename + "数据源为" + sqlData);
			JAVATools.SetCmdwritelog("sql:" + String.format("insert into %s (" + sqlTableS + ") values(" + sqlTableE + ") ", tablename));
			JAVATools.SetCmdwritelog("数据:" + insertList);
			//批量插入并切换数据源
			flag = rs.executeBatchSql(String.format("insert into %s (" + sqlTableS + ") values(" + sqlTableE + ") ", tablename), insertList, sqlData);
		} catch (Exception exo) {
			flag = false;
			exo.printStackTrace();
			new BaseBean().writeLog("插入明细表失败:" + exo.getMessage());
		}
		return flag;
	}

	public static String Lengthmax(String value, Integer sum) {
		if ("".equals(value)) {
			return "";
		}
		if (value.length() > sum) {
			value = value.substring(0, sum - 1);
		}
		return value;
	}

	public static List<String> cityCodeToName(String code) {
		RecordSet rs = new RecordSet();
		List<String> resultList = new ArrayList<>();
		if (com.engine.integration.util.StringUtils.isBlank(code)) {
			return resultList;
		}
		String[] desInfo = code.split(",");
		String ids = Arrays.stream(desInfo).map(s -> "\'" + s + "\'").collect(Collectors.joining(","));
		String sql = "select name from uf_city where code in (" + ids + ") order by instr('" + code + "',code)";
		rs.executeQuery(sql);
		while (rs.next()) {
			resultList.add(rs.getString("name"));
		}
		return resultList;
	}
}
