package nc.ui.hr.baod_orders.view;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Vector;
import java.util.Map.Entry;

import javax.swing.JProgressBar;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.hr.plugin.GetDataUtil;
import nc.desktop.ui.WorkbenchEnvironment;
import nc.hr.utils.OutputDialogUtil;
import nc.itf.hr.IReceivableService;
import nc.itf.hr.SocialInsuranceAllMaintain;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.BeanProcessor;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.log.NcLog;
import nc.ui.pub.ButtonObject;
import nc.ui.pub.ToftPanel;
import nc.ui.pub.beans.MessageDialog;
import nc.ui.pub.beans.UILabel;
import nc.ui.pub.beans.UIPanel;
import nc.ui.pub.beans.UIRefPane;
import nc.ui.pub.beans.UITablePane;
import nc.ui.pub.beans.ValueChangedEvent;
import nc.ui.pub.beans.ValueChangedListener;
import nc.ui.pub.link.BillLinkOneNodeCenter;
import nc.vo.arap.receivable.AggReceivableBillVO;
import nc.vo.arap.receivable.ReceivableBillItemVO;
import nc.vo.arap.receivable.ReceivableBillVO;
import nc.vo.fipub.exception.ExceptionHandler;
import nc.vo.fipub.freevalue.Module;
import nc.vo.gl.pubvoucher.DetailVO;
import nc.vo.gl.pubvoucher.OperationResultVO;
import nc.vo.gl.pubvoucher.VoucherVO;
import nc.vo.glcom.ass.AssVO;
import nc.vo.glcom.tools.GLPubProxy;
import nc.vo.pub.BusinessException;
import nc.vo.pub.SuperVO;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.data.ValueUtils;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.pub.MathTool;
import nc.vo.uap.rbac.profile.FunctionPermProfileManager;

/**
 * 公积金分摊表
 * 
 * @author YaoYu
 * 
 */
