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.Map.Entry;
import java.util.Vector;

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.desktop.ui.WorkbenchEnvironment;
import nc.hr.utils.OutputDialogUtil;
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.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.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.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 ServiceChargeAllocationUI 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 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[] subheadings = { "序号", "员工编号", "姓名", "缴费基数", "公司部分", "备注" };
	private Map<String, Map<String, UFDouble>> beforePsgMoney = null; // 处理前金额
	private Map<String, Map<String, UFDouble>> afterPsgMoney = null; // 处理后金额
	private String orgCode;// 查询组织
	private String orgName = null;
	private String orgId = null;
	private String period;// 查询期间
	Map<String, Map<String, String>> middleTableData = new HashMap<String, Map<String, String>>();// 中间表数
	private SocialInsuranceAllMaintain siaMaintain = NCLocator.getInstance().lookup(SocialInsuranceAllMaintain.class);

	public ServiceChargeAllocationUI() {
		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 });// 添加按钮
	}

	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 = "60H20105";
			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) {
					ServiceChargeAllocationUI.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) {
					ServiceChargeAllocationUI.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 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, "提示", "凭证已生成");
			}
		} catch (Exception e) {
			MessageDialog.showHintDlg(this, "提示", e.getMessage());
		}
	}

	/**
	 * 数据处理，表格渲染
	 * 
	 * @param dataList
	 * @param title
	 * @param ListMap
	 */
	private Map<String, UFDouble> addTableToList(String str, List<Object[]> dataList, String title, List<Map<String, String>> ListMap) {
		dataList.add(new Object[] { title });
		Map<String, UFDouble> sumMap = new HashMap<String, UFDouble>();
		// 合计部分
		UFDouble SumStaff = new UFDouble(0.00, 2);
		UFDouble SumOrg = new UFDouble(0.00, 2);
		// 小计部分
		UFDouble subtotalStaff = new UFDouble(0.00, 2);
		UFDouble subtotalOrg = new UFDouble(0.00, 2);
		if ("表一：个人承担".equals(title)) {
			dataList.add(subheading);
			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");
				String combinedField = title + clerkcode + clerkname;
				// 取中间表数据
				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");
				}
				UFDouble basicsMoney = nvl(basicssum, 2);
				UFDouble staffMoney = nvl(staffsum, 2);
				UFDouble 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);
					}
				}
				// 统计合计
				SumStaff = SumStaff.add(staffMoney);
				SumOrg = SumOrg.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 });
					// 统计小计
					subtotalStaff = subtotalStaff.add(staffMoney);
					subtotalOrg = subtotalOrg.add(orgMoney);
					if (i + 1 == ListMap.size()) {
						// 第一行和最后一行输出小计
						// 输出小计
						dataList.add(new Object[] { "小计", null, null, null, subtotalStaff,subtotalOrg });
						subtotalStaff = new UFDouble(0.00, 2);
						subtotalOrg = new UFDouble(0.00, 2);
					} else if (!orgName.equals(ListMap.get(i + 1).get("orgname"))) {
						// 如果当前行组织不等于下一行组织输出小计
						// 输出小计
						dataList.add(new Object[] { "小计", null, null, null, subtotalStaff,subtotalOrg });
						subtotalStaff = new UFDouble(0.00, 2);
						subtotalOrg = new UFDouble(0.00, 2);
					}
				} else {
					// 输出行数据
					dataList.add(new Object[] { i + 1, clerkcode, clerkname, basicsMoney, staffMoney, orgMoney, mark, str });
				}
			}
			// 输出合计
			dataList.add(new Object[] { "合计", null, null, null, SumStaff, SumOrg });
		} else {
			dataList.add(subheadings);
			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");
				String combinedField = null;
				if (null == orgName) {
					combinedField = title + clerkcode + clerkname;
				} else {
					combinedField = title + orgName + clerkcode + clerkname;
				}
				// 取中间表数据
				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");
				}
				UFDouble basicsMoney = nvl(basicssum, 2);
				UFDouble staffMoney = nvl(staffsum, 2);
				UFDouble 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);
					}
				}
				// 统计合计
				SumOrg = SumOrg.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, orgMoney, mark, null, str + orgName });
					// 统计小计
					subtotalOrg = subtotalOrg.add(orgMoney);
					if (i + 1 == ListMap.size()) {
						// 第一行和最后一行输出小计
						// 输出小计
						dataList.add(new Object[] { "小计", null, null, null, subtotalOrg });
						subtotalStaff = new UFDouble(0.00, 2);
						subtotalOrg = new UFDouble(0.00, 2);
					} else if (!orgName.equals(ListMap.get(i + 1).get("orgname"))) {
						// 如果当前行组织不等于下一行组织输出小计
						// 输出小计
						dataList.add(new Object[] { "小计", null, null, null, subtotalOrg });
						subtotalStaff = new UFDouble(0.00, 2);
						subtotalOrg = new UFDouble(0.00, 2);
					}
				} else {
					// 输出行数据
					dataList.add(new Object[] { i + 1, clerkcode, clerkname, basicsMoney, orgMoney, mark, null, str });
				}
			}
			// 输出合计
			dataList.add(new Object[] { "合计", null, null, null, SumOrg });
		}
		sumMap.put("staff", SumStaff);
		sumMap.put("org", SumOrg);
		return sumMap;
	}

	/**
	 * 表格渲染
	 * 
	 * @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 < 6; 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);
		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));
		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");// 公司承担公司部分
		Map<String, String> TableTenMap = queryTableTen(orgCode, period);
		// UFDouble TableTenStaff = nvl(TableTenMap.get("so_staff_sum"), 2);//个人实际缴纳数
		// UFDouble TableTenOrg = nvl(TableTenMap.get("so_org_sum"), 2);//公司实际缴纳数
		// 社保账单实际交纳数 = 个人实际缴纳数+公司实际缴纳数
		// UFDouble actualSum = TableTenStaff.add(TableTenOrg);
		UFDouble actualSum = nvl(TableTenMap.get("agency_money"), 2);
		// 服务费分摊表金额 = 个人承担个人、公司部分+外部公司承担个人、公司部分+部门承担个人、公司部分+公司承担个人、公司部分
		UFDouble sbgjjfillSum = tableOneStaff.add(tableOneOrg).add(tableTwoStaff).add(tableTwoOrg).add(tableThreeStaff).add(tableThreeOrg).add(tableFourStaff).add(tableFourOrg);
		// 差额= SIBCO账单支付数-服务费分摊表金额
		UFDouble difference = actualSum.sub(sbgjjfillSum);
		dataList.set(0, new Object[] { "汇总信息" });
		dataList.set(1, new Object[] { "SIBCO账单支付数", actualSum, "服务费分摊表金额", sbgjjfillSum, "差额", difference });
		dataList.set(2, new Object[] { "个人承担", "公司部分", tableOneOrg, "外部公司承担", "公司部分", tableTwoOrg, "部门承担", "公司部分", tableThreeOrg });
		dataList.set(3, new Object[] { "个人承担", "个人部分", tableOneStaff, "外部公司承担", "个人部分", null, "部门承担", "个人部分", null });
		dataList.set(4, new Object[] { "公司承担  ", "公司部分", tableFourOrg });
		dataList.set(5, new Object[] { "公司承担  ", "个人部分", tableFourStaff });
		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().setSelectionMode(1); 2025-03-21
//		tablepanel.getTable().setAutoResizeMode(0);
		tablepanel.getTable().setColumnWidth(new int[] { 300, 160, 160, 160, 160, 160, 160, 160, 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);

				// 从8行开始，第7列值变成白色
				if (row >= 8 && 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 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(" clerkcode,");
		sql.append(" clerkname,");
		sql.append(" CAST(endowment_base AS VARCHAR2 ( 50 ) ) AS basicssum,");
		sql.append(" CAST(NULL AS VARCHAR2 ( 50 ) ) AS staffsum,");
		sql.append(" CAST(NULL AS VARCHAR2 ( 50 ) ) AS orgsum,");
		sql.append(" NULL AS mark");
		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)");
		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,");
		sql.append(" clerkname,");
		sql.append(" CAST(endowment_base AS VARCHAR2 ( 50 ) ) AS basicssum,");
		sql.append(" CAST(NULL AS VARCHAR2 ( 50 ) ) AS staffsum,");
		sql.append(" CAST(AGENCY_MONEY AS VARCHAR2 ( 50 ) ) AS orgsum,");
		sql.append(" 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,");
		sql.append(" clerkname,");
		sql.append(" CAST(endowment_base AS VARCHAR2 ( 50 ) ) AS basicssum,");
		sql.append(" CAST(NULL AS VARCHAR2 ( 50 ) ) AS staffsum,");
		sql.append(" CAST(AGENCY_MONEY AS VARCHAR2 ( 50 ) ) AS orgsum,");
		sql.append(" mark");
		sql.append(" FROM");
		sql.append(" (SELECT T.Endowment_Base,T.CLERKCODE,T.CLERKNAME,T.so_org_sum,T.so_staff_sum,T.ORGCODE,T.PAY_MONTH,");
		sql.append(" T.AGENCY_MONEY,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 = '残保金人员' )");
		sql.append(" UNION ALL");
		sql.append(" SELECT t1.Endowment_Base,t1.CLERKCODE,t1.CLERKNAME,t1.so_org_sum,t1.so_staff_sum,T1.ORGCODE,");
		sql.append(" t1.PAY_MONTH,T1.AGENCY_MONEY,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 = '" + 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(" costorgname AS orgname,");
		sql.append(" clerkcode,");
		sql.append(" clerkname,");
		sql.append(" CAST(NULL AS VARCHAR2 ( 50 ) ) AS basicssum,");
		sql.append(" CAST(NULL AS VARCHAR2 ( 50 ) ) AS staffsum,");
		sql.append(" CAST(AGENCY_MONEY AS VARCHAR2 ( 50 ) ) AS orgsum,");
		sql.append(" NULL AS mark");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" t.CLERKCODE, T1.CLERKNAME, t.ym, sum( nvl( t.VALUE, 0 ) ) AS sum_per_cost,");
		sql.append(" T13.Name AS costorgname, T13.Name AS salocation, to_number( t1.AGENCY_MONEY ) AS AGENCY_MONEY");
		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(" LEFT JOIN (SELECT t12.CLERK_CODE, t12.NC_PK_POST FROM nc6337.monthly_position_gjj t12");
		sql.append(" WHERE t12.month = to_char( last_day( to_date( '" + period + "', 'yyyy-mm' ) ), 'yyyy-mm-dd' ) ) 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(" WHERE t.key IN ( '社保个人合计', '费用调整社保', '社保个人扣款', '费用调整社保T' )");
		sql.append(" AND t.ym = '" + period + "' || '-01'  AND t1.ORGCODE = '" + orgCode + "' ");
		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(" AND t1.CLERKNAME <> '李旭光'  AND t14.PK_POST NOT IN ( SELECT T3.PK_POST FROM NC6337.om_post t3 WHERE T3.postname = '残保金人员' ) ");
		sql.append(" GROUP BY t.CLERKCODE, T1.CLERKNAME, t.ym, t1.AGENCY_MONEY, T13.Name UNION ALL");
		sql.append(" SELECT t.WORKERCODE AS CLERKCODE, t1.CLERKNAME, t.WA_PERIOD AS ym, 0 AS sum_per_cost, T6.NAME AS costorgname, '上海天华' AS salocation,");
		sql.append(" round( nvl( t1.AGENCY_MONEY, 0 ) * nvl( t.perc, 0 ), 3 ) AS AGENCY_MONEY ");
		sql.append(" FROM nc6337.v_hr_allocationratio_gjjshareF t");
		sql.append(" LEFT JOIN nc6337.V_SUM_TB_HR_SOCIAL_SECURITY t1 ON t1.CLERKCODE = t.WORKERCODE ");
		sql.append(" 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 t.WA_PERIOD = '" + period + "' || '-01'  AND t1.CLERKNAME IS NOT NULL  AND t1.ORGCODE = '" + orgCode + "' UNION ALL");
		sql.append(" SELECT t1.CLERKCODE, t1.CLERKNAME, t1.PAY_MONTH || '-01' AS ym, 0 AS sum_per_cost, T1.PAY_SOS_ORG AS costorgname,");
		sql.append(" '上海天华' AS salocation, to_number( t1.AGENCY_MONEY ) AS AGENCY_MONEY ");
		sql.append(" FROM NC6337.V_SUM_TB_HR_SOCIAL_SECURITY_D t1 ");
		sql.append(" WHERE t1.MARK IN ( '资质人员', '上海公司承担' )  AND t1.PAY_MONTH = '" + period + "'  AND t1.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 Map<String, String> queryTableTen(String orgCode, String period) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT");
		sql.append(" *");
		sql.append(" FROM");
		sql.append(" NC6337.V_SUM_TB_HR_SOCIAL_SECURITY_D T");
		sql.append(" WHERE");
		sql.append(" T.CLERKNAME = '总数' AND T.PAY_MONTH = '" + period + "' 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("so_staff_sum", null);
			map.put("so_org_sum", null);
			map.put("agency_money", 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 insert() {
		try {
			String orgName = getOrgPanel().getRefModel().getRefNameValue();
			// 0表示有实际新增，而不是点击弹框后关闭了
			if (new ServiceChargeAllInsertDiaLog(orgCode, orgName, period).showModal() == 0) {
				MessageDialog.showHintDlg(this, "提示", "新增成功！");
			}
		} catch (Exception e) {
			MessageDialog.showHintDlg(this, "提示", e.getMessage());
		}
	}

	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 {
				int tableNumber = 0;
				for (int i = 0; i < rows.length; i++) {
					String value = ValueUtils.getString(table.getTable().getValueAt(rows[i], 7));
					if (value == null) {
						MessageDialog.showHintDlg(this, "提示", "请选择正确的行修改！");
						return;
					}else {
						int index = value.indexOf("-");
						int number = Integer.parseInt(value.substring(0, index));
						if(i == 0) {
							tableNumber = number;
						}else {
							if(tableNumber != number) {
								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 ServiceChargeAllUpdateDialog(selectedData, orgCode, period).showModal() == 0) {
				// 刷新
				tableProcessing();
				MessageDialog.showHintDlg(this, "提示", "修改成功！");
			}
		} catch (Exception e) {
			MessageDialog.showHintDlg(this, "提示", e.getMessage());
		}
	}

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

	/**
	 * 组装凭证借贷金额
	 * 
	 * @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 objbmgs = tablepane.getTable().getValueAt(2, 8);
		// 表四 公司承担-公司部分合计
		Object objgsgs = tablepane.getTable().getValueAt(4, 2);
		// 服务费分摊表金额
		Object objsibco = tablepane.getTable().getValueAt(1, 3);

		/** 借方：其他应收款/个人往来/个人明细 **/
		// 金额=表一(由个人承担) 公司部门金额合计 K10
		UFDouble grcmpamount = objgs == null ? UFDouble.ZERO_DBL : new UFDouble(objgs.toString());

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

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

		/** 借方：管理费用/办公费/部门：其他虚拟财务 **/
		UFDouble cmpamount = objgsgs == null ? UFDouble.ZERO_DBL : new UFDouble(objgsgs.toString());
		// 金额
		// UFDouble jscmpamout = cmpamount.div(new UFDouble("1.05")).sub(grcmpamount.multiply(new UFDouble("1.05"))).sub(bmcmpamount.div(new UFDouble("1.05")).multiply(new UFDouble("0.05")))
		// .sub(bcmpamount.div(new UFDouble("1.05")).multiply(new UFDouble("0.05"))).setScale(2, UFDouble.ROUND_HALF_UP);
		UFDouble jscmpamout = cmpamount.add(bmcmpamount);

		/** 贷方: 应付账款/实际应付款/上海国际企业商务咨询有限公司 **/
		// 金额=服务费分摊表金额
		UFDouble jsibcomount = objsibco == null ? UFDouble.ZERO_DBL : new UFDouble(objsibco.toString());

		/** 借方：应交税费/应交增值税/进项税额/认证抵扣 **/
		// 金额=贷方金额-借方金额
		// UFDouble yjsamount = jsibcomount.sub(grcmpamount.add(bmcmpamount).add(bcmpamount).add(jscmpamout));

		map.put("管理费用/办公费", jscmpamout);
		map.put("其他应收款/个人往来", grcmpamount);
		map.put("应付账款/预估成本/办公费", bmcmpamount);
		map.put("其他应收款/单位往来", bcmpamount);
		// map.put("应交税费", yjsamount);
		map.put("预付账款/贷方", jsibcomount);
		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);// 会计年度      2025-03-13
		String monthperiod = period.substring(5, 7);// 会计月份    2025-03-13
		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 = "660209";// 管理费用/办公费
				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 = "122102";// 其他应收款/个人往来
				debitamount = entry.getValue();// 借方发生额
				if (debitamount.doubleValue() != 0) {
					pk_accasoa = tranKm(km_code, pk_accountGlbook);// 科目
					// 查询表一员工明细
					List<String> ycode = querygcode(orgCode, period);
					for (int i = 0; i < ycode.size(); i++) {
						DetailVO itemVO = new DetailVO();
						getDetailvo(itemVO, pk_accasoa, creditamount, debitamount, voucher, "服务分摊费");
						// 辅助核算
						AssVO[] assvos = getAss(pk_accasoa, "0002", psndocCode(ycode.get(i)), 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 = "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 + "月 人事代理服务费");
					// 辅助核算
					AssVO[] assvos1 = getAss(pk_accasoa, "0001", "其他-虚拟（财务成本归结）", pk_org);// 部门：其他虚拟财务
					AssVO[] assvos = getAss(pk_accasoa, "0010", "PM201601130001", pk_org);// 项目：其他
					AssVO[] assvos2 = getAss(pk_accasoa, "0043", "99", pk_org);// 项目专业：不涉及
					ArrayList<AssVO> arrassvo = new ArrayList<AssVO>();
					arrassvo.add(assvos[0]);
					arrassvo.add(assvos1[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= "2221010101";//应交税费/应交增值税/进项税额/认证抵扣
			// debitamount = entry.getValue();//借方发生额
			// pk_accasoa= tranKm(km_code, pk_accountGlbook);//科目
			// DetailVO itemVO = new DetailVO();
			// getDetailvo(itemVO, pk_accasoa, creditamount, debitamount, voucher, period+"人事代理服务费");
			// 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, "05", "11", pk_org);// 待摊事项：人事代理费摊销
					// AssVO[] assvos = getAss(pk_accasoa, "0004","G000371",pk_org);//客商：上海国际企业商务咨询服务有限公司
					// AssVO[] assvos1 = getAss(pk_accasoa, "X01","1122",pk_org);//现金流
					ArrayList<AssVO> arrassvo = new ArrayList<AssVO>();
					arrassvo.add(assvos[0]);
					// arrassvo.add(assvos1[0]);
					itemVO.setAss((AssVO[]) arrassvo.toArray(new AssVO[0]));
					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.setDetailindex(Integer.parseInt(detailno));
		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 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;
	}
}