public class AccumulationFundAllocationUI extends ToftPanel {
	private IUAPQueryBS iuap = (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
	private ButtonObject bt_query = new ButtonObject("查询", "", 2, "bt_query");
	private ButtonObject bt_insert = new ButtonObject("新增", "", 2, "bt_insert");
	private ButtonObject bt_update = new ButtonObject("修改", "", 2, "bt_update");
	private ButtonObject bt_output = new ButtonObject("导出", "", 2, "bt_output");
	private ButtonObject bt_voucher = new ButtonObject("生成凭证", "", 2, "bt_voucher");
	private ButtonObject bt_linkvouchar = new ButtonObject("联查凭证", "", 2, "bt_linkvouchar");
	private ButtonObject bt_arrecbill = new ButtonObject("生成内部应收单", "", 2, "bt_arrecbill");

	private JProgressBar pb;
	private UITablePane tablepanel = null;
	private UIPanel ivjUIPanel0 = null;
	private UIPanel ivjUIPanel2 = null;
	private UIPanel ivjUIPanel4 = null;
	private UIPanel ivjUIPanel45 = null;
	private UILabel ivjOrgLabel = null;
	private UILabel ivjperiodLabel = null;
	private UIRefPane ivjcostcpanel = null;
	private UIRefPane ivjOrgPanel = null;
	private UIRefPane ivjperiodpanel = null;
	private UITablePane ivjTablePanel = null;
	private String[] subheading = { "序号", "员工编号", "姓名", "缴费基数", "个人部分", "公司部分", "备注" };
	private String orgCode;// 查询组织
	private String period;// 查询期间
	private Map<String, Map<String, UFDouble>> beforePsgMoney = null;// 处理前金额
	private Map<String, Map<String, UFDouble>> afterPsgMoney = null;// 处理后金额
	Map<String, Map<String, String>> middleTableData = null;// 中间表数据
	private SocialInsuranceAllMaintain siaMaintain = NCLocator.getInstance().lookup(SocialInsuranceAllMaintain.class);
	private Map<String, UFDouble> tableFourSelfMap = null;// 表四（凭证）
	private Map<String, UFDouble> tableOneOrgMap = null;// 表一（凭证）
	private Map<String, UFDouble> tableSixSelfMap = null;// 表六（凭证）
	private Map<String, UFDouble> tableSevenSelfMap = null;// 表七（凭证）

	public AccumulationFundAllocationUI() {
		initialize();
		tablepanel = getTablePanel();
	}

	@Override
	public String getTitle() {
		return "公积金分摊表";
	}

	public void initialize() {
		setLayout(new BorderLayout());
		add(getUIPanel0(), BorderLayout.NORTH);
		add(getUIPanel2(), BorderLayout.CENTER);
		add(getUIPanel4(), BorderLayout.SOUTH);
		setButtons(new ButtonObject[] { this.bt_query, this.bt_insert, this.bt_update, this.bt_output, this.bt_voucher, this.bt_linkvouchar, this.bt_arrecbill });// 添加按钮
	}

	private UILabel getOrgLabel() {
		if (this.ivjOrgLabel == null) {
			this.ivjOrgLabel = new UILabel();
			this.ivjOrgLabel.setName("pkorg");
			this.ivjOrgLabel.setText("财务组织");
		}
		return this.ivjOrgLabel;
	}

	private UIRefPane getOrgPanel() {
		if (this.ivjOrgPanel == null) {
			// 节点编码
			String nodeCode = "60H20104";
			this.ivjOrgPanel = new UIRefPane();
			this.ivjOrgPanel.setName("pkorg");
			this.ivjOrgPanel.setRefNodeName("财务组织");
			// 权限组织
			String[] pkorgs = FunctionPermProfileManager.getInstance().getProfile(WorkbenchEnvironment.getInstance().getLoginUser().getUser_code()).getFuncSubInfo(nodeCode).getFuncPermissionPkorgs();
			this.ivjOrgPanel.getRefModel().setFilterPks(pkorgs);

			this.ivjOrgPanel.setBounds(new Rectangle(100, 20));
			this.ivjOrgPanel.setPreferredSize(new Dimension(170, 20));
			// this.ivjOrgPanel.setMultiSelectedEnabled(true);
			this.ivjOrgPanel.addValueChangedListener(new ValueChangedListener() {
				public void valueChanged(ValueChangedEvent e) {
					AccumulationFundAllocationUI.this.initialize();
				}
			});
		}
		return this.ivjOrgPanel;
	}

	private UILabel getperiodclabel() {
		if (this.ivjperiodLabel == null) {
			this.ivjperiodLabel = new UILabel();
			this.ivjperiodLabel.setName("period");
			this.ivjperiodLabel.setText("年月");
		}
		return this.ivjperiodLabel;
	}

	private UIRefPane getperiodpanel() {
		if (this.ivjperiodpanel == null) {
			this.ivjperiodpanel = new UIRefPane();
			this.ivjperiodpanel.setName("period");
			this.ivjperiodpanel.setRefNodeName("会计期间档案");
			this.ivjperiodpanel.setBounds(new Rectangle(100, 20));
			this.ivjperiodpanel.setPreferredSize(new Dimension(170, 20));
			this.ivjperiodpanel.addValueChangedListener(new ValueChangedListener() {
				public void valueChanged(ValueChangedEvent e) {
					AccumulationFundAllocationUI.this.initialize();
				}
			});
		}
		return this.ivjperiodpanel;
	}

	private UIPanel getUIPanel0() {
		if (this.ivjUIPanel0 == null) {
			try {
				this.ivjUIPanel0 = new UIPanel();
				this.ivjUIPanel0.setLayout(new BorderLayout());
				UIPanel sel = new UIPanel();
				sel.setLayout(new FlowLayout());
				sel.add(getOrgLabel());
				sel.add(getOrgPanel());
				sel.add(getperiodclabel());
				sel.add(getperiodpanel());
				this.ivjUIPanel0.add(sel, BorderLayout.WEST);
			} catch (Throwable ivjExc) {
				handleException(ivjExc);
			}
		}
		return this.ivjUIPanel0;
	}

	private UIPanel getUIPanel4() {
		if (this.ivjUIPanel4 == null) {
			this.ivjUIPanel4 = new UIPanel();
			this.ivjUIPanel4.setLayout(new BorderLayout());
			this.ivjUIPanel4.add(getUILabel45(), BorderLayout.CENTER);
		}
		return this.ivjUIPanel4;
	}

	private UIPanel getUILabel45() {
		if (this.ivjUIPanel45 == null) {
			try {
				this.ivjUIPanel45 = new UIPanel();
				this.ivjUIPanel45.setName("UIPanel3");
				this.ivjUIPanel45.setPreferredSize(new Dimension(0, 10));
				this.ivjUIPanel45.setLayout(new BorderLayout());
				this.ivjUIPanel45.add(getprogressbar(), BorderLayout.EAST);
			} catch (Throwable ivjExc) {
				handleException(ivjExc);
			}
		}
		return this.ivjUIPanel45;
	}

	private void handleException(Throwable e) {
		ExceptionHandler.consume(e);
	}

	private JProgressBar getprogressbar() {
		if (this.pb == null) {
			this.pb = new JProgressBar();
			this.pb.setIndeterminate(false);
		}
		return this.pb;
	}

	private UIPanel getUIPanel2() {
		if (this.ivjUIPanel2 == null) {
			this.ivjUIPanel2 = new UIPanel();
			this.ivjUIPanel2.setLayout(new BorderLayout());
			this.ivjUIPanel2.setPreferredSize(new Dimension(0, 500));
			this.ivjUIPanel2.add(getTablePanel(), BorderLayout.CENTER);
		}
		return this.ivjUIPanel2;
	}

	private UITablePane getTablePanel() {
		if (this.ivjTablePanel == null) {
			try {
				this.ivjTablePanel = new UITablePane();
				this.ivjTablePanel.setName("TablePanel");
				this.ivjTablePanel.setLayout(new CardLayout());
			} catch (Throwable ivjExc) {

			}
		}
		return this.ivjTablePanel;
	}

	private Vector<Object> convertovector(Object[] objArray) {
		if (objArray == null) {
			return null;
		}
		Vector<Object> v = new Vector<Object>(objArray.length);
		for (int i = 0; i < objArray.length; i++) {
			v.addElement(objArray[i]);
		}
		return v;
	}

	@Override
	public void onButtonClicked(ButtonObject bt) {
		try {
			// 停止编辑;
			getOrgPanel().stopEditing();
			getperiodpanel().stopEditing();
			orgCode = getOrgPanel().getRefModel().getRefCodeValue();
			Vector periodData = getperiodpanel().getRefModel().getSelectedData();
			if (periodData != null && periodData.size() > 0) {
				Vector v = (Vector) periodData.get(0);
				period = v.get(0).toString();
			}
			if(orgCode == null || period == null) {
				ExceptionUtils.wrappBusinessException("财务组织、年月必须选择，请选择后再操作！");
			}
			if ("bt_query".equals(bt.getCode())) {
				tableProcessing();
			} else if ("bt_insert".equals(bt.getCode())) {
				insert();
			} else if ("bt_update".equals(bt.getCode())) {
				update(getTablePanel());
			} else if ("bt_output".equals(bt.getCode())) {
				onoutput();
			} else if ("bt_linkvouchar".equals(bt.getCode())) {
				String pkvouchersql = "select voucher_pk from voucher_flag where tablename='公积金分摊表' and orgcode='" + orgCode + "' and period='" + period + "' and nvl(dr,0)=0 ";
				Object voucher_pk = iuap.executeQuery(pkvouchersql, new ColumnProcessor());
				if (null != voucher_pk) {
					String sqlvoucher = "select num from gl_voucher where pk_voucher='" + voucher_pk + "' ";
					Object vouchernum = iuap.executeQuery(sqlvoucher, new ColumnProcessor());
					if (null != vouchernum) {
						VoucherVO[] aggvos = GLPubProxy.getRemoteVoucher().queryByPks(new String[] { voucher_pk.toString() });
						BillLinkOneNodeCenter.linkQuery_Dialog(this, "C0", new String[] { voucher_pk.toString() }, aggvos, true);
					}
				}
			} else if ("bt_voucher".equals(bt.getCode())) {
				String pkvouchersql = "select voucher_pk from voucher_flag where tablename='公积金分摊表' and orgcode='" + orgCode + "' and period='" + period + "' and nvl(dr,0)=0 ";
				Object voucher_pk = iuap.executeQuery(pkvouchersql, new ColumnProcessor());
				if (null != voucher_pk) {
					String sqlvoucher = "select num from gl_voucher where pk_voucher='" + voucher_pk + "' ";
					Object vouchernum = iuap.executeQuery(sqlvoucher, new ColumnProcessor());
					if (null != vouchernum) {
						ExceptionUtils.wrappBusinessException("付款凭证【" + vouchernum + "】已经生成!不能重复生成!");
					} else {
						// 凭证已经被删除，更新中间库
						StringBuilder insertSQL = new StringBuilder("update  voucher_flag set dr=1 where voucher_pk='" + voucher_pk + "' ");
						siaMaintain.executeBaseDAO(insertSQL.toString());
					}
				}
				MessageDialog.showHintDlg(this, "", "生成凭证开始");
				// 组装生成凭证数据
				Map<String, UFDouble> voucheramount = getVoucherAmount(getTablePanel());
				VoucherVO voucher = getVoucherVO(voucheramount);
				for (DetailVO detail : voucher.getDetails()) {
					if (detail.getAss() != null && detail.getAss().length > 0) {
						String assIDs = GLPubProxy.getRemoteFreevaluePub().getAssID_RequiresNew(detail.getAss(), false, "", InvocationInfoProxy.getInstance().getGroupId(), Module.GL);
						detail.setAssid(assIDs);
					}
				}
				OperationResultVO[] rs = GLPubProxy.getRemoteVoucher().save((VoucherVO) voucher, new Boolean(true));
				// 保存已经生成凭证的标识pk
				String pk = rs[0].m_strPK;
				StringBuilder insertSQL = new StringBuilder("insert into voucher_flag (TABLENAME, ORGCODE, PERIOD,  VOUCHER_PK) values (");
				insertSQL.append("'").append("公积金分摊表").append("',");
				insertSQL.append("'").append(orgCode).append("', ");
				insertSQL.append("'").append(period).append("', ");
				insertSQL.append("'").append(pk).append("'); ");
				siaMaintain.executeBaseDAO(insertSQL.toString());
				MessageDialog.showHintDlg(this, "提示", "凭证已生成");
			} else if ("bt_arrecbill".equals(bt.getCode())) {
				// 验证内部应收是否存在
				String pk_recbillsql = "select pk_recbill from ar_recbill where def11='公积金分摊表_" + orgCode + "_" + period + "' and nvl(dr,0)=0 ";
				Object pk_recbill = iuap.executeQuery(pk_recbillsql, new ColumnProcessor());
				if (null != pk_recbill) {
					ExceptionUtils.wrappBusinessException("内部应收单【" + period + "】已经生成!不能重复生成!");
				}
				//2025-06-10 start
				if(null == tableFourSelfMap||tableFourSelfMap.isEmpty()) {
					ExceptionUtils.wrappBusinessException("本月无数据!");
				}
				//2025-06-10 end
				MessageDialog.showHintDlg(this, "", "生成内部应收单开始");
				// 组装应收单数据新增应收单
				String billNO = addReceivableBill(getTablePanel());
				MessageDialog.showHintDlg(this, "提示", "内部应收单已生成 " + billNO);
			}
		} catch (Exception e) {
			e.printStackTrace();
			NcLog.info(e.getMessage());
			MessageDialog.showHintDlg(this, "提示", e.getMessage());
		}
	}

	/**
	 * 表格渲染
	 * 
	 * @param orgCode
	 * @param period
	 * @throws Exception
	 */
	private void tableProcessing() throws Exception {
		// 初始化
		beforePsgMoney = new HashMap<String, Map<String, UFDouble>>();
		afterPsgMoney = new HashMap<String, Map<String, UFDouble>>();
		middleTableData = new HashMap<String, Map<String, String>>();
		queryMiddleTable();
		String[] m_sTitle = { null, null, null, null, null, null, null, null, null };
		List<Object[]> dataList = new ArrayList<Object[]>();
		for (int i = 0; i < 11; i++) {
			Object[] row = new Object[0];
			dataList.add(row);
		}
		Map<String, Map<String, UFDouble>> tableMap = new HashMap<String, Map<String, UFDouble>>();
		List<Map<String, String>> tableOne = queryTableOne(orgCode, period);
		moneyDispose("表一：由个人承担", tableOne);
		List<Map<String, String>> tableTwo = queryTableTwo(orgCode, period);
		moneyDispose("表二：由外部公司承担", tableTwo);
		List<Map<String, String>> tableThree = queryTableThree(orgCode, period);
		moneyDispose("表三：由部门承担或全额公司承担", tableThree);
		List<Map<String, String>> tableFour = queryTableFour(orgCode, period);
		moneyDispose("表四：个人部分已在集团内其他公司扣除", tableFour);
		List<Map<String, String>> tableFive = queryTableFive(orgCode, period);
		moneyDispose("表五：月薪工资表中当月扣当月缴纳", tableFive);
		List<Map<String, String>> tableSix = queryTableSix(orgCode, period);
		moneyDispose("表六：实际已缴当月工资个人部分未扣", tableSix);
		List<Map<String, String>> tableSeven = queryTableSeven(orgCode, period);
		moneyDispose("表七：实际未缴当月工资个人部分已扣", tableSeven);
		List<Map<String, String>> TableEight = queryTableEight(orgCode, period);
		moneyDispose("表八：实际集团内其他公司已缴当月工资个人部分已扣", TableEight);
		tableMap.put("tableOne", addTableToList("1-", dataList, "表一：由个人承担", tableOne));
		tableMap.put("tableTwo", addTableToList("2-", dataList, "表二：由外部公司承担", tableTwo));
		tableMap.put("tableThree", addTableToList("3-", dataList, "表三：由部门承担或全额公司承担", tableThree));
		tableMap.put("tableFour", addTableToList("4-", dataList, "表四：个人部分已在集团内其他公司扣除", tableFour));
		tableMap.put("tableFive", addTableToList("5-", dataList, "表五：月薪工资表中当月扣当月缴纳", tableFive));
		tableMap.put("tableSix", addTableToList("6-", dataList, "表六：实际已缴当月工资个人部分未扣", tableSix));
		tableMap.put("tableSeven", addTableToList("7-", dataList, "表七：实际未缴当月工资个人部分已扣", tableSeven));
		tableMap.put("TableEight", addTableToList("8-", dataList, "表八：实际集团内其他公司已缴当月工资个人部分已扣", TableEight));
		UFDouble tableOneStaff = tableMap.get("tableOne").get("staff");// 个人承担个人部分
		UFDouble tableOneOrg = tableMap.get("tableOne").get("org");// 个人承担公司部分
		UFDouble tableTwoStaff = tableMap.get("tableTwo").get("staff");// 外部公司承担个人部分
		UFDouble tableTwoOrg = tableMap.get("tableTwo").get("org");// 外部公司承担公司部分
		UFDouble tableThreeStaff = tableMap.get("tableThree").get("staff");// 部门承担或全额公司承担个人部分
		UFDouble tableThreeOrg = tableMap.get("tableThree").get("org");// 部门承担或全额公司承担公司部分
		UFDouble tableFourStaff = tableMap.get("tableFour").get("staff");// 个人部分已在集团内其他公司扣除个人部分
		UFDouble tableFourOrg = tableMap.get("tableFour").get("org");// 个人部分已在集团内其他公司扣除公司部分
		UFDouble tableFiveStaff = tableMap.get("tableFive").get("staff");// 月薪工资表中当月扣当月缴纳个人部分
		UFDouble tableFiveOrg = tableMap.get("tableFive").get("org");// 月薪工资表中当月扣当月缴纳公司部分
		UFDouble tableSixStaff = tableMap.get("tableSix").get("staff");// 实际已缴当月工资个人部分未扣个人部分
		UFDouble tableSixOrg = tableMap.get("tableSix").get("org");// 实际已缴当月工资个人部分未扣公司部分
		UFDouble tableSevenStaff = tableMap.get("tableSeven").get("staff");// 实际未缴当月工资个人部分已扣个人部分
		UFDouble tableSevenOrg = tableMap.get("tableSeven").get("org");// 实际未缴当月工资个人部分已扣公司部分
		UFDouble tableEightStaff = tableMap.get("TableEight").get("staff");// 实际集团内其他公司已缴当月工资个人部分已扣个人部分
		UFDouble tableEightOrg = tableMap.get("TableEight").get("org");// 实际集团内其他公司已缴当月工资个人部分已扣公司部分
		UFDouble queryTableNine = nvl(queryTableNine(orgCode, period), 2);// 个人工资表扣缴数
		Map<String, String> TableTenMap = queryTableTen(orgCode, period);
		UFDouble TableTenStaff = nvl(TableTenMap.get("housing_fund_staff"), 2);// 个人实际缴纳数
		UFDouble TableTenOrg = nvl(TableTenMap.get("housing_fund_org"), 2);// 公司实际缴纳数
		// 社保账单实际交纳数 = 个人实际缴纳数+公司实际缴纳数
		UFDouble actualSum = TableTenStaff.add(TableTenOrg);
		// 社保分摊表金额 = 个人承担个人、公司部分+外部公司承担个人、公司部分+部门承担或全额公司承担个人、公司部分+
		// 个人部分已在集团内其他公司扣除个人、公司部分+月薪工资表中当月扣当月缴纳个人、公司部分+实际已缴当月工资个人部分未扣个人、公司部分
		UFDouble specialfillSum = tableOneStaff.add(tableOneOrg).add(tableTwoStaff).add(tableTwoOrg).add(tableThreeStaff).add(tableThreeOrg).add(tableFourStaff).add(tableFourOrg).add(tableFiveStaff)
				.add(tableFiveOrg).add(tableSixStaff).add(tableSixOrg);
		// 个人工资表扣缴数分摊表金额 = 月薪工资表中当月扣当月缴纳个人部分 +实际未缴当月工资个人部分已扣个人部分 + 实际集团内其他公司已缴当月工资个人部分已扣个人部分
		UFDouble staffPaymentSum = tableFiveStaff.add(tableSevenStaff).add(tableEightStaff);
		// 个人实际缴纳数分摊表金额 = 个人承担个人部分 + 外部公司承担个人部分 +部门承担或全额公司承担个人部分 + 个人部分已在集团内其他公司扣除个人部分
		// +月薪工资表中当月扣当月缴纳个人部分 + 实际已缴当月工资个人部分未扣个人部分
		UFDouble staffActualSum = tableOneStaff.add(tableTwoStaff).add(tableThreeStaff).add(tableFourStaff).add(tableFiveStaff).add(tableSixStaff);
		// 公司实际缴纳数分摊表金额 = 个人承担公司部分 + 外部公司承担公司部分 + 部门承担或全额公司承担公司部分 + 个人部分已在集团内其他公司扣除公司部分 +
		// 月薪工资表中当月扣当月缴纳公司部分 + 实际已缴当月工资个人部分未扣公司部分
		UFDouble orgActualSum = tableOneOrg.add(tableTwoOrg).add(tableThreeOrg).add(tableFourOrg).add(tableFiveOrg).add(tableSixOrg);
		dataList.set(0, new Object[] { "汇总信息" });
		dataList.set(1, new Object[] { "公积金汇缴单实际缴纳数", actualSum, "公积金分摊表金额", specialfillSum });
		dataList.set(2, new Object[] { "个人承担", "公司部分", tableOneOrg, "外部公司承担", "公司部分", tableTwoOrg, "部门承担或全额公司承担", "公司部分", tableThreeOrg });
		dataList.set(3, new Object[] { "个人承担", "个人部分", tableOneStaff, "外部公司承担", "个人部分", tableTwoStaff, "部门承担或全额公司承担", "个人部分", tableThreeStaff });
		dataList.set(4, new Object[] { "个人部分已在集团内其他公司扣除  ", "公司部分", tableFourOrg, "月薪工资表中当月扣当月缴纳", "公司部分", tableFiveOrg, "实际已缴当月工资个人部分未扣", "公司部分", tableSixOrg });
		dataList.set(5, new Object[] { "个人部分已在集团内其他公司扣除  ", "个人部分", tableFourStaff, "月薪工资表中当月扣当月缴纳", "个人部分", tableFiveStaff, "实际已缴当月工资个人部分未扣", "个人部分", tableSixStaff });
		dataList.set(6, new Object[] { "实际未缴当月工资个人部分已扣  ", "公司部分", tableSevenOrg, "实际集团内其他公司已缴当月工资个人部分已扣", "公司部分", tableEightOrg});
		dataList.set(7, new Object[] { "实际未缴当月工资个人部分已扣  ", "个人部分", tableSevenStaff, "实际集团内其他公司已缴当月工资个人部分已扣", "个人部分", tableEightStaff});
		dataList.set(8, new Object[] { "个人", "工资表扣缴数", queryTableNine, "分摊表金额", staffPaymentSum, "差异", queryTableNine.sub(staffPaymentSum) });
		dataList.set(9, new Object[] { "个人", "实际缴纳数", TableTenStaff, "分摊表金额", staffActualSum, "差异", TableTenStaff.sub(staffActualSum) });
		dataList.set(10, new Object[] { "公司", "实际缴纳数", TableTenOrg, "分摊表金额", orgActualSum, "差异", TableTenOrg.sub(orgActualSum) });
		Object[][] dataArray = new Object[dataList.size()][m_sTitle.length];
		for (int i = 0; i < dataList.size(); i++) {
			Object[] rowData = dataList.get(i);
			dataArray[i] = rowData;
		}
		DefaultTableModel model = new DefaultTableModel(dataArray, m_sTitle) {
			// 所有单元格不允许编辑
			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		tablepanel.getTable().setModel(model);
		tablepanel.getTable().setColumnWidth(new int[] { 300, 150, 150, 300, 150, 150, 200, 190, 160 });
		TableCellRenderer renderer = new DefaultTableCellRenderer() {
			@Override
			public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
				// 调用父类的getTableCellRendererComponent方法
				super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
				// 从十三行开始，第七列值变成白色,其他列值为黑色
				if (row >= 13 && column == 7) {
					// 如果单元格被选中，则设置值和背景颜色相同，未被选中时设置成白色
					if (isSelected) {
						setForeground(Color.decode("#F9E2D0"));
					} else {
						setForeground(Color.white);
					}
				} else {
					setForeground(Color.BLACK);
				}
				// 返回渲染的组件
				return this;
			}
		};
		tablepanel.getTable().getColumnModel().getColumn(7).setCellRenderer(renderer);
	}

	/**
	 * 根据员工号统计个人、公司部分金额
	 * 
	 * @param ListMap
	 */
	private void moneyDispose(String title, List<Map<String, String>> ListMap) {
		for (int i = 0; i < ListMap.size(); i++) {
			Map<String, UFDouble> mapMoney = new HashMap<String, UFDouble>();
			Map<String, String> map = ListMap.get(i);
			String clerkcode = map.get("clerkcode");
			String clerkname = map.get("clerkname");
			String orgName = map.get("orgname");
			String staffMoney = null;
			String orgMoney = null;
			// orgName可能存在为空的情况,拼接的时候会把null拼接到新的字符串，使用三目运算处理改问题
			String combinedField = title + (orgName == null ? "" : orgName) + clerkcode + clerkname;
			// 取中间表数据
			Map<String, String> middleTableMap = middleTableData.get(combinedField);
			// middleTableMap为空表示中间表为空，使用原始数据，不为空使用中间表数据
			if (middleTableMap != null) {
				staffMoney = MathTool.nvl(ValueUtils.getUFDouble(middleTableMap.get("staffsum"))).toString();
				orgMoney = MathTool.nvl(ValueUtils.getUFDouble(middleTableMap.get("orgsum"))).toString();
			} else {
				staffMoney = MathTool.nvl(ValueUtils.getUFDouble(map.get("staffsum"))).toString();
				orgMoney = MathTool.nvl(ValueUtils.getUFDouble(map.get("orgsum"))).toString();
			}
			int staffMoneyLength = staffMoney.substring(staffMoney.indexOf(".") + 1).length();// 个人部分小数位数
			int orgMoneyLength = orgMoney.substring(orgMoney.indexOf(".") + 1).length();// 公司部分小数位数
			// 个人部分或者公司部分小数位数大于2位需要进行金额处理
			if (staffMoneyLength > 2 || orgMoneyLength > 2) {
				UFDouble beforePsgStaffMoney = new UFDouble(staffMoney);
				UFDouble beforePsgOrgMoney = new UFDouble(orgMoney);
				// 个人部分或者公司部分存在0.0000情况,个人部分或者公司部分其中一个不等于0需要进行金额处理
				if (!MathTool.equals(beforePsgStaffMoney, null) || !MathTool.equals(beforePsgOrgMoney, null)) {
					// 如果当前clerkcode在map中有数据将两个金额相加
					if (beforePsgMoney.get(clerkcode) != null) {
						mapMoney = beforePsgMoney.get(clerkcode);
						beforePsgStaffMoney = beforePsgStaffMoney.add(mapMoney.get("beforePsgStaffMoney"));
						beforePsgOrgMoney = beforePsgOrgMoney.add(mapMoney.get("beforePsgOrgMoney"));
					}
					mapMoney.put("beforePsgStaffMoney", beforePsgStaffMoney);
					mapMoney.put("beforePsgOrgMoney", beforePsgOrgMoney);
					beforePsgMoney.put(clerkcode, mapMoney);
				}
			}
		}
	}

	/**
	 * 数据处理，表格渲染
	 * 
	 * @param dataList
	 * @param title
	 * @param ListMap
	 */
	private Map<String, UFDouble> addTableToList(String str, List<Object[]> dataList, String title, List<Map<String, String>> ListMap) {
		if ("表四：个人部分已在集团内其他公司扣除".equals(title)) {
			tableFourSelfMap = new HashMap<String, UFDouble>();
		}
		if ("表一：由个人承担".equals(title)) {
			tableOneOrgMap = new HashMap<String, UFDouble>();
		}
		if ("表六：实际已缴当月工资个人部分未扣".equals(title)) {
			tableSixSelfMap = new HashMap<String, UFDouble>();
		}
		if ("表七：实际未缴当月工资个人部分已扣".equals(title)) {
			tableSevenSelfMap = new HashMap<String, UFDouble>();
		}
		dataList.add(new Object[] { title });
		dataList.add(subheading);
		Map<String, UFDouble> MapMoney = new HashMap<String, UFDouble>();
		// 合计部分
		UFDouble staffTotal = new UFDouble(0.00, 2);
		UFDouble orgTotal = new UFDouble(0.00, 2);
		// 小计部分
		UFDouble staffSubtotal = new UFDouble(0.00, 2);
		UFDouble orgSubtotal = new UFDouble(0.00, 2);
		for (int i = 0; i < ListMap.size(); i++) {
			Map<String, String> map = ListMap.get(i);
			Map<String, UFDouble> mapMoney = new HashMap<String, UFDouble>();
			String clerkcode = map.get("clerkcode");
			String clerkname = map.get("clerkname");
			String orgName = map.get("orgname");
			String basicssum = MathTool.nvl(ValueUtils.getUFDouble(map.get("basicssum"))).toString();
			String staffsum = MathTool.nvl(ValueUtils.getUFDouble(map.get("staffsum"))).toString();
			String orgsum = MathTool.nvl(ValueUtils.getUFDouble(map.get("orgsum"))).toString();
			String mark = map.get("mark");
			// orgName可能存在为空的情况,拼接的时候会把null拼接到新的字符串，使用三目运算处理改问题
			String combinedField = title + (orgName == null ? "" : orgName) + clerkcode + clerkname;
			UFDouble basicsMoney = new UFDouble(0.00, 2);
			UFDouble staffMoney = new UFDouble(0.00, 2);
			UFDouble orgMoney = new UFDouble(0.00, 2);
			// 取中间表数据
			Map<String, String> middleTableMap = middleTableData.get(combinedField);
			// middleTableMap不为空使用中间表数据
			if (middleTableMap != null) {
				basicssum = MathTool.nvl(ValueUtils.getUFDouble(middleTableMap.get("basicssum"))).toString();
				staffsum = MathTool.nvl(ValueUtils.getUFDouble(middleTableMap.get("staffsum"))).toString();
				orgsum = MathTool.nvl(ValueUtils.getUFDouble(middleTableMap.get("orgsum"))).toString();
				mark = middleTableMap.get("mark");
			}
			basicsMoney = nvl(basicssum, 2);
			staffMoney = nvl(staffsum, 2);
			orgMoney = nvl(orgsum, 2);
			int staffsumLength = staffsum.substring(staffsum.indexOf(".") + 1).length();// 个人部分小数位数
			int orgsumLength = orgsum.substring(orgsum.indexOf(".") + 1).length();// 公司部分小数位数
			// 个人部分或者公司部分小数位数大于2位需要进行金额处理
			if (staffsumLength > 2 || orgsumLength > 2) {
				UFDouble afterPsgStaffMoney = staffMoney;
				UFDouble afterPsgOrgMoney = orgMoney;
				// 个人部分或者公司部分存在0.0000情况,个人部分或者公司部分其中一个不等于0需要进行金额处理
				if (!MathTool.equals(afterPsgStaffMoney, null) || !MathTool.equals(afterPsgOrgMoney, null)) {
					// 如果当前员工编号在map中有数据将两个金额相加
					if (afterPsgMoney.get(clerkcode) != null) {
						mapMoney = afterPsgMoney.get(clerkcode);
						afterPsgStaffMoney = afterPsgStaffMoney.add(mapMoney.get("afterPsgStaffMoney"));
						afterPsgOrgMoney = afterPsgOrgMoney.add(mapMoney.get("afterPsgOrgMoney"));
					}
					// 取处理前个人部分金额
					UFDouble beforePsgStaffMoney = beforePsgMoney.get(clerkcode).get("beforePsgStaffMoney");
					// 取处理前公司部分金额
					UFDouble beforePsgOrgMoney = beforePsgMoney.get(clerkcode).get("beforePsgOrgMoney");
					// 如果处理后个人部分金额大于取处理前个人部分金额，处理后个人部分行金额减去两个值的差
					if (MathTool.greaterThan(afterPsgStaffMoney, beforePsgStaffMoney)) {
						staffMoney = staffMoney.sub(afterPsgStaffMoney.sub(beforePsgStaffMoney).setScale(2, UFDouble.ROUND_HALF_UP));
					}
					// 如果处理后公司部分金额大于取处理前公司部分金额，处理后公司部分行金额减去两个值的差
					if (MathTool.greaterThan(afterPsgOrgMoney, beforePsgOrgMoney)) {
						orgMoney = orgMoney.sub(afterPsgOrgMoney.sub(beforePsgOrgMoney).setScale(2, UFDouble.ROUND_HALF_UP));
					}
					mapMoney.put("afterPsgStaffMoney", afterPsgStaffMoney);
					mapMoney.put("afterPsgOrgMoney", afterPsgOrgMoney);
					afterPsgMoney.put(clerkcode, mapMoney);
				}
			}

			// 统计合计
			staffTotal = staffTotal.add(staffMoney);
			orgTotal = orgTotal.add(orgMoney);
			if (orgName != null) {
				// 组织不为空输出组织小标题和小计
				if (i == 0) {
					// 输出组织小标题
					dataList.add(new Object[] { orgName });
				} else if (!orgName.equals(ListMap.get(i - 1).get("orgname"))) {
					// 如果当前行组织不等于上一行组织输组织小标题
					// 输出组织小标题
					dataList.add(new Object[] { orgName });
				}
				// 输出行数据
				dataList.add(new Object[] { i + 1, clerkcode, clerkname, basicsMoney, staffMoney, orgMoney, mark, str + orgName });
				if ("表一：由个人承担".equals(title)) {
					tableOneOrgMap.put(clerkcode + "," + clerkname, orgMoney);
				}
				if ("表六：实际已缴当月工资个人部分未扣".equals(title)) {
					tableSixSelfMap.put(clerkcode + "," + clerkname, staffMoney);
				}
				if ("表七：实际未缴当月工资个人部分已扣".equals(title)) {
					tableSevenSelfMap.put(clerkcode + "," + clerkname, staffMoney);
				}
				// 统计小计
				staffSubtotal = staffSubtotal.add(staffMoney);
				orgSubtotal = orgSubtotal.add(orgMoney);
				if (i + 1 == ListMap.size()) {
					// 第一行和最后一行输出小计
					// 输出小计
					dataList.add(new Object[] { "小计", null, null, null, staffSubtotal, orgSubtotal });
					if ("表四：个人部分已在集团内其他公司扣除".equals(title)) {
						tableFourSelfMap.put(orgName, staffSubtotal);
					}
					staffSubtotal = new UFDouble(0.00, 2);
					orgSubtotal = new UFDouble(0.00, 2);
				} else if (!orgName.equals(ListMap.get(i + 1).get("orgname"))) {
					// 如果当前行组织不等于下一行组织输出小计
					// 输出小计
					dataList.add(new Object[] { "小计", null, null, null, staffSubtotal, orgSubtotal });
					if ("表四：个人部分已在集团内其他公司扣除".equals(title)) {
						tableFourSelfMap.put(orgName, staffSubtotal);
					}
					staffSubtotal = new UFDouble(0.00, 2);
					orgSubtotal = new UFDouble(0.00, 2);
				}
			} else {
				// 输出行数据
				dataList.add(new Object[] { i + 1, clerkcode, clerkname, basicsMoney, staffMoney, orgMoney, mark, str });
				if ("表一：由个人承担".equals(title)) {
					tableOneOrgMap.put(clerkcode + "," + clerkname, orgMoney);
				}
				if ("表六：实际已缴当月工资个人部分未扣".equals(title)) {
					tableSixSelfMap.put(clerkcode + "," + clerkname, staffMoney);
				}
				if ("表七：实际未缴当月工资个人部分已扣".equals(title)) {
					tableSevenSelfMap.put(clerkcode + "," + clerkname, staffMoney);
				}
			}
		}
		// 输出合计
		dataList.add(new Object[] { "合计", null, null, null, staffTotal, orgTotal });
		MapMoney.put("staff", staffTotal);
		MapMoney.put("org", orgTotal);
		return MapMoney;
	}

	/**
	 * 查询个人承担
	 * 
	 * @param period
	 * @param orgcode
	 * @return
	 * @throws Exception
	 */
	private List<Map<String, String>> queryTableOne(String orgCode, String period) throws Exception {
		String title = "表一：由个人承担";
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT orgname,clerkcode,clerkname,sum(basicssum) as basicssum,sum(staffsum) as staffsum,sum(orgsum) as orgsum,max(mark) as mark");
		sql.append(" FROM");
		sql.append(" (SELECT ");
		sql.append(" NULL AS orgname,");
		sql.append(" t.CLERKCODE AS clerkcode,");
		sql.append(" T1.CLERKNAME AS clerkname,");
		sql.append(" CAST( t1.housing_fund_base AS VARCHAR2 ( 50 ) ) AS basicssum,");
		sql.append(" CAST( NULL AS VARCHAR2 ( 50 ) ) AS staffsum,");
		sql.append(" CAST( SUM( NVL( t.VALUE, 0 ) ) AS VARCHAR2 ( 50 ) ) AS orgsum,");
		sql.append(" t1.mark AS mark");
		sql.append(" from NC6337.v_data_xz_gjjshare t");
		sql.append(" LEFT JOIN NC6337.V_SUM_TB_HR_SOCIAL_SECURITY t1 ON t1.CLERKCODE = t.CLERKCODE AND t1.PAY_MONTH || '-01' = t.ym");
		sql.append(" WHERE");
		sql.append(" t.key = '公积金公司税后扣款' and t.VALUE <> 0 and t.ym='"+period+"'||'-01' and t1.ORGCODE_HOUSE='"+orgCode+"' and t1.ENDOWMENT_BASE is not null");
		sql.append(" GROUP BY t.CLERKCODE,T1.CLERKNAME,t1.housing_fund_base,t1.mark");
		sql.append(jointSql(title, orgCode, period));
		sql.append(" )GROUP BY orgname,clerkcode,clerkname ORDER BY orgname,clerkcode");
		return (List<Map<String, String>>) iuap.executeQuery(sql.toString(), new MapListProcessor());
	}
	

	

	/**
	 * 查询外部公司承担
	 * 
	 * @param period
	 * @param orgcode
	 * @return
	 * @throws Exception
	 */
	private List<Map<String, String>> queryTableTwo(String orgCode, String period) throws Exception {
		String title = "表二：由外部公司承担";
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT orgname,clerkcode,clerkname,sum(basicssum) as basicssum,sum(staffsum) as staffsum,sum(orgsum) as orgsum,max(mark) as mark");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" NULL AS orgname,");
		sql.append(" clerkcode as clerkcode,");
		sql.append(" clerkname as clerkname,");
		sql.append(" CAST(housing_fund_base AS VARCHAR2 ( 50 ) ) AS basicssum,");
		sql.append(" CAST(housing_fund_staff AS VARCHAR2 ( 50 ) ) AS staffsum,");
		sql.append(" CAST(housing_fund_org AS VARCHAR2 ( 50 ) ) AS orgsum,");
		sql.append(" mark AS mark");
		sql.append(" FROM nc6337.V_SUM_TB_HR_SOCIAL_SECURITY t");
		sql.append(" WHERE");
		sql.append(" t.out_org IS NOT NULL AND t.PAY_MONTH = '"+period+"' AND t.ORGCODE = '"+orgCode+"'");
		sql.append(jointSql(title, orgCode, period));
		sql.append(" )GROUP BY orgname,clerkcode,clerkname ORDER BY orgname,clerkcode");
		return (List<Map<String, String>>) iuap.executeQuery(sql.toString(), new MapListProcessor());
	}

	/**
	 * 由部门承担或全额公司承担
	 * 
	 * @param period
	 * @param orgcode
	 * @return
	 * @throws Exception
	 */
	private List<Map<String, String>> queryTableThree(String orgCode, String period) throws Exception {
		String title = "表三：由部门承担或全额公司承担";
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT orgname,clerkcode,clerkname,sum(basicssum) as basicssum,sum(staffsum) as staffsum,sum(orgsum) as orgsum,max(mark) as mark");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" NULL AS orgname,");
		sql.append(" clerkcode AS clerkcode,");
		sql.append(" clerkname AS clerkname,");
		sql.append(" CAST(housing_fund_base AS VARCHAR2 ( 50 ) ) AS basicssum,");
		sql.append(" CAST(HOUSING_FUND_STAFF AS VARCHAR2 ( 50 ) ) AS staffsum,");
		sql.append(" CAST(HOUSING_FUND_ORG AS VARCHAR2 ( 50 ) ) AS orgsum,");
		sql.append(" NULL AS mark");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" T.housing_fund_base,T.CLERKCODE,T.CLERKNAME,T.HOUSING_FUND_ORG,T.HOUSING_FUND_STAFF,T.ORGCODE_HOUSE,T.PAY_MONTH,T.MARK");
		sql.append(" FROM");
		sql.append(" NC6337.V_SUM_TB_HR_SOCIAL_SECURITY T");
		sql.append(" WHERE");
		sql.append(" T.PK_POST IN ( SELECT T3.PK_POST FROM NC6337.om_post t3 WHERE T3.postname = '残保金人员' ) AND T.HOUSING_FUND_ORG <> 0");
		sql.append(" UNION ALL");
		sql.append(" SELECT");
		sql.append(" t1.housing_fund_base,t1.CLERKCODE,t1.CLERKNAME,t1.HOUSING_FUND_ORG,t1.HOUSING_FUND_STAFF,T1.ORGCODE_HOUSE,t1.PAY_MONTH,T1.MARK");
		sql.append(" FROM");
		sql.append(" NC6337.V_SUM_TB_HR_SOCIAL_SECURITY_D t1 ");
		sql.append(" WHERE");
		sql.append(" t1.MARK = '表三') t2");
		sql.append(" WHERE");
		sql.append(" t2.PAY_MONTH = '"+period+"' AND t2.ORGCODE_HOUSE = '"+orgCode+"'");
		sql.append(jointSql(title, orgCode, period));
		sql.append(" )GROUP BY orgname,clerkcode,clerkname ORDER BY orgname,clerkcode");
		return (List<Map<String, String>>) iuap.executeQuery(sql.toString(), new MapListProcessor());
	}

	/**
	 * 查询个人部分已在集团内其他公司扣除
	 * 
	 * @param period
	 * @param orgcode
	 * @return
	 * @throws Exception
	 */
	private List<Map<String, String>> queryTableFour(String orgCode, String period) throws Exception {
		String title = "表四：个人部分已在集团内其他公司扣除";
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT orgname,clerkcode,clerkname,sum(basicssum) as basicssum,sum(staffsum) as staffsum,sum(orgsum) as orgsum,max(mark) as mark");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" salocation AS orgname,");
		sql.append(" clerkcode,");
		sql.append(" clerkname,");
		sql.append(" CAST(housing_fund_base AS VARCHAR2 ( 50 ) ) AS basicssum,");
		sql.append(" CAST(HOUSING_FUND_STAFF AS VARCHAR2 ( 50 ) ) AS staffsum,");
		sql.append(" CAST(HOUSING_FUND_ORG AS VARCHAR2 ( 50 ) ) AS orgsum,");
		sql.append(" mark");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" t.CLERKCODE,T1.CLERKNAME,t.ym,sum( nvl( t.VALUE, 0 ) ) AS sum_per_cost,t.c_23 AS salocation,t1.HOUSING_FUND_ORG,t1.HOUSING_FUND_STAFF,t1.housing_fund_base,t1.mark");
		sql.append(" FROM");
		sql.append(" NC6337.v_data_xz_gjjshare t");
		sql.append(" LEFT JOIN NC6337.V_SUM_TB_HR_SOCIAL_SECURITY t1 ON t1.CLERKCODE = t.CLERKCODE");
		sql.append(" AND t1.PAY_MONTH || '-01' = t.ym");
		sql.append(" WHERE");
		sql.append(" t.key = '社保个人合计' AND t.VALUE <> 0 AND t.ym = '"+period+"' || '-01' AND t1.ORGCODE_HOUSE = '"+orgCode+"' AND t1.HOUSING_FUND_PAY_ORG <> t.c_23");
		sql.append(" GROUP BY ROWNUM,t.CLERKCODE,T1.CLERKNAME,t.ym,t1.housing_fund_base,t1.HOUSING_FUND_ORG,t1.HOUSING_FUND_STAFF,t.c_23,t1.mark");
		sql.append(" ORDER BY t.c_23)");
		sql.append(jointSql(title, orgCode, period));
		sql.append("  )GROUP BY orgname,clerkcode,clerkname ORDER BY orgname,clerkcode");
		return (List<Map<String, String>>) iuap.executeQuery(sql.toString(), new MapListProcessor());
	}

	/**
	 * 查询月薪工资表中当月扣当月缴纳
	 * 
	 * @param period
	 * @param orgcode
	 * @return
	 * @throws Exception
	 */
	private List<Map<String, String>> queryTableFive(String orgCode, String period) throws Exception {
		String title = "表五：月薪工资表中当月扣当月缴纳";
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT orgname,clerkcode,clerkname,sum(basicssum) as basicssum,sum(staffsum) as staffsum,sum(orgsum) as orgsum,max(mark) as mark");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" costorgname AS orgname,");
		sql.append(" clerkcode,");
		sql.append(" clerkname,");
		sql.append(" CAST(housing_fund_base AS VARCHAR2 ( 50 ) ) AS basicssum,");
		sql.append(" CAST(HOUSING_FUND_STAFF AS VARCHAR2 ( 50 ) ) AS staffsum,");
		sql.append(" CAST(HOUSING_FUND_ORG AS VARCHAR2 ( 50 ) ) AS orgsum,");
		sql.append(" mark");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" t.CLERKCODE,T1.CLERKNAME,t.ym,sum( nvl( t.VALUE, 0 ) ) AS sum_per_cost,T13.Name AS costorgname,t.c_23 AS salocation,t1.HOUSING_FUND_ORG - nvl( t15.sum_per_cost, 0 ) - nvl( t16.HOUSING_FUND_ORG, 0 ) AS HOUSING_FUND_ORG,t1.HOUSING_FUND_STAFF,t1.housing_fund_base,t1.mark ");
		sql.append(" FROM");
		sql.append(" NC6337.v_data_xz_gjjshare t");
		sql.append(" LEFT JOIN NC6337.V_SUM_TB_HR_SOCIAL_SECURITY t1 ON t1.CLERKCODE = t.CLERKCODE");
		sql.append(" AND t1.PAY_MONTH || '-01' = t.ym");
		sql.append(" LEFT JOIN (");
		sql.append(" SELECT");
		sql.append(" t12.CLERK_CODE,");
		sql.append(" t12.NC_PK_POST");
		sql.append(" FROM");
		sql.append(" nc6337.monthly_position_gjj t12");
		sql.append(" WHERE");
		sql.append(" t12.month = to_char( last_day( to_date( '"+period+"', 'yyyy-mm' ) ), 'yyyy-mm-dd' )");
		sql.append(" ) T12 ON t12.CLERK_CODE = t.CLERKCODE");
		sql.append(" LEFT JOIN nc6337.om_post t14 ON t14.pk_post = t12.NC_PK_POST");
		sql.append(" LEFT JOIN nc6337.org_corp T13 ON T13.Pk_Corp = t14.pk_org");
		sql.append(" LEFT JOIN nc6337.person_afford_sbgjj_g t15 ON t15.CLERKCODE = t.CLERKCODE AND t.YM = t15.ym");
		sql.append(" LEFT JOIN nc6337.DEPT_AFFORD_SBGJJ t16 ON t16.CLERKCODE = t.CLERKCODE AND t.YM = t16.PAY_MONTH");
		sql.append(" WHERE");
		sql.append(" t.key IN ( '公积金个人合计', '费用调整公积金', '公积金个人扣款', '费用调整公积金t' )AND t.VALUE <> 0 AND t.ym = '"+period+"' || '-01' AND t1.ORGCODE_HOUSE = '"+orgCode+"' AND t1.Housing_Fund_Pay_Org = t.c_23");
		sql.append(" AND t.CLERKCODE NOT IN ( SELECT t11.WORKERCODE FROM nc6337.v_hr_allocationratio_gjjshareF t11 WHERE t11.WA_PERIOD = '"+period+"' || '-01' )");
		sql.append(" GROUP BY t.CLERKCODE,t.CLERKCODE,T1.CLERKNAME,t.ym,t1.housing_fund_base,t1.HOUSING_FUND_ORG - nvl( t15.sum_per_cost, 0 ) - nvl( t16.HOUSING_FUND_ORG, 0 ),t1.HOUSING_FUND_STAFF,T13.Name,t.c_23,t1.mark");
		sql.append(" UNION ALL");
		sql.append(" SELECT");
		sql.append(" t.WORKERCODE AS CLERKCODE,t1.CLERKNAME,t.WA_PERIOD AS ym,0 AS sum_per_cost,T6.NAME AS costorgname,'上海天华' AS salocation,round( nvl( t1.HOUSING_FUND_ORG, 0 ) * nvl( t.perc, 0 ), 2 ) AS HOUSING_FUND_ORG,");
		sql.append(" round( nvl( t1.HOUSING_FUND_STAFF, 0 ) * nvl( t.perc, 0 ), 2 ) AS HOUSING_FUND_STAFF,t1.housing_fund_base,t1.mark");
		sql.append(" FROM");
		sql.append(" nc6337.v_hr_allocationratio_gjjshareF t");
		sql.append(" LEFT JOIN nc6337.V_SUM_TB_HR_SOCIAL_SECURITY t1 ON t1.CLERKCODE = t.WORKERCODE AND t1.PAY_MONTH || '-01' = t.WA_PERIOD");
		sql.append(" LEFT JOIN ( SELECT DISTINCT T5.CODE, T5.NAME, t5.pk_corp FROM nc6337.ORG_CORP T5 ) T6 ON T6.pk_corp = T.COST_ORG");
		sql.append(" WHERE");
		sql.append(" t.WA_PERIOD = '"+period+"' || '-01'AND t1.CLERKNAME IS NOT NULL AND t1.ORGCODE_HOUSE = '"+orgCode+"' UNION ALL");
		sql.append(" SELECT");
		sql.append(" t1.CLERKCODE,t1.CLERKNAME,t1.PAY_MONTH || '-01' AS ym,0 AS sum_per_cost,T1.Housing_Fund_Pay_Org AS costorgname,'上海天华' AS salocation,t1.HOUSING_FUND_ORG,0 AS HOUSING_FUND_STAFF,t1.housing_fund_base,t1.mark");
		sql.append(" FROM");
		sql.append(" NC6337.V_SUM_TB_HR_SOCIAL_SECURITY_D t1");
		sql.append(" WHERE");
		sql.append(" t1.MARK IN ( '资质人员', '上海公司承担' )AND t1.PAY_MONTH = '"+period+"'AND t1.ORGCODE_HOUSE = '"+orgCode+"')");
		sql.append(jointSql(title, orgCode, period));
		sql.append("  )GROUP BY orgname,clerkcode,clerkname ORDER BY orgname,clerkcode");
		return (List<Map<String, String>>) iuap.executeQuery(sql.toString(), new MapListProcessor());
	}

	/**
	 * 查询实际已缴纳当月工资个人部分未扣
	 * 
	 * @param period
	 * @param orgCode
	 * @return
	 * @throws Exception
	 */
	private List<Map<String, String>> queryTableSix(String orgCode, String period) throws Exception {
		String title = "表六：实际已缴当月工资个人部分未扣";
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT");
		sql.append(" orgname,clerkcode,clerkname,sum(basicssum) as basicssum,sum(staffsum) as staffsum,sum(orgsum) as orgsum,max(mark) as mark");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" T13.Name AS orgname,");
		sql.append(" clerkcode,");
		sql.append(" clerkname,");
		sql.append(" CAST(housing_fund_base AS VARCHAR2 ( 50 ) ) AS basicssum,");
		sql.append(" CAST(housing_fund_staff AS VARCHAR2 ( 50 ) ) AS staffsum,");
		sql.append(" CAST(housing_fund_org AS VARCHAR2 ( 50 ) ) AS orgsum,");
		sql.append(" mark");
		sql.append(" FROM");
		sql.append(" nc6337.V_SUM_TB_HR_SOCIAL_SECURITY t1");
		sql.append(" LEFT JOIN (");
		sql.append(" SELECT");
		sql.append(" t12.CLERK_CODE,");
		sql.append(" t12.NC_PK_POST");
		sql.append(" FROM");
		sql.append(" nc6337.monthly_position_gjj t12");
		sql.append(" WHERE");
		sql.append(" t12.month = to_char( last_day( to_date( '"+period+"', 'yyyy-mm' ) ), 'yyyy-mm-dd' )");
		sql.append(" ) T12 ON t12.CLERK_CODE = t1.CLERKCODE");
		sql.append(" LEFT JOIN nc6337.om_post t14 ON t14.pk_post = t12.NC_PK_POST");
		sql.append(" LEFT JOIN nc6337.org_corp T13 ON T13.Pk_Corp = t14.pk_org");
		sql.append(" WHERE");
		sql.append(" t1.CLERKCODE NOT IN (");
		sql.append(" SELECT");
		sql.append(" t2.CLERKCODE");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" t.CLERKCODE,sum( nvl( t.VALUE, 0 ) ) AS sumVALUE");
		sql.append(" FROM");
		sql.append(" NC6337.v_data_xz_gjjshare t");
		sql.append(" WHERE");
		sql.append(" t.key IN ( '公积金个人合计', '公积金个人扣款' )AND t.ym = '"+period+"' || '-01'");
		sql.append(" GROUP BY t.CLERKCODE) t2");
		sql.append(" WHERE");
		sql.append(" t2.sumVALUE > 0)");
		sql.append(" AND T12.NC_PK_POST NOT IN ( SELECT T3.PK_POST FROM NC6337.om_post t3 WHERE T3.postname IN ( '残保金人员', '资质人员' ) ) AND t1.out_org IS NULL");
		sql.append(" AND t1.housing_fund_base <> 0 AND t1.PAY_MONTH = '"+period+"'AND t1.ORGCODE_HOUSE = '"+orgCode+"'");
		sql.append(jointSql(title, orgCode, period));
		sql.append(" )GROUP BY orgname,clerkcode,clerkname ORDER BY orgname,clerkcode");
		return (List<Map<String, String>>) iuap.executeQuery(sql.toString(), new MapListProcessor());
	}

	/**
	 * 查询实际未缴当月工资个人部分已扣
	 * 
	 * @param period
	 * @param orgCode
	 * @return
	 * @throws Exception
	 */
	private List<Map<String, String>> queryTableSeven(String orgCode, String period) throws Exception {
		String title = "表七：实际未缴当月工资个人部分已扣";
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT");
		sql.append(" orgname,clerkcode,clerkname,sum(basicssum) as basicssum,sum(staffsum) as staffsum,sum(orgsum) as orgsum,max(mark) as mark");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" orgname,");
		sql.append(" clerkcode,");
		sql.append(" clerkname,");
		sql.append(" CAST(housing_fund_base AS VARCHAR2 ( 50 ) ) AS basicssum,");
		sql.append(" CAST(housing_fund_staff AS VARCHAR2 ( 50 ) ) AS staffsum,");
		sql.append(" CAST(so_org_sum AS VARCHAR2 ( 50 ) ) AS orgsum,");
		sql.append(" mark");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" t1.CLERKCODE,t1.CLERKNAME,t1.housing_fund_base,( t16.sumvalue - t1.HOUSING_FUND_STAFF ) AS HOUSING_FUND_STAFF,0 AS so_org_sum,T13.Name AS orgname,t1.mark ");
		sql.append(" FROM");
		sql.append(" nc6337.V_SUM_TB_HR_SOCIAL_SECURITY t1");
		sql.append(" LEFT JOIN (");
		sql.append(" SELECT");
		sql.append(" t12.CLERK_CODE,t12.NC_PK_POST");
		sql.append(" FROM");
		sql.append(" nc6337.monthly_position_gjj t12 ");
		sql.append(" WHERE");
		sql.append(" t12.month = to_char( last_day( to_date( '"+period+"', 'yyyy-mm' ) ), 'yyyy-mm-dd' )");
		sql.append(" ) T12 ON t12.CLERK_CODE = t1.CLERKCODE");
		sql.append(" LEFT JOIN nc6337.om_post t14 ON t14.pk_post = t12.NC_PK_POST");
		sql.append(" LEFT JOIN nc6337.org_corp T13 ON T13.Pk_Corp = t14.pk_org");
		sql.append(" LEFT JOIN nc6337.person_deduction_sbgjj_g t16 ON t16.CLERKCODE = t1.CLERKCODE ");
		sql.append(" AND t1.pay_month || '-01' = t16.ym");
		sql.append(" WHERE");
		sql.append(" t1.CLERKCODE IN (");
		sql.append(" SELECT");
		sql.append(" t2.CLERKCODE");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" t.CLERKCODE,sum( nvl( t.VALUE, 0 ) ) AS sumVALUE");
		sql.append(" FROM");
		sql.append(" NC6337.v_data_xz_gjjshare t ");
		sql.append(" WHERE");
		sql.append(" t.key IN ( '公积金个人合计', '公积金个人扣款' ) AND t.ym = '"+period+"' || '-01'");
		sql.append(" GROUP BY t.CLERKCODE) t2");
		sql.append(" WHERE");
		sql.append(" t2.sumVALUE > 0) ");
		sql.append(" AND T12.NC_PK_POST NOT IN ( SELECT T3.PK_POST FROM NC6337.om_post t3 WHERE T3.postname IN ( '残保金人员', '资质人员' ) )");
		sql.append(" AND t1.out_org IS NULL AND t1.housing_fund_base <> 0 AND ( t16.sumvalue - t1.HOUSING_FUND_STAFF ) <> 0");
		sql.append(" AND t1.PAY_MONTH = '"+period+"' AND t1.ORGCODE_HOUSE = '"+orgCode+"'");
		sql.append(" UNION ALL");
		sql.append(" SELECT");
		sql.append(" t1.CLERKCODE,t1.CLERKNAME,t1.housing_fund_base,t1.HOUSING_FUND_STAFF,t1.HOUSING_FUND_ORG,T13.Name AS orgname,t1.mark");
		sql.append(" FROM");
		sql.append(" nc6337.V_SUM_TB_HR_SOCIAL_SECURITY_D t1");
		sql.append(" LEFT JOIN (");
		sql.append(" SELECT");
		sql.append(" t12.CLERK_CODE,t12.NC_PK_POST");
		sql.append(" FROM");
		sql.append(" nc6337.monthly_position_gjj t12");
		sql.append(" WHERE");
		sql.append(" t12.month = to_char( last_day( to_date( '"+period+"', 'yyyy-mm' ) ), 'yyyy-mm-dd' )");
		sql.append(" ) T12 ON t12.CLERK_CODE = t1.CLERKCODE");
		sql.append(" LEFT JOIN nc6337.om_post t14 ON t14.pk_post = t12.NC_PK_POST");
		sql.append(" LEFT JOIN nc6337.org_corp T13 ON T13.Pk_Corp = t14.pk_org");
		sql.append(" WHERE");
		sql.append(" t1.mark LIKE '%表七%' AND t1.PAY_MONTH = '"+period+"'AND t1.ORGCODE_HOUSE = '"+orgCode+"')");
		sql.append(jointSql(title, orgCode, period));
		sql.append(" )GROUP BY orgname,clerkcode,clerkname ORDER BY orgname,clerkcode");
		return (List<Map<String, String>>) iuap.executeQuery(sql.toString(), new MapListProcessor());
	}

	/**
	 * 查询实际集团内其他公司已缴当月工资个人部分已扣
	 * 
	 * @param period
	 * @param orgCode
	 * @return
	 * @throws Exception
	 */
	private List<Map<String, String>> queryTableEight(String orgCode, String period) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT");
		sql.append(" contributoryorg AS orgname,clerkcode,clerkname,basicssum,staffsum,orgsum,mark");
		sql.append(" FROM");
		sql.append(" accumulation_fund");
		sql.append(" WHERE");
		sql.append(" tablename = '公积金分摊表' AND combined_field LIKE '表八：实际集团内其他公司已缴当月工资个人部分已扣%'");
		sql.append("  AND orgcode = '" + orgCode + "' AND period = '" + period + "'");
		sql.append(" ORDER BY CONTRIBUTORYORG,clerkcode");
		return (List<Map<String, String>>) iuap.executeQuery(sql.toString(), new MapListProcessor());
	}

	/**
	 * 查询工资表扣缴数
	 * 
	 * @param period
	 * @param orgCode
	 * @return
	 * @throws Exception
	 */
	private Object queryTableNine(String orgCode, String period) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT");
		sql.append(" sum( nvl( t.VALUE, 0 ) ) AS sum_per_cost");
		sql.append(" FROM");
		sql.append(" NC6337.v_data_xz_gjjshare t");
		sql.append(" WHERE");
		sql.append(" t.key IN ( '公积金个人合计', '费用调整公积金', '公积金个人扣款', '费用调整公积金t' )");
		sql.append(" AND t.ym = '"+period+"' || '-01'AND t.c_23 = ( SELECT t1.name FROM nc6337.org_corp t1 WHERE t1.code = '"+orgCode+"' )");
		return (Object) iuap.executeQuery(sql.toString(), new ColumnProcessor());
	}

	/**
	 * 查询实际缴纳数
	 * 
	 * @param period
	 * @param orgCode
	 * @return
	 * @throws Exception
	 */
	private Map<String, String> queryTableTen(String orgCode, String period) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT * FROM NC6337.V_SUM_TB_HR_SOCIAL_SECURITY_D T");
		sql.append(" WHERE T.CLERKNAME='总数'");
		sql.append(" AND T.PAY_MONTH='"+period+"'");
		sql.append(" AND T.ORGCODE='"+orgCode+"'");
		Map<String, String> map = (Map<String, String>) iuap.executeQuery(sql.toString(), new MapProcessor());
		if (map == null) {
			map = new HashMap<String, String>();
			map.put("housing_fund_staff", null);
			map.put("housing_fund_org", null);
		}
		return map;
	}
	
	/**
	 * 拼接中间表sql
	 * @param title
	 * @param orgCode
	 * @param period
	 * @return
	 */
	public StringBuffer jointSql(String title, String orgCode, String period) {
		StringBuffer sql = new StringBuffer();
		sql.append(" UNION ALL");
		sql.append(" SELECT");
		sql.append(" contributoryorg  AS orgname,");
		sql.append(" clerkcode,");
		sql.append(" clerkname,");
		sql.append(" basicssum,");
		sql.append(" staffsum,");
		sql.append(" orgsum,");
		sql.append(" mark");
		sql.append(" FROM accumulation_fund");
		sql.append(" WHERE");
		sql.append(" tablename = '公积金分摊表' AND combined_field LIKE '"+title+"%' AND orgcode = '"+orgCode+"' AND period = '"+period+"' ");
		return sql;
	}

	/**
	 * 查询中间表数据并处理
	 * 
	 * @return
	 * @throws Exception
	 */
	private void queryMiddleTable() throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT");
		sql.append(" combined_field,basicssum,staffsum,orgsum,mark from accumulation_fund");
		sql.append(" WHERE ");
		sql.append(" tablename = '公积金分摊表' AND combined_field NOT LIKE '表八：实际集团内其他公司已缴当月工资个人部分已扣%'");
		sql.append(" AND orgcode = '" + orgCode + "' AND period = '" + period + "'");
		List<Map<String, String>> listMap = (List<Map<String, String>>) iuap.executeQuery(sql.toString(), new MapListProcessor());
		for (int i = 0; i < listMap.size(); i++) {
			Map<String, String> map = listMap.get(i);
			middleTableData.put(map.get("combined_field"), map);
		}
	}

	/**
	 * 将Object转成UFDouble，设置保留几位小数
	 * 
	 * @param obj
	 * @param power
	 * @return
	 */
	public UFDouble nvl(Object obj, int power) {
		return MathTool.nvl(ValueUtils.getUFDouble(obj)).setScale(2, UFDouble.ROUND_HALF_UP);
	}

	/**
	 * 导出
	 */
	private void onoutput() {
		OutputDialogUtil outdig = new OutputDialogUtil(this, getTablePanel(), "公积金分摊表");
		if (outdig.showModal() == 2) {
			return;
		}
	}

	/**
	 * 获取修改数据打开修改界面 修改数据
	 * 
	 * @param table
	 */
	private void update(UITablePane table) {
		try {
			List<Object[]> selectedData = new ArrayList<Object[]>();
			int rows[] = table.getTable().getSelectedRows();
			if (rows.length == 0) {
				MessageDialog.showHintDlg(this, "提示", "请选择需要修改的数据！");
				return;
			} else {
				for (int i = 0; i < rows.length; i++) {
					Object obj = table.getTable().getValueAt(rows[i], 7);
					if (obj == null) {
						MessageDialog.showHintDlg(this, "提示", "请选择正确的行修改！");
						return;
					}
					// 小标题加上组织和表组合为8位
					Object[] rowData = new Object[8];
					for (int j = 0; j < 8; j++) {
						rowData[j] = table.getTable().getValueAt(rows[i], j);
					}
					selectedData.add(rowData);
				}
			}
			// 0表示有实际修改，而不是点击弹框后关闭了
			if (new AccumulationFundAllUpdateDialog(selectedData, orgCode, period).showModal() == 0) {
				// 调用报表查询刷新数据
				tableProcessing();
				MessageDialog.showHintDlg(this, "提示", "修改成功！");
			}
		} catch (Exception e) {
			MessageDialog.showHintDlg(this, "提示", e.getMessage());
		}
	}

	/**
	 * 打开新增页面
	 */
	private void insert() {
		try {
			String orgName = getOrgPanel().getRefModel().getRefNameValue();
			// 0表示有实际新增，而不是点击弹框后关闭了
			if (new AccumulationFundAllInsertDiaLog(orgCode, orgName, period).showModal() == 0) {
				MessageDialog.showHintDlg(this, "提示", "新增成功！");
			}
		} catch (Exception e) {
			MessageDialog.showHintDlg(this, "提示", e.getMessage());
		}
	}

	/**
	 * 
	 * 组装凭证借贷金额
	 * 
	 * @param tablepane
	 * 
	 */
	private Map<String, UFDouble> getVoucherAmount(UITablePane tablepane) {
		Map<String, UFDouble> map = new LinkedHashMap<String, UFDouble>();
		// 表一 个人承担-公司部分合计
		Object objgs = tablepane.getTable().getValueAt(2, 2);
		// 表一 个人承担-个人部分合计
		Object objgr = tablepane.getTable().getValueAt(3, 2);
		// 表二 外部公司承担-公司部分合计
		Object objwbgs = tablepane.getTable().getValueAt(2, 5);
		// 表二 外部公司承担-个人部分合计
		Object objwbgr = tablepane.getTable().getValueAt(3, 5);
		// 表三 部门承担或全额公司承担-公司部分合计
		Object objbmgs = tablepane.getTable().getValueAt(2, 8);
		// 表三 部门承担或全额公司承担-个人部分合计
		Object objbmgr = tablepane.getTable().getValueAt(3, 8);
		// 表四 个人部分已在集团内其他公司扣除-公司部分合计
		Object objbsgs = tablepane.getTable().getValueAt(4, 2);
		// 表四 个人部分已在集团内其他公司扣除-个人部分合计
		Object objbsgr = tablepane.getTable().getValueAt(5, 2);
		// 表五 月薪工资表中当月扣当月缴纳-公司部分合计
		Object objbwgs = tablepane.getTable().getValueAt(4, 5);
		// 表五 月薪工资表中当月扣当月缴纳-个人部分合计
		Object objbwgr = tablepane.getTable().getValueAt(5, 5);
		// 表六 实际已缴当月工资个人部分未扣-公司部分合计
		Object objblgs = tablepane.getTable().getValueAt(4, 8);
		// 表六 实际已缴当月工资个人部分未扣-个人部分合计
		Object objblgr = tablepane.getTable().getValueAt(5, 8);
		// 表七 实际未缴当月工资个人部分已扣-个人部分合计
		Object objbqgr = tablepane.getTable().getValueAt(7, 2);
		// 表八 实际集团内其他公司已缴当月工资个人部分已扣-个人部分合计
		Object objbbgr = tablepane.getTable().getValueAt(7, 5);
		// 公积金分摊表总金额
		Object objsibco = tablepane.getTable().getValueAt(1, 3);

		/** 借方：管理费用/住房公积金/部门：其他虚拟财务 **/
		UFDouble bsgs = objbsgs == null ? UFDouble.ZERO_DBL : new UFDouble(objbsgs.toString());
		UFDouble bwgs = objbwgs == null ? UFDouble.ZERO_DBL : new UFDouble(objbwgs.toString());
		UFDouble blgs = objblgs == null ? UFDouble.ZERO_DBL : new UFDouble(objblgs.toString());
		// 金额=表四 表五 表六 公司部分合计
		UFDouble gjjcmpamout = bsgs.add(bwgs).add(blgs);

		/** 借方：其他应收款/五险一金 **/
		UFDouble bwgr = objbwgr == null ? UFDouble.ZERO_DBL : new UFDouble(objbwgr.toString());
		UFDouble bqgr = objbqgr == null ? UFDouble.ZERO_DBL : new UFDouble(objbqgr.toString());
		// 金额=表五 表七 个人部分合计
		UFDouble bwbqhj = bwgr.add(bqgr);

		/** 借方：其他应收款/个人往来/个人明细/人员档案 **/
		UFDouble bygs = objgs == null ? UFDouble.ZERO_DBL : new UFDouble(objgs.toString());
		UFDouble blgr = objblgr == null ? UFDouble.ZERO_DBL : new UFDouble(objblgr.toString());
		// 金额=表一公司部分合计+表六个人部分合计
		UFDouble byblhj = bygs.add(blgr);

		/** 借方：应付账款/预估成本/办公费/部门：对应部门 项目：其他 项目专业：不涉及 **/
		UFDouble bmgs = objbmgs == null ? UFDouble.ZERO_DBL : new UFDouble(objbmgs.toString());
		UFDouble bmgr = objbmgr == null ? UFDouble.ZERO_DBL : new UFDouble(objbmgr.toString());
		// 金额=表三(由部门承担) 表三 个人部分+公司部分合计 (个人部分为0)
		UFDouble bsbmhj = bmgs.add(bmgr);

		/** 借方：其他应收款/单位往来/对应公司-上海茗杰商务咨询有限公司 注：辅助核算客商和人关联的，尤咏杰---上海茗杰商务咨询有限公司 **/
		// 现在只有1个人（尤咏杰），先写默认值，后续有新增人员再进行优化
		UFDouble wbgs = objwbgs == null ? UFDouble.ZERO_DBL : new UFDouble(objwbgs.toString());
		UFDouble wbgr = objwbgr == null ? UFDouble.ZERO_DBL : new UFDouble(objwbgr.toString());
		// 金额=表二 个人部分+公司部分合计 天祥投资结算
		UFDouble wbgshj = wbgs.add(wbgr);

		/** 借方：其他应收款/内部往来/代垫费用/对应公司 **/
		// 金额=表四 个人部分合计
		UFDouble bsgr = objbsgr == null ? UFDouble.ZERO_DBL : new UFDouble(objbsgr.toString());

		/** 生成的凭证自动加一行借方数据，等于管理费用/社会保险费/部门：其他虚拟财务与应付账款/预估成本/办公费/部门：合计值 借方：应付职工薪酬/住房公积金 **/
		// 金额=管理费用/住房公积金+应付账款/预估成本/办公费
		UFDouble gjjhj = gjjcmpamout.add(bsbmhj);

		/** 贷方: 预付账款/待摊费用/待摊事项：公积金摊销 **/
		// 金额=公积金汇缴单实际缴纳数
		UFDouble jsibcomount = objsibco == null ? UFDouble.ZERO_DBL : new UFDouble(objsibco.toString());
		// 金额=社保分摊表金额扣除内部往来
		UFDouble xjsibcomount = jsibcomount.sub(bsgr);

		/** 贷方: 其他应收款/个人往来 **/
		// 金额=表七个人部分合计
		UFDouble bqgrmx = objbqgr == null ? UFDouble.ZERO_DBL : new UFDouble(objbqgr.toString());

		/** 生成的凭证自动加一行借方数据，等于管理费用/社会保险费/部门：其他虚拟财务与应付账款/预估成本/办公费/部门：合计值 贷方：应付职工薪酬/住房公积金 **/
		// 金额=管理费用/住房公积金+应付账款/预估成本/办公费
		UFDouble gjjhd = gjjcmpamout.add(bsbmhj);

		map.put("管理费用/住房公积金", gjjcmpamout);
		map.put("其他应收款/五险一金", bwbqhj);
		map.put("其他应收款/个人往来", byblhj);
		map.put("应付账款/预估成本/办公费", bsbmhj);
		map.put("其他应收款/单位往来", wbgshj);
		// map.put("其他应收款/内部往来", bsgr);
		map.put("应付职工薪酬/住房公积金", gjjhj);
		map.put("预付账款/待摊费用/贷方", xjsibcomount);
		map.put("其他应收款/个人往来/贷方", bqgrmx);
		map.put("应付职工薪酬/住房公积金/贷方", gjjhd);
		return map;
	}

	// 凭证封装
	public VoucherVO getVoucherVO(Map<String, UFDouble> map) throws Exception {
		VoucherVO voucher = new VoucherVO();
		String pk_org = getPk_financeorg(orgCode);
		// 组织版本
		String pk_group = InvocationInfoProxy.getInstance().getGroupId();// 集团
		String yearperiod = period.substring(0, 4);// 会计年度
		String monthperiod = period.substring(5, 7);// 会计月份
		Date newDate = convertStringToDate(period + "-01", "yyyy-MM-dd");
		String nexMonthDate = getMonthFirstDate(newDate);// 下月最后一天
		String year = nexMonthDate.substring(0, 4);// 会计年度
		String month = nexMonthDate.substring(5, 7);// 会计月份
		//String pk_user = InvocationInfoProxy.getInstance().getUserId();// 制单人
		String pk_user = getpk_user("XTPZ000101");//制单人
		String pk_accountGlbook = tran_accountingbook(pk_org);// 核算账簿
		String pk_vouchertype = vouchertypeGetCode("03");// 凭证类型03;
		String pk_org_v = getPkorgv(pk_org);
		voucher.setPk_vouchertype(pk_vouchertype);// 记账凭证
		voucher.setAttachment(0);
		voucher.setDetailmodflag(UFBoolean.TRUE);
		voucher.setDiscardflag(UFBoolean.FALSE);
		voucher.setIsdifflag(UFBoolean.FALSE);
		voucher.setPeriod(month);// 会计月份
		voucher.setPk_manager("N/A");
		voucher.setPk_prepared(pk_user);
		voucher.setCreator(pk_user);
		voucher.setPk_system("GL");// 新增来源系统（社保公积金），用来和手工区分
		// voucher.setPrepareddate(new UFDate(period + "-30"));// 凭证日期
		if ("02".equals(month)) {
			voucher.setPrepareddate(new UFDate(nexMonthDate));// 凭证日期
		} else {
			voucher.setPrepareddate(new UFDate(nexMonthDate));// 凭证日期
		}
		voucher.setSignflag(UFBoolean.TRUE);
		voucher.setVoucherkind(0);
		voucher.setYear(year);// 会计年度
		voucher.setPk_org(pk_org);
		voucher.setPk_org_v(pk_org_v);
		voucher.setPk_group(pk_group);
		voucher.setPk_accountingbook(pk_accountGlbook);
		ArrayList<DetailVO> itemarr = new ArrayList<DetailVO>();
		for (Entry<String, UFDouble> entry : map.entrySet()) {
			String key = entry.getKey();
			String km_code = "";
			UFDouble creditamount = UFDouble.ZERO_DBL;
			UFDouble debitamount = UFDouble.ZERO_DBL;
			String pk_accasoa = "";
			if ("管理费用/住房公积金".equals(key)) {
				km_code = "660206";// 管理费用/住房公积金
				debitamount = entry.getValue();// 借方发生额
				if (debitamount.doubleValue() != 0) {
					pk_accasoa = tranKm(km_code, pk_accountGlbook);// 科目
					DetailVO itemVO = new DetailVO();
					getDetailvo(itemVO, pk_accasoa, creditamount, debitamount, voucher, "缴纳" + yearperiod + "年" + monthperiod + "月 公积金");
					// 辅助核算
					AssVO[] assvos = getAss(pk_accasoa, "0001", "其他-虚拟（财务成本归结）", pk_org);// 部门：其他虚拟财务
					ArrayList<AssVO> arrassvo = new ArrayList<AssVO>();
					arrassvo.add(assvos[0]);
					itemVO.setAss((AssVO[]) arrassvo.toArray(new AssVO[0]));
					itemarr.add(itemVO);
				}
				
			} else if ("其他应收款/五险一金".equals(key)) {
				km_code = "122104";// 其他应收款/五险一金
				debitamount = entry.getValue();// 借方发生额
				if (debitamount.doubleValue() != 0) {
					pk_accasoa = tranKm(km_code, pk_accountGlbook);// 科目
					DetailVO itemVO = new DetailVO();
					getDetailvo(itemVO, pk_accasoa, creditamount, debitamount, voucher, "缴纳" + yearperiod + "年" + monthperiod + "月 公积金");
					itemarr.add(itemVO);
				}
				
			} else if ("其他应收款/个人往来".equals(key)) {
				km_code = "122102";// 其他应收款/个人往来
				debitamount = entry.getValue();// 借方发生额
				pk_accasoa = tranKm(km_code, pk_accountGlbook);// 科目
				if (null != tableOneOrgMap) {// 表一个人承担公司部分
					UFDouble debitamounttotal = new UFDouble();
					for (Entry<String, UFDouble> tableOneOrgEntry : tableOneOrgMap.entrySet()) {
						String checkCode_name = tableOneOrgEntry.getKey();
						String checkCode = checkCode_name.split(",")[0];
						String userName = checkCode_name.split(",")[1];
						UFDouble debitamountOrg = tableOneOrgEntry.getValue();// 借方发生额
						if (debitamountOrg.doubleValue() != 0) {
							debitamounttotal = debitamounttotal.add(debitamountOrg);
							DetailVO itemVO = new DetailVO();
							getDetailvo(itemVO, pk_accasoa, creditamount, debitamountOrg, voucher, "缴纳" + yearperiod + "年" + monthperiod + "月 公积金 " + userName);
							// 辅助核算
							AssVO[] assvos = getAss(pk_accasoa, "0002", psndocCode(checkCode), pk_org);// 人员
							ArrayList<AssVO> arrassvo = new ArrayList<AssVO>();
							arrassvo.add(assvos[0]);
							itemVO.setAss((AssVO[]) arrassvo.toArray(new AssVO[0]));
							itemarr.add(itemVO);
						}
					}
					UFDouble debitamounttotal1 = debitamounttotal;
				}
				if (null != tableSixSelfMap) {// 表六 个人部分
					UFDouble debitamounttotal = new UFDouble();
					for (Entry<String, UFDouble> tableSixSelfEntry : tableSixSelfMap.entrySet()) {
						String checkCode_name = tableSixSelfEntry.getKey();
						String checkCode = checkCode_name.split(",")[0];
						String userName = checkCode_name.split(",")[1];
						UFDouble debitamountSelf = tableSixSelfEntry.getValue();// 借方发生额
						if (debitamountSelf.doubleValue() != 0) {
							debitamounttotal = debitamounttotal.add(debitamountSelf);
							DetailVO itemVO = new DetailVO();
							getDetailvo(itemVO, pk_accasoa, creditamount, debitamountSelf, voucher, "缴纳" + yearperiod + "年" + monthperiod + "月 公积金 " + userName + "-实际已缴个人未扣");
							// 辅助核算
							AssVO[] assvos = getAss(pk_accasoa, "0002", psndocCode(checkCode), pk_org);// 人员
							ArrayList<AssVO> arrassvo = new ArrayList<AssVO>();
							arrassvo.add(assvos[0]);
							itemVO.setAss((AssVO[]) arrassvo.toArray(new AssVO[0]));
							itemarr.add(itemVO);
						}
					}
					UFDouble debitamounttotal1 = debitamounttotal;
				}
			} else if ("应付账款/预估成本/办公费".equals(key)) {
				km_code = "22020205";// 应付账款/预估成本/办公费
				debitamount = entry.getValue();// 借方发生额
				if (debitamount.doubleValue() != 0) {
					pk_accasoa = tranKm(km_code, pk_accountGlbook);// 科目
					DetailVO itemVO = new DetailVO();
					getDetailvo(itemVO, pk_accasoa, creditamount, debitamount, voucher, "缴纳" + yearperiod + "年" + monthperiod + "月 公积金 ");
					// 辅助核算  2025-03-13
					ArrayList<AssVO> arrassvo = new ArrayList<AssVO>();
					AssVO[] assvos = getAss(pk_accasoa, "0010", "PM201601130001", pk_org);// 项目：其他
					AssVO[] assvos2 = getAss(pk_accasoa, "0043", "99", pk_org);// 项目专业：不涉及
					if("000101".equals(orgCode)){
						AssVO[] assvos1 = getAss(pk_accasoa, "0001", "结构三所", pk_org);// 部门：结构三所
						arrassvo.add(assvos1[0]);	
					}else{
						AssVO[] assvos1 = getAss(pk_accasoa, "0001", "其他-虚拟（财务成本归结）", pk_org);// 部门：其他虚拟财务
						arrassvo.add(assvos1[0]);
					}
					arrassvo.add(assvos[0]);
					arrassvo.add(assvos2[0]);
					itemVO.setAss((AssVO[]) arrassvo.toArray(new AssVO[0]));
					itemarr.add(itemVO);	
				}
				
			} else if ("其他应收款/单位往来".equals(key)) {
				km_code = "122101";// 其他应收款/单位往来
				debitamount = entry.getValue();// 借方发生额
				if(debitamount.doubleValue() != 0){// 判断外部公司承担表公司部分是否为0(龙咏杰特殊处理)
					pk_accasoa = tranKm(km_code, pk_accountGlbook);// 科目
					DetailVO itemVO = new DetailVO();
					getDetailvo(itemVO, pk_accasoa, creditamount, debitamount, voucher, "缴纳" + yearperiod + "年" + monthperiod + "月 公积金 尤咏杰");
					// 辅助核算：上海茗杰商务咨询有限公司
					AssVO[] assvos = getAss(pk_accasoa, "0004", "G006353", pk_org);// 客商
					ArrayList<AssVO> arrassvo = new ArrayList<AssVO>();
					arrassvo.add(assvos[0]);
					itemVO.setAss((AssVO[]) arrassvo.toArray(new AssVO[0]));
					itemarr.add(itemVO);
				}
				
			}
			// else if ("其他应收款/内部往来".equals(key)) {
			// // 取表四个人部分合计包含各个子公司，每个公司一条明细
			// km_code = "12210503";// 其他应收款/内部往来/代垫费用
			// debitamount = entry.getValue();// 借方发生额
			// pk_accasoa = tranKm(km_code, pk_accountGlbook);// 科目
			// if (null != tableFourSelfMap) {// 表四每个公司小计
			// UFDouble debitamounttotal = new UFDouble();
			// for (Entry<String, UFDouble> tableFourSelfEntry : tableFourSelfMap.entrySet()) {
			// String orgName = tableFourSelfEntry.getKey();
			// UFDouble debitamountOrg = tableFourSelfEntry.getValue();// 借方发生额
			// debitamounttotal = debitamounttotal.add(debitamountOrg);
			// if (debitamountOrg.doubleValue() != 0) {
			// DetailVO itemVO = new DetailVO();
			// getDetailvo(itemVO, pk_accasoa, creditamount, debitamountOrg, voucher, "缴纳" + year + "年" + month + "月 公积金 ");
			// // 辅助核算
			// AssVO[] assvos = getAss(pk_accasoa, "0004", getbd_cust_supplier_code(orgName), pk_org);// 客商
			// ArrayList<AssVO> arrassvo = new ArrayList<AssVO>();
			// arrassvo.add(assvos[0]);
			// itemVO.setAss((AssVO[]) arrassvo.toArray(new AssVO[0]));
			// itemarr.add(itemVO);
			// }
			// }
			// UFDouble debitamounttotal1 = debitamounttotal;
			// }
			// }
			else if ("应付职工薪酬/住房公积金".equals(key)) {
				km_code = "221106";// 应付职工薪酬/住房公积金 无辅助核算
				debitamount = entry.getValue();// 借方发生额
				if (debitamount.doubleValue() != 0) {
					pk_accasoa = tranKm(km_code, pk_accountGlbook);// 科目
					DetailVO itemVO = new DetailVO();
					getDetailvo(itemVO, pk_accasoa, creditamount, debitamount, voucher, "缴纳" + yearperiod + "年" + monthperiod + "月 公积金 ");
					itemarr.add(itemVO);
				}
				
			} else if ("预付账款/待摊费用/贷方".equals(key)) {
				// km_code = "220201";
				km_code = "11230101";// 预付账款/待摊费用
				creditamount = entry.getValue();// 贷方发生额
				if (creditamount.doubleValue() != 0) {
					pk_accasoa = tranKm(km_code, pk_accountGlbook);// 科目
					DetailVO itemVO = new DetailVO();
					getDetailvo(itemVO, pk_accasoa, creditamount, debitamount, voucher, "缴纳" + yearperiod + "年" + monthperiod + "月 公积金 ");
					// 辅助核算
					// AssVO[] assvos = getAss(pk_accasoa, "0004", "G000371", pk_org);// 客商
					AssVO[] assvos = getAss(pk_accasoa, "05", "10", pk_org);// 待摊事项：公积金摊销
					ArrayList<AssVO> arrassvo = new ArrayList<AssVO>();
					arrassvo.add(assvos[0]);
					itemVO.setAss((AssVO[]) arrassvo.toArray(new AssVO[0]));
					itemarr.add(itemVO);
				}
				
			} else if ("其他应收款/个人往来/贷方".equals(key)) {
				km_code = "122102";// 其他应收款/个人往来
				creditamount = entry.getValue();// 贷方发生额
				pk_accasoa = tranKm(km_code, pk_accountGlbook);// 科目
				if (null != tableSevenSelfMap) {// 表七个人承担个人部分
					UFDouble debitamounttotal = new UFDouble();
					for (Entry<String, UFDouble> tableSevenSelfEntry : tableSevenSelfMap.entrySet()) {
						String checkCode_name = tableSevenSelfEntry.getKey();
						String checkCode = checkCode_name.split(",")[0];
						String userName = checkCode_name.split(",")[1];
						UFDouble creditamountOrg = tableSevenSelfEntry.getValue();// 贷方发生额
						if (creditamountOrg.doubleValue() != 0) {
							debitamounttotal = debitamounttotal.add(creditamountOrg);
							DetailVO itemVO = new DetailVO();
							getDetailvo(itemVO, pk_accasoa, creditamountOrg, debitamount, voucher, "缴纳" + yearperiod + "年" + monthperiod + "月 公积金 " + userName + "-实际未缴个人已扣");
							// 辅助核算
							AssVO[] assvos = getAss(pk_accasoa, "0002", psndocCode(checkCode), pk_org);// 人员
							ArrayList<AssVO> arrassvo = new ArrayList<AssVO>();
							arrassvo.add(assvos[0]);
							itemVO.setAss((AssVO[]) arrassvo.toArray(new AssVO[0]));
							itemarr.add(itemVO);
						}
					}
					UFDouble debitamounttotal1 = debitamounttotal;
				}
			} else if ("应付职工薪酬/住房公积金/贷方".equals(key)) {
				km_code = "221106";// 应付职工薪酬/住房公积金 无辅助核算
				creditamount = entry.getValue();// 贷方发生额
				if (creditamount.doubleValue() != 0) {
					pk_accasoa = tranKm(km_code, pk_accountGlbook);// 科目
					DetailVO itemVO = new DetailVO();
					getDetailvo(itemVO, pk_accasoa, creditamount, debitamount, voucher, "缴纳" + yearperiod + "年" + monthperiod + "月 公积金 ");
					itemarr.add(itemVO);
				}
				
			}
		}
		voucher.setDetails((DetailVO[]) itemarr.toArray(new DetailVO[0]));
		return voucher;
	}

	private DetailVO getDetailvo(DetailVO itemVO, String pk_accasoa, UFDouble creditamount, UFDouble debitamount, VoucherVO voucher, String explanation) throws BusinessException {
		String pk_currtype = getcurrtype("CNY");// 币种
		itemVO.setPk_accasoa(pk_accasoa);// 会计科目
		itemVO.setCreditamount(creditamount);// 贷方
		itemVO.setCreditquantity(UFDouble.ZERO_DBL);// 数量
		itemVO.setDebitamount(debitamount);// 借方
		itemVO.setDirection("D");// 方向
		itemVO.setDebitquantity(UFDouble.ZERO_DBL);
		itemVO.setDiscardflag(UFBoolean.FALSE);
		itemVO.setExcrate1(UFDouble.ZERO_DBL);
		itemVO.setExcrate2(UFDouble.ONE_DBL);
		itemVO.setExplanation(explanation);// 摘要
		voucher.setExplanation(explanation);// 主表摘要
		itemVO.setFraccreditamount(UFDouble.ZERO_DBL);
		itemVO.setFracdebitamount(UFDouble.ZERO_DBL);
		itemVO.setIsdifflag(UFBoolean.FALSE);
		itemVO.setLocalcreditamount(itemVO.getCreditamount());// 全局贷方
		itemVO.setLocaldebitamount(itemVO.getDebitamount());// 借方
		itemVO.setPeriod(voucher.getPeriod());// 会计期间
		itemVO.setPk_manager(voucher.getPk_manager());
		itemVO.setPk_system(voucher.getPk_system());
		itemVO.setPk_vouchertype(voucher.getPk_vouchertype());// 凭证类型
		itemVO.setPrepareddate(voucher.getPrepareddate());
		itemVO.setPrice(UFDouble.ZERO_DBL);
		itemVO.setVoucherkind(0);// 凭证类别
		itemVO.setYear(voucher.getYear());
		itemVO.setPk_org(voucher.getPk_org());
		itemVO.setPk_org(voucher.getPk_org());
		itemVO.setPk_org_v(voucher.getPk_org_v());
		itemVO.setPk_group(voucher.getPk_group());
		itemVO.setPk_accountingbook(voucher.getPk_accountingbook());
		itemVO.setPk_unit(voucher.getPk_org());
		itemVO.setPk_unit_v(voucher.getPk_org_v());
		itemVO.setPk_currtype(pk_currtype);// 币种
		return itemVO;
	}

	private AssVO[] getAss(String pk_km, String code1, String pk_checkvalue1, String pk_org) throws ClassNotFoundException, BusinessException {

		ArrayList zrr = new ArrayList();

		String sql = "select c.pk_accasoa,\n" + "       c.pk_accchart,\n" + "       c.pk_account,\n" + "       c.name,\n" + "       c.dispname,\n" + "       a.refnodename,\n" + "\n"
				+ "       a.code,\n" + "       a.name,\n" + "       a.refnodename,\n" + "       m.defaulttablename,\n" + "       m.id,\n" + "       a.  pk_accassitem  ,  m.fullclassname  "
				+ "  from bd_accassitem a, bd_accass b, bd_accasoa c, md_class m\n" + " where a.classid = m.id\n" + "   and a.pk_accassitem = b.pk_entity\n" + "   and b.pk_accasoa = c.pk_accasoa\n"
				+ "  and  c.pk_accasoa  = '" + pk_km + "' ";
		if (code1 != null) {
			sql += "  and   a.code = '" + code1 + "'  ";
		}
		;
		// 查询科目对应的辅助核算
		ArrayList ass_arr = (ArrayList) iuap.executeQuery(sql, new MapListProcessor());
		if (ass_arr != null) {
			for (int j = 0; j < ass_arr.size(); j++) {
				HashMap assmap = (HashMap) ass_arr.get(j);
				String getRefnodename = assmap.get("refnodename") + "";
				String fullclassname = assmap.get("fullclassname") + "";
				SuperVO refvo = initSuperVOClass(Class.forName(fullclassname));
				String qrykey = "code";
				if ("项目".equals(getRefnodename)) {
					qrykey = "project_code";
				} else if ("部门".equals(getRefnodename)) {
					qrykey = "name";
				}
				String refsql = "select * from   " + refvo.getTableName() + " where  nvl(dr,0) = 0   and ( " + qrykey + "  ='" + pk_checkvalue1 + "'  or " + refvo.getPKFieldName() + " = '"
						+ pk_checkvalue1 + "' )";
				if (refvo.getTableName().equals("org_dept")) {
					refsql = "select * from   " + refvo.getTableName() + " where  nvl(dr,0) = 0  and   pk_org  = '" + pk_org + "'  and ( " + qrykey + "  ='" + pk_checkvalue1 + "'  or "
							+ refvo.getPKFieldName() + " = '" + pk_checkvalue1 + "' )";
				} else if (refvo.getTableName().equals("bd_defdoc")) {
					if ("公司内部专业(自定义档案)".equals(getRefnodename)) {
						refsql = "select * from   " + refvo.getTableName() + " where  nvl(dr,0) = 0  and  ( " + qrykey + "  ='" + pk_checkvalue1 + "'  or " + refvo.getPKFieldName() + " = '"
								+ pk_checkvalue1 + "' )  " + "and  pk_defdoclist =(select pk_defdoclist from  bd_defdoclist  where   code = 'HR016' )     ";
					} else if ("现金流(自定义档案)".equals(getRefnodename)) {
						refsql = "select * from   " + refvo.getTableName() + " where  nvl(dr,0) = 0  and  ( " + qrykey + "  ='" + pk_checkvalue1 + "'  or " + refvo.getPKFieldName() + " = '"
								+ pk_checkvalue1 + "' )  " + "and  pk_defdoclist =(select pk_defdoclist from  bd_defdoclist  where   code ='X01')     ";
					} else if ("待摊事项(自定义档案)".equals(getRefnodename)) {
						refsql = "select * from   " + refvo.getTableName() + " where  nvl(dr,0) = 0  and  ( " + qrykey + "  ='" + pk_checkvalue1 + "'  or " + refvo.getPKFieldName() + " = '"
								+ pk_checkvalue1 + "' )  " + "and  pk_defdoclist =(select pk_defdoclist from  bd_defdoclist  where   code = '14' )     ";
					}
				}
				SuperVO dataVO = (SuperVO) iuap.executeQuery(refsql, new BeanProcessor(Class.forName(fullclassname)));
				if (dataVO == null) {
					throw new BusinessException("辅助核算翻译失败：" + pk_checkvalue1);
				}
				AssVO tempAss = new AssVO();
				String pk_checkvalue = dataVO.getPrimaryKey();
				String code = "";
				if ("项目".equals(getRefnodename)) {
					code = dataVO.getAttributeValue("project_code") + "";
				} else {
					code = dataVO.getAttributeValue("code") + "";
				}
				if ("".equals(getRefnodename)) {
					// 说明是基本类型，则直接当作字符串保存
					tempAss.setPk_Checkvalue(code);
					tempAss.setPk_Checktype(assmap.get("pk_accassitem") + "");
					tempAss.setChecktypecode(assmap.get("code") + "");
					tempAss.setChecktypename(assmap.get("name") + "");
				} else {
					tempAss.setPk_Checktype(assmap.get("pk_accassitem") + "");
					tempAss.setChecktypecode(assmap.get("code") + "");
					tempAss.setChecktypename(assmap.get("name") + "");
					if ("项目".equals(getRefnodename)) {
						tempAss.setCheckvaluename(dataVO.getAttributeValue("project_name") + "");
					} else {

						tempAss.setCheckvaluename(dataVO.getAttributeValue("name") + "");
					}
					tempAss.setPk_Checkvalue(pk_checkvalue);
					tempAss.setCheckvaluecode(code);
				}
				if (tempAss != null && "".equals(tempAss.getPk_Checkvalue())) {
					throw new BusinessException("辅助核算翻译失败：" + code);
				}
				zrr.add(tempAss);
			}
		} else {
			return null;
		}
		return (AssVO[]) zrr.toArray(new AssVO[0]);
	}

	private SuperVO initSuperVOClass(Class className) {
		Object vo;
		try {
			vo = className.newInstance();
		} catch (InstantiationException e) {
			throw new IllegalArgumentException("Parameter Class can not be instantiated!!");
		} catch (IllegalAccessException e) {
			throw new IllegalArgumentException(" Illegal Parameter!!");
		}
		if (!(vo instanceof SuperVO))
			throw new IllegalArgumentException("Parameter Class is not SuperVO");
		return (SuperVO) vo;
	}

	/**
	 * 币种
	 * 
	 * @param pk_org
	 * @return
	 * @throws BusinessException
	 * @throws DAOException
	 */
	private String getcurrtype(String code) throws BusinessException {
		String sql = "select      pk_currtype   from  bd_currtype  where    code   = ? and nvl(dr,0) = 0 ";
		SQLParameter parameter = new SQLParameter();
		parameter.addParam(code);
		Object pk_currtype = iuap.executeQuery(sql, parameter, new ColumnProcessor());
		return pk_currtype != null ? pk_currtype + "" : "";
	}

	/**
	 * 核算账簿
	 * 
	 * @throws BusinessException
	 * @throws DAOException
	 */
	private String tran_accountingbook(String pk_org) throws BusinessException {
		String sql = "select   pk_accountingbook  from  org_accountingbook  where    pk_relorg   = ? and nvl(dr,0) = 0 ";
		SQLParameter parameter = new SQLParameter();
		parameter.addParam(pk_org);
		Object pk_vouchertype = iuap.executeQuery(sql, parameter, new ColumnProcessor());
		return pk_vouchertype != null ? pk_vouchertype + "" : "";
	}

	/**
	 * 凭证类型
	 * 
	 * @param pk
	 * @return
	 * @throws DAOException
	 * @throws BusinessException
	 */
	private String vouchertypeGetCode(String pk) throws BusinessException {
		String sql = "select  pk_vouchertype     from  bd_vouchertype  where  code   = ? and nvl(dr,0) = 0 ";
		SQLParameter parameter = new SQLParameter();
		parameter.addParam(pk);
		Object pk_vouchertype = iuap.executeQuery(sql, parameter, new ColumnProcessor());
		return pk_vouchertype != null ? pk_vouchertype + "" : "";
	}

	/**
	 * 财务组织版本
	 */
	private String getPkorgv(String pk) throws BusinessException {
		String sql = "select   pk_vid    from  org_financeorg_v  where   pk_financeorg    = ? and nvl(dr,0) = 0 ";
		SQLParameter parameter = new SQLParameter();
		parameter.addParam(pk);
		Object pk_vid = iuap.executeQuery(sql, parameter, new ColumnProcessor());
		return pk_vid != null ? pk_vid + "" : "";
	}

	/**
	 * 科目编码翻译
	 * 
	 * @throws BusinessException
	 * @throws DAOException
	 */
	private String tranKm(String km_code, String pk_accountingbook) throws BusinessException {
		String sql = "select bd_accasoa.pk_accasoa\n" + "  from bd_accasoa bd_accasoa\n" + " inner join bd_account\n" + "    on bd_accasoa.pk_account = bd_account.pk_account\n" + " where 11 = 11\n"
				+ "   and ((bd_accasoa.enablestate = 1 or bd_accasoa.enablestate = 2 or\n" + "       bd_accasoa.enablestate = 3))\n" + "   and bd_account.code = ?\n"
				+ "   and bd_accasoa.pk_accchart =\n" + "       (select pk_accchart\n" + "           from bd_accchart\n" + "          where  originalchart =\n"
				+ "                 (select pk_curraccchart\n" + "                    from org_accountingbook\n" + "                   where pk_accountingbook = ? and alterchart <> '~' and\n"
				+ "           tempversionflag <> 'Y'));";
		SQLParameter parameter = new SQLParameter();
		parameter.addParam(km_code);
		parameter.addParam(pk_accountingbook);
		Object pk_accasoa = (String) iuap.executeQuery(sql, parameter, new ColumnProcessor());
		return pk_accasoa != null ? pk_accasoa + "" : "";
	}

	// 查询表一员工名称
	private List<String> querygcode(String orgCode, String period) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT");
		sql.append(" clerkcode ");
		sql.append(" FROM");
		sql.append(" (SELECT ROWNUM AS seq,t.CLERKCODE,T1.CLERKNAME,t.ym,sum( nvl( t.VALUE, 0 ) ) AS sum_per_cost,t1.ENDOWMENT_BASE");
		sql.append(" FROM");
		sql.append(" NC6337.v_data_xz_gjjshare t");
		sql.append(" LEFT JOIN NC6337.V_SUM_TB_HR_SOCIAL_SECURITY t1 ON t1.CLERKCODE = t.CLERKCODE AND t1.PAY_MONTH || '-01' = t.ym");
		sql.append(" WHERE");
		sql.append(" t.key = '社保公司税后扣款' AND t.VALUE <> 0 AND t.ym = '" + period + "' || '-01' AND t1.ORGCODE = '" + orgCode + "'");
		sql.append(" AND t1.ENDOWMENT_BASE IS NOT NULL");
		sql.append(" GROUP BY ROWNUM,t.CLERKCODE,T1.CLERKNAME,t.ym,t1.ENDOWMENT_BASE");
		sql.append(" ORDER BY ROWNUM)");
		return (List<String>) iuap.executeQuery(sql.toString(), new ColumnListProcessor());
	}

	// 员工编号查询人员编码
	private String psndocCode(String clerkcode) throws BusinessException {
		String sql = "select bd_psndoc.code from  hi_psnjob " + "inner join bd_psndoc on bd_psndoc.pk_psndoc=hi_psnjob.pk_psndoc " + "and nvl(hi_psnjob.dr,0)=0 and nvl(bd_psndoc.dr,0)=0 "
				+ "and hi_psnjob.clerkcode='" + clerkcode + "'  ";
		Object code = (String) iuap.executeQuery(sql, new ColumnProcessor());
		return code != null ? code + "" : "";
	}

	private String getPk_financeorg(String code) throws BusinessException {
		String sql = "select pk_financeorg  from  org_financeorg  where code='" + code + "' and nvl(dr,0)=0 and enablestate ='2' ";
		Object pk_financeorg = (String) iuap.executeQuery(sql, new ColumnProcessor());
		return pk_financeorg != null ? pk_financeorg + "" : "";
	}

	private String getpk_user(String code) throws BusinessException {
		String sql = "select cuserid   from  sm_user  where user_code='" + code + "' and nvl(dr,0)=0 and enablestate ='2' ";
		Object cuserid = (String) iuap.executeQuery(sql, new ColumnProcessor());
		return cuserid != null ? cuserid + "" : "";
	}

	// 根据客商名称查询客商编码
	private String getbd_cust_supplier_code(String name) throws BusinessException {
		String sql = "select code  from  bd_cust_supplier  where name='" + name + "' and nvl(dr,0)=0  ";
		Object code = (String) iuap.executeQuery(sql, new ColumnProcessor());
		return code != null ? code + "" : "";
	}

	// 日期格式转字符串
	private String getMonthFirstDate(Date date) {
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		calendar.add(Calendar.MONTH, 1);
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		Date first = calendar.getTime();
		return convertDateToString(first, "yyyy-MM-dd");
	}

	// 获取下个月最后一天
	private String convertDateToString(Date inDate, String dateFormat) {
		String resultValue = "";
		if (inDate == null) {
			return resultValue;
		}
		try {
			SimpleDateFormat df = new SimpleDateFormat(dateFormat == null ? "yyyy-MM-dd" : dateFormat, Locale.US);
			resultValue = df.format(inDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultValue;
	}

	// 字符串转日期格式
	private Date convertStringToDate(String inDate, String format) {
		if (inDate == null || inDate.isEmpty()) {
			return null;
		}
		SimpleDateFormat df;
		Date resultDate = null;
		try {
			df = new SimpleDateFormat(format == null ? "yyyy-MM-dd" : format, Locale.US);
			df.setLenient(false);
			resultDate = df.parse(inDate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultDate;
	}

	/**
	 * 
	 * 生成内部应收单
	 * 
	 * @throws Exception
	 * 
	 */
	private String addReceivableBill(UITablePane tablepane) throws Exception {
		String billNO = "";
		Map<String, UFDouble> map = new LinkedHashMap<String, UFDouble>();
		// 表四 个人部分已在集团内其他公司扣除-个人部分合计
		Object objbsgr = tablepane.getTable().getValueAt(5, 2);
		/** 借方：其他应收款/内部往来/代垫费用/对应公司 **/
		// 金额=表四 个人部分合计
		UFDouble bsgr = objbsgr == null ? UFDouble.ZERO_DBL : new UFDouble(objbsgr.toString());// 20385.96
		if (null != tableFourSelfMap) {// 表四每个公司小计
			AggReceivableBillVO aggReceivableBillVO = new AggReceivableBillVO();
			ReceivableBillVO receivableBillVO = new ReceivableBillVO();
			// 赋值主表数据
			receivableBillVO.setDef11("公积金分摊表_" + orgCode + "_" + period);
			String pk_org = getPk_financeorg(orgCode);
			// 组织版本
			String pk_group = InvocationInfoProxy.getInstance().getGroupId();// 集团
			String pk_user = InvocationInfoProxy.getInstance().getUserId();// 制单人
			String pk_org_v = getPkorgv(pk_org);
			receivableBillVO.setBillstatus(-1);
			receivableBillVO.setPk_group(pk_group);
			receivableBillVO.setPk_org(pk_org);
			receivableBillVO.setPk_org_v(pk_org_v);
			receivableBillVO.setPk_fiorg(pk_org);// 应收财务组织
			receivableBillVO.setSett_org(pk_org);// 结算财务组织
			receivableBillVO.setSett_org_v(pk_org);// 结算财务组织版本
			receivableBillVO.setBillmaker(pk_user);// 制单人
			receivableBillVO.setBilldate(new UFDate());// 单据日期
			receivableBillVO.setCreator(pk_user);// 创建人
			receivableBillVO.setCreationtime(new UFDateTime());// 创建时间
			receivableBillVO.setBusidate(new UFDate());// 开票日期
			receivableBillVO.setObjtype(0);// 往来对象
			receivableBillVO.setPk_deptid(GetDataUtil.getDeptPK("000101205"));// 收款部门
			receivableBillVO.setLocal_money(bsgr);// 合计金额--本币金额
			receivableBillVO.setMoney(bsgr);// 原币金额
			String pk_bankaccsub = GetDataUtil.getBankaccsubPK("310066218018000420123");
			receivableBillVO.setRecaccount(pk_bankaccsub);// 收款银行账户
			receivableBillVO.setPk_busitype(GetDataUtil.getBusitypePK("AR01"));// 业务流程：选择收款
			receivableBillVO.setBillclass("ys");// 单据大类：应收单
			String year = period.substring(0, 4);// 会计年度
			String month = period.substring(5, 7);// 会计月份
			receivableBillVO.setBillyear(year);// 单据会计年度
			receivableBillVO.setBillperiod(month);// 单据会计期间
			receivableBillVO.setIsreded(UFBoolean.FALSE);// 是否红冲过
			receivableBillVO.setIsflowbill(UFBoolean.FALSE);// 是否流程单据
			receivableBillVO.setPk_billtype("F0");// 单据类型编码
			String pk_currtype = getcurrtype("CNY");// 币种
			receivableBillVO.setPk_currtype(pk_currtype);// 币种
			receivableBillVO.setPk_balatype(GetDataUtil.getBalatypePK("12"));
			String pk_country = GetDataUtil.getCountryzonePK("CN");// 国家地区 默认CN
			receivableBillVO.setSendcountryid(pk_country);// 发货国
			receivableBillVO.setTaxcountryid(pk_country);// 报税国
			receivableBillVO.setSubjcode("11230101");// 科目编码
			receivableBillVO.setSrc_syscode(0);// 单据来源系统
			receivableBillVO.setSyscode(0);// 单据所属系统
			receivableBillVO.setScomment("S00009");// 摘要
			receivableBillVO.setMoney(bsgr);// 金额
			// 应收类型：内部应收单(含代垫费用)
			String pk_tradetype = "F0-Cxx-01";
			receivableBillVO.setPk_tradetype(pk_tradetype);
			String pk_billtypeid = GetDataUtil.getBilltypePK(pk_tradetype, pk_group);
			receivableBillVO.setPk_tradetypeid(pk_billtypeid);
			receivableBillVO.setIsflowbill(UFBoolean.FALSE);// 是否流程单据
			receivableBillVO.setIsreded(UFBoolean.FALSE);// 是否红冲过
			aggReceivableBillVO.setParentVO(receivableBillVO);
			List<ReceivableBillItemVO> listItemVO = new ArrayList<ReceivableBillItemVO>();
			int rowNo = 0;
			for (Entry<String, UFDouble> tableFourSelfEntry : tableFourSelfMap.entrySet()) {
				rowNo++;
				String orgName = tableFourSelfEntry.getKey();// 公司名称
				UFDouble debitamount = tableFourSelfEntry.getValue();// 借方发生额
				if (debitamount.doubleValue() != 0) {
					ReceivableBillItemVO receivableBillItemVO = new ReceivableBillItemVO();
					// 赋值子表数据
					receivableBillItemVO.setPk_org(pk_org);
					receivableBillItemVO.setPk_org_v(pk_org_v);
					receivableBillItemVO.setPk_group(pk_group);
					receivableBillItemVO.setPk_fiorg(pk_org);// 应收财务组织
					receivableBillItemVO.setDef30("06");// 费用归属：06待摊费用"
					receivableBillItemVO.setDef30(GetDataUtil.getDefdocPK("06", "05", "待摊费用"));
					receivableBillItemVO.setDef26(GetDataUtil.getDefdocPK("S00009", "08", "代垫费用"));// 收款摘要：S00009代垫费用
					receivableBillItemVO.setDef29(GetDataUtil.getDefdocPK("060501", "YS001", "不开票结算"));// 收款业务性质：060501不开票结算
					receivableBillItemVO.setDef15(GetDataUtil.getDefdocPK("其他合同（财务专用）", "01", "其他合同（财务专用）"));// 经营合同名称
					receivableBillItemVO.setDef16("其他合同（财务专用）");// 合同编号
					receivableBillItemVO.setDef10(year + month + "公积金个人部分");// 备注
					String code = getbd_cust_supplier_code(orgName);// 根据名称查询code
					receivableBillItemVO.setCustomer(GetDataUtil.getCustomerPK(code));// 客户
					receivableBillItemVO.setOrdercubasdoc(GetDataUtil.getCustomerPK(code));// 订单客户
					receivableBillItemVO.setTaxcodeid(GetDataUtil.getTaxcodePK("10"));// 税码
					receivableBillItemVO.setTaxrate(new UFDouble(0));// 税率
					receivableBillItemVO.setLocal_money_bal(debitamount);// 组织本币余额
					receivableBillItemVO.setLocal_money_de(debitamount);// 价税合计
					receivableBillItemVO.setLocal_notax_de(debitamount);// 金额
					receivableBillItemVO.setLocal_tax_de(new UFDouble(0));// 税额
					receivableBillItemVO.setLocal_price(debitamount);// 本币单价
					receivableBillItemVO.setLocal_taxprice(debitamount);// 本币含税单价
					receivableBillItemVO.setMoney_bal(debitamount);// 原币余额
					receivableBillItemVO.setMoney_de(debitamount);// 借方原币金额
					receivableBillItemVO.setNotax_de(debitamount);// 借方原币无税金额
					receivableBillItemVO.setOccupationmny(debitamount);// 预占用原币余额
					receivableBillItemVO.setCaltaxmny(debitamount);// 计税金额
					receivableBillItemVO.setPrice(debitamount);// 单价
					receivableBillItemVO.setTaxprice(debitamount);// 含税单价
					receivableBillItemVO.setBilldate(new UFDate());// 单据日期
					receivableBillItemVO.setBusidate(new UFDate());// 起算日期
					receivableBillItemVO.setPk_billtype("F0");// 单据类型编码
					receivableBillItemVO.setBillclass("ys");// 单据大类
					receivableBillItemVO.setRowno(rowNo);// 单据分录号--行号
					receivableBillItemVO.setRowtype(22);// 行类型：22代垫
					receivableBillItemVO.setDirection(1);// 方向：1借方
					receivableBillItemVO.setPk_currtype(pk_currtype);// 币种
					receivableBillItemVO.setTaxtype(1);// 扣税类别：1应税外加
					receivableBillItemVO.setObjtype(0);// 往来对象
					receivableBillItemVO.setPk_balatype(GetDataUtil.getBalatypePK("12"));
					receivableBillItemVO.setSendcountryid(pk_country);// 发货国
					receivableBillItemVO.setBuysellflag(1);// 购销类型 1国内销售
					// receivableBillItemVO.setConfernum("ARAP_0001A81000000000NVK0_D02024012200077450");// 内部交易结算号
					receivableBillItemVO.setPk_billtype("F0");// 单据类型编码
					receivableBillItemVO.setPk_deptid(GetDataUtil.getDeptPK("000101205"));// 部门
					receivableBillItemVO.setPk_deptid_v(GetDataUtil.getDeptPK("000101205"));// 部门
					receivableBillItemVO.setPk_psndoc(GetDataUtil.getPsndocPK("1001A8100000003IHP1U"));// 业务员
					// 应收类型：内部应收单(含代垫费用);
					receivableBillItemVO.setPk_tradetype(pk_tradetype);
					receivableBillItemVO.setPk_tradetypeid(pk_billtypeid);
					receivableBillItemVO.setQuantity_bal(new UFDouble(1));// 数量余额
					receivableBillItemVO.setQuantity_de(new UFDouble(1));// 借方数量
					receivableBillItemVO.setRate(new UFDouble(1));// 组织本币税率
					receivableBillItemVO.setRecaccount(pk_bankaccsub);// 收款银行账户
					receivableBillItemVO.setRececountryid(pk_country);// 收货国
					receivableBillItemVO.setSett_org(pk_org);// 结算财务组织
					receivableBillItemVO.setSett_org_v(pk_org);// 结算财务组织版本
					receivableBillItemVO.setTriatradeflag(UFBoolean.FALSE);// 三角贸易区
					receivableBillItemVO.setSettlecurr(pk_currtype);// 收款币种
					receivableBillItemVO.setSettlemoney(debitamount);// 收款金额
					listItemVO.add(receivableBillItemVO);
				}
			}
			aggReceivableBillVO.setChildrenVO(listItemVO.toArray(new ReceivableBillItemVO[listItemVO.size()]));
			// 调用应收单新增方法
			IReceivableService receivableService = NCLocator.getInstance().lookup(IReceivableService.class);
			AggReceivableBillVO aggvo = receivableService.receivable_RequiresNew(aggReceivableBillVO);
			ReceivableBillVO headerVO = (ReceivableBillVO) aggvo.getParentVO();
			billNO = headerVO.getBillno();
		}
		return billNO;
	}

}
