package nc.ui.hr.baod_orders.view;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.swing.JProgressBar;

import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.desktop.ui.WorkbenchEnvironment;
import nc.hr.utils.SpecialDataUtil;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.ArrayListProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.log.NcLog;
import nc.pubitf.rbac.IFunctionPermissionPubService;
import nc.ui.pub.ButtonObject;
import nc.ui.pub.SeparatorButtonObject;
import nc.ui.pub.ToftPanel;
import nc.ui.pub.beans.MessageDialog;
import nc.ui.pub.beans.UICheckBox;
import nc.ui.pub.beans.UIComboBox;
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.UITextField;
import nc.ui.pub.beans.ValueChangedEvent;
import nc.ui.pub.beans.ValueChangedListener;
import nc.ui.pub.beans.table.NCTableModel;
import nc.ui.resa.refmodel.CostCenterTreeRefModel;
import nc.vo.arap.transaction.SystemInfoVO;
import nc.vo.fipub.exception.ExceptionHandler;
import nc.vo.pub.BusinessException;
import nc.vo.pub.ValueObject;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.pubapp.pattern.pub.MathTool;
import nc.vo.uap.rbac.profile.FunctionPermProfileManager;
import nc.vo.uap.rbac.profile.IFunctionPermProfile;

/**
 * 全员收入统计表
 * @author Yaoyu
 *
 */
@SuppressWarnings("deprecation")
public class IncomeStatisticalUI extends ToftPanel {
	
	private static final long serialVersionUID = -3038845740036357554L;
	private ButtonObject bt_recalcula = new ButtonObject("查询", "", 2, "recalcula");
	private ButtonObject bt_output = new ButtonObject("导出", "", 2, "output");
	private SeparatorButtonObject separatorBtn = new SeparatorButtonObject();
	private UIPanel ivjUIPanel0 = null;
	private UIPanel ivjUIPanel2 = null;
	private UIPanel ivjUIPanel4 = null;
	private UIPanel ivjUIPanel45 = null;
	private UIRefPane ivjOrgPanel = null;
	private UIRefPane ivjcostcpanel = null;
	private UIRefPane ivjperiodpanel = null;
	private UIRefPane ivjperiodpanels = null;
	private UITablePane ivjTablePanel = null;
	private UILabel ivjOrgLabel = null;
	private UILabel ivjperiodLabel = null;
	private UILabel ivjperiodLabels = null;
	private UITextField ivjCodeText = null;
	private UITextField ivjNameText = null;
	private UILabel ivjCodeLabel = null;
	private UILabel ivjNameLabel = null;
	private UILabel ivjPostLabel = null;
	private UIRefPane ivjPostPane = null;
	private IUAPQueryBS IUAPQueryBS = (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class);
	private JProgressBar pb;
	private SimpleDateFormat inputFormat = new  SimpleDateFormat("yyyy-MM");
	public IncomeStatisticalUI() {
		initialize();
	}

	/**
	 * 初始化
	 */
	private void initialize() {
		setLayout(new BorderLayout());
		add(getUIPanel0(), BorderLayout.NORTH);
		add(getUIPanel2(), BorderLayout.CENTER);
		add(getUIPanel4(), BorderLayout.SOUTH);
		setButtons(new ButtonObject[] { this.bt_recalcula, this.separatorBtn,this.bt_output});//添加按钮
	}

	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 = "60H10110";
			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) {
					IncomeStatisticalUI.this.initialize();
				}
			});
		}
		return this.ivjOrgPanel;
	}

	private UILabel getperiodclabel() {
		if (this.ivjperiodLabel == null) {
			this.ivjperiodLabel = new UILabel();
			this.ivjperiodLabel.setName("startPeriod");
			this.ivjperiodLabel.setText("开始期间");
		}
		return this.ivjperiodLabel;
	}
	
	private UIRefPane getperiodpanel() {
		if (this.ivjperiodpanel == null) {
			this.ivjperiodpanel = new UIRefPane();
			this.ivjperiodpanel.setName("startPeriod");
			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) {
					IncomeStatisticalUI.this.initialize();
				}
			});
		}
		return this.ivjperiodpanel;
	}
	private UILabel getperiodclabels() {
		if (this.ivjperiodLabels == null) {
			this.ivjperiodLabels = new UILabel();
			this.ivjperiodLabels.setName("endPeriod");
			this.ivjperiodLabels.setText("结束期间");
		}
		return this.ivjperiodLabels;
	}
	
	private UIRefPane getperiodpanels() {
		if (this.ivjperiodpanels == null) {
			this.ivjperiodpanels = new UIRefPane();
			this.ivjperiodpanels.setName("endPeriod");
			this.ivjperiodpanels.setRefNodeName("会计期间档案");
			this.ivjperiodpanels.setBounds(new Rectangle(100, 20));
			this.ivjperiodpanels.setPreferredSize(new Dimension(170, 20));
			this.ivjperiodpanels.addValueChangedListener(new ValueChangedListener() {

				public void valueChanged(ValueChangedEvent e) {
					IncomeStatisticalUI.this.initialize();
				}
			});
		}
		return this.ivjperiodpanels;
	}
	
	private Component getCodeLabel() {
		if (this.ivjCodeLabel == null) {
			this.ivjCodeLabel = new UILabel();
			this.ivjCodeLabel.setName("code");
			this.ivjCodeLabel.setText("员工号");
		}
		return this.ivjCodeLabel;
	}
	
	private UITextField getCodeText() {
		if (this.ivjCodeText == null) {
			this.ivjCodeText = new UITextField();
			this.ivjCodeText.setBounds(new Rectangle(100, 20));
			this.ivjCodeText.setPreferredSize(new Dimension(170, 20));
		}
		return this.ivjCodeText;
	}
	
	private UILabel getNameLabel() {
		if (this.ivjNameLabel == null) {
			this.ivjNameLabel = new UILabel();
			this.ivjNameLabel.setName("name");
			this.ivjNameLabel.setText("员工姓名");
		}
		return this.ivjNameLabel;
	}
	

	private UITextField getNameText() {
		if (this.ivjNameText == null) {
			this.ivjNameText = new UITextField();
			this.ivjNameText.setBounds(new Rectangle(100, 20));
			this.ivjNameText.setPreferredSize(new Dimension(170, 20));
		}
		return this.ivjNameText;
	}
	
	private UILabel getPostLabel() {
		if (this.ivjPostLabel == null) {
			this.ivjPostLabel = new UILabel();
			this.ivjPostLabel.setName("postLabel");
			this.ivjPostLabel.setText("激励类型");
		}
		return this.ivjPostLabel;
	}
	
	private UIRefPane getPostPane() {
		if (this.ivjPostPane == null) {
			this.ivjPostPane = new UIRefPane();
			this.ivjPostPane.setName("postPane");
			this.ivjPostPane.setRefNodeName("岗位属性(自定义档案)");
			this.ivjPostPane.setBounds(new Rectangle(100, 20));
			this.ivjPostPane.setPreferredSize(new Dimension(170, 20));
			this.ivjPostPane.setMultiSelectedEnabled(true);//设置可以多选
			this.ivjPostPane.addValueChangedListener(new ValueChangedListener() {
				public void valueChanged(ValueChangedEvent e) {
					IncomeStatisticalUI.this.initialize();
				}
			});
		}
		return this.ivjPostPane;
	}
	

	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;
	}

	public String getTitle() {
		return "全员收入统计表";
	}

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

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

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

	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);
	}

	
	public  void onButtonClicked(ButtonObject bo) {
		try {
			//停止编辑;
			getPostPane().stopEditing();
			getOrgPanel().stopEditing();
			getperiodpanel().stopEditing();
			getperiodpanels().stopEditing();
			//获取查询条件
			String codeType[] = getPostPane().getRefModel().getRefCodeValues();
			String code[] = getOrgPanel().getRefModel().getRefCodeValues();
			String startPeriod = null;
			String endPeriod = null;
			Vector startPeriodData = getperiodpanel().getRefModel().getSelectedData();
			if (startPeriodData != null && startPeriodData.size() > 0) {
				Vector v = (Vector) startPeriodData.get(0);
				startPeriod = v.get(0).toString();
			}
			Vector endPeriodData = getperiodpanels().getRefModel().getSelectedData();
			if (endPeriodData != null && endPeriodData.size() > 0) {
				Vector v = (Vector) endPeriodData.get(0);
				endPeriod = v.get(0).toString();
			}
			
			if (bo == this.bt_recalcula) {
				String psncoed = getCodeText().getText();
				String psnname = getNameText().getText();
				if(code == null || startPeriod == null || endPeriod == null) {
					ExceptionUtils.wrappBusinessException("财务组织、开始期间、结束期间必须选择，请选择后再操作！");
				}
				
				StringBuffer codein = new StringBuffer();
				codein.append("in (");
				for (int i = 0;i < code.length; i++) {
					codein.append("'"+code[i]+"',");
				}
				codein.deleteCharAt(codein.length() - 1); // 删除最后的逗号  
				codein.append(")"); 
				
				StringBuffer codeTypein = new StringBuffer();
				if(codeType != null) {
					String userCode = InvocationInfoProxy.getInstance().getUserCode();
					String pk_defdoc = queryDftDocUser(userCode);
						
					codeTypein.append("defname in (");
					for (int i = 0;i < codeType.length; i++) {
						//激励类型存在如C1编码，截取第一位用于后续判断
						String type = codeType[i].substring(0,1);
						//如果当前登录人在档案中有维护,并且激励类型有A,B,C,F其中任意一个选项，表示此次为查询核心人员信息，需将A,B,C,F类型数据全部查出
						if(pk_defdoc != null && ("A".equals(type) || "B".equals(type) || "C".equals(type) || "F".equals(type))) {
							//清空拼接的sql信息，重新拼接
							codeTypein.setLength(0);
							//codeTypein.append("(bd_defdoc.code like 'A%' or bd_defdoc.code like 'B%' or bd_defdoc.code like 'C%' or bd_defdoc.code like 'F%',");
							codeTypein.append("(defname like 'A%' or defname like 'B%' or defname like 'C%' or defname like 'F%',");
							break;
						}
						codeTypein.append("'"+codeType[i]+"',");
					}
					codeTypein.deleteCharAt(codeTypein.length() - 1); // 删除最后的逗号  
					codeTypein.append(")"); 
				}
				calcula(codein.toString(),startPeriod,endPeriod,psncoed,psnname,codeTypein.toString());
			}
			if (bo == this.bt_output) {
				onoutput();
			}
		} catch (Exception e) {
			MessageDialog.showHintDlg(this, "提示", e.getMessage());
		}
		
		
		
        
	}

	


	private void calcula(String codein,String startPeriod,String endPeriod,String psncode,String psnname,String codeTypein) throws Exception {
		Map<String,String> map = getDateIntervalsql(inputFormat.parse(startPeriod), inputFormat.parse(endPeriod));
		UITablePane tablepanel = getTablePanel();
		NCTableModel model = new NCTableModel();
		String[] m_sTitle = {"行数","发放月数","员工号","姓名","成本归属公司","成本归属部门","岗位","激励类型","主职/兼职","该岗位起始日期","该岗位结束日期",
				"收入总计","收入:固定部分","收入:浮动部分","固浮比(%)","部门承担","预发待扣","公司补贴","资质补贴及审图资格补贴","设计奖金","市场费奖金+重点项目市场费奖金","部级、省市获奖项目设计奖励","本期所级管理团队奖金（不含本期已发放管理预发奖金，含本期所级缓发奖金）",
				"大客户经理奖金","所级人员保底补差金额","设计人员保底补差金额","技术管理奖金","管理预算相关补贴","总师、职能人员奖金","公司级管理者计算奖金",
				"公司级管理者保底补差","分红"};
		Vector<Object> vTitle = convertovector(m_sTitle);
		Vector<Vector<Object>> vresult = new Vector<Vector<Object>>();
		ArrayList<Object> list = queryData(codein, startPeriod, endPeriod, map,psncode,psnname,codeTypein);
		UFDouble totalsrzj = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalgdbf = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalfdbf = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalgfb = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalbmcd = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalyfdk = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totaldesignbonus = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalmarketbonus = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalawardsbonus = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalgsbt = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalzzbt = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalmanagementbonus = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalservicebonus = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalguaranteebonus1 = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalguaranteebonus2 = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalspecialbonus = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalallowancebonus = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalfunction_bonus = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalmanage_jsbonus = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalmanage_bdamount = new UFDouble(UFDouble.ZERO_DBL);
		UFDouble totalshare_bonus = new UFDouble(UFDouble.ZERO_DBL);
		for (int i = 0; i < list.size(); i++) {
			
			Vector<Object> v = new Vector<Object>();
			Object[] objects = (Object[]) list.get(i);
			v.add(i+1);
			for (int j = 0; j < objects.length; j++) {
				//发放月数为0赋值空
				if(j == 0 && objects[j] != null) {
					if(Integer.parseInt(objects[j].toString()) == 0) {
						objects[j] = null;
					}
				}
				//金额为0赋值空，不为了保留两位小数
				if(j > 9 && objects[j] != null) {
					UFDouble data = new UFDouble(String.valueOf(objects[j]));
					if(MathTool.isZero(data)) {
						objects[j] = null;
					}else {
						objects[j] = data.setScale(2, UFDouble.ROUND_HALF_UP);
					}
				}
				v.add(objects[j]);
				//计算收入和固浮比
				if(j == 9) {
					UFDouble srzj = new UFDouble(UFDouble.ZERO_DBL);
					UFDouble gdbf = new UFDouble(UFDouble.ZERO_DBL);
					UFDouble fdbf = new UFDouble(UFDouble.ZERO_DBL);
					UFDouble gfb = new UFDouble(UFDouble.ZERO_DBL);
					
					
					UFDouble bmcd = new UFDouble(objects[10] == null ? "0.00" : String.valueOf(objects[10]));
					UFDouble yfdk = new UFDouble(objects[11] == null ? "0.00" : String.valueOf(objects[11]));
					UFDouble gsbt = new UFDouble(objects[12] == null ? "0.00" : String.valueOf(objects[12]));
					UFDouble zzbt = new UFDouble(objects[13] == null ? "0.00" : String.valueOf(objects[13]));
					
					UFDouble designbonus = new UFDouble(objects[14] == null ? "0.00" : String.valueOf(objects[14]));
					UFDouble marketbonus = new UFDouble(objects[15] == null ? "0.00" : String.valueOf(objects[15]));
					UFDouble awardsbonus = new UFDouble(objects[16] == null ? "0.00" : String.valueOf(objects[16]));
					UFDouble managementbonus = new UFDouble(objects[17] == null ? "0.00" : String.valueOf(objects[17]));
					UFDouble servicebonus = new UFDouble(objects[18] == null ? "0.00" : String.valueOf(objects[18]));
					UFDouble guaranteebonus1 = new UFDouble(objects[19] == null ? "0.00" : String.valueOf(objects[19]));
					UFDouble guaranteebonus2 = new UFDouble(objects[20] == null ? "0.00" : String.valueOf(objects[20]));
					UFDouble specialbonus = new UFDouble(objects[21] == null ? "0.00" : String.valueOf(objects[21]));
					UFDouble allowancebonus = new UFDouble(objects[22] == null ? "0.00" : String.valueOf(objects[22]));
					UFDouble function_bonus = new UFDouble(objects[23] == null ? "0.00" : String.valueOf(objects[23]));
					UFDouble manage_jsbonus = new UFDouble(objects[24] == null ? "0.00" : String.valueOf(objects[24]));
					UFDouble manage_bdamount = new UFDouble(objects[25] == null ? "0.00" : String.valueOf(objects[25]));
					UFDouble share_bonus = new UFDouble(objects[26] == null ? "0.00" : String.valueOf(objects[26]));
					//固定部分 = 部门承担+预发代扣+公司补贴+资质补贴及审图资格补贴
					gdbf = bmcd.add(yfdk).add(gsbt).add(zzbt);
					//浮动部分 =设计奖金——分红相加
					fdbf = designbonus.add(marketbonus).add(awardsbonus).add(managementbonus).add(servicebonus).add(guaranteebonus1)
							.add(guaranteebonus2).add(specialbonus).add(allowancebonus).add(function_bonus).add(manage_jsbonus)
							.add(manage_bdamount).add(share_bonus);
					//收入总计=固定部分+浮动部分
					srzj = gdbf.add(fdbf);
					if(!MathTool.isZero(fdbf) && !MathTool.isZero(gdbf)) {
						gfb = fdbf.div(gdbf);
					}
					
					//收入等于0赋值空，不等于保留两位小数，固浮比转换成百分比
					if(MathTool.isZero(srzj)) {
						v.add(null);
						v.add(null);
						v.add(null);
						v.add(null);
					}else {
						DecimalFormat df = new DecimalFormat("0.00");
						String result = df.format(gfb.multiply(100).doubleValue());
						v.add(srzj.setScale(2, UFDouble.ROUND_HALF_UP));
						v.add(gdbf.setScale(2, UFDouble.ROUND_HALF_UP));
						v.add(fdbf.setScale(2, UFDouble.ROUND_HALF_UP));
						v.add(result+"%");	
					}
					
					//将所有金额合计
					totalsrzj = totalsrzj.add(srzj);  
					totalgdbf = totalgdbf.add(gdbf);  
					totalfdbf = totalfdbf.add(fdbf);  
					totalgfb = totalgfb.add(gfb);
					totalbmcd = totalbmcd.add(bmcd);
					totalyfdk = totalyfdk.add(yfdk);  
					totalgsbt = totalgsbt.add(gsbt);  
					totalzzbt = totalzzbt.add(zzbt);  
					totaldesignbonus = totaldesignbonus.add(designbonus);  
					totalmarketbonus = totalmarketbonus.add(marketbonus);  
					totalawardsbonus = totalawardsbonus.add(awardsbonus);  
					totalmanagementbonus = totalmanagementbonus.add(managementbonus);  
					totalservicebonus = totalservicebonus.add(servicebonus);  
					totalguaranteebonus1 = totalguaranteebonus1.add(guaranteebonus1);  
					totalguaranteebonus2 = totalguaranteebonus2.add(guaranteebonus2);  
					totalspecialbonus = totalspecialbonus.add(specialbonus);  
					totalallowancebonus = totalallowancebonus.add(allowancebonus);  
					totalfunction_bonus = totalfunction_bonus.add(function_bonus);  
					totalmanage_jsbonus = totalmanage_jsbonus.add(manage_jsbonus);  
					totalmanage_bdamount = totalmanage_bdamount.add(manage_bdamount);  
					totalshare_bonus = totalshare_bonus.add(share_bonus);
				}
			}
			vresult.add(v);
		}
		
		// 创建用于存储合计统计数据的Vector对象
		Vector<Object> vTotal = new Vector<Object>();
		vTotal.add("合计");

		// 将合计值添加到合计统计的Vector对象中
		vTotal.add(null); // 第一列留空
		vTotal.add(null); // 第二列留空
		vTotal.add(null); // 第三列留空
		vTotal.add(null); // 第四列留空
		vTotal.add(null); // 第五列留空
		vTotal.add(null); // 第六列留空
		vTotal.add(null); // 第七列留空
		vTotal.add(null); // 第八列留空
		vTotal.add(null); // 第九列留空
		vTotal.add(null); // 第十列留空
		vTotal.add(totalsrzj.setScale(2, UFDouble.ROUND_HALF_UP)); // 第十一列为收入总计合计值
		vTotal.add(totalgdbf.setScale(2, UFDouble.ROUND_HALF_UP)); // 第十二列为收入:固定部分合计值
		vTotal.add(totalfdbf.setScale(2, UFDouble.ROUND_HALF_UP)); // 第十三列为收入:浮动部分合计值
		DecimalFormat df = new DecimalFormat("0.00");
		String result = df.format(totalgfb.multiply(100).doubleValue());
		vTotal.add(result+"%");	//第十四列为固浮比
		vTotal.add(totalbmcd.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totalyfdk.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totalgsbt.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totalzzbt.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totaldesignbonus.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totalmarketbonus.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totalawardsbonus.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totalmanagementbonus.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totalservicebonus.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totalguaranteebonus1.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totalguaranteebonus2.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totalspecialbonus.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totalallowancebonus.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totalfunction_bonus.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totalmanage_jsbonus.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totalmanage_bdamount.setScale(2, UFDouble.ROUND_HALF_UP));
		vTotal.add(totalshare_bonus.setScale(2, UFDouble.ROUND_HALF_UP));
		// 将合计统计的Vector对象添加到原有数据集合中
		vresult.add(vTotal);
		model.setDataVector(vresult, vTitle);
		tablepanel.getTable().setModel(model);
		tablepanel.getTable().setSelectionMode(1);
		tablepanel.getTable().setAutoResizeMode(0);
		tablepanel.getTable().setColumnWidth(new int[] { 50,50,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150,150 });
	}
	
	private void onoutput() {
		CostOutputDialog costdig = new CostOutputDialog(this, getTablePanel());
		if (costdig.showModal() == 2) {
			return;
		}
	}
	public 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;
	}
	
	
//	public static String getDateIntervalsql(Date startDate,Date endDate){
//
//		// 创建起始日期的 Calendar 实例  
//        Calendar startCal = Calendar.getInstance();  
//        startCal.setTime(startDate);  
//  
//        // 创建用于迭代的 Calendar 实例，从起始日期开始  
//        Calendar currentCal = Calendar.getInstance();  
//        currentCal.setTime(startDate);  
//  
//        // 用于构建 SQL IN 子句的 StringBuffer  
//        StringBuffer sqlin = new StringBuffer();
//        sqlin.append(" in (");  
//        // 循环直到当前日期超过结束日期  
//        while (currentCal.getTime().before(endDate) || currentCal.getTime().equals(endDate)) {  
//            // 获取年份和月份（月份需要 +1，因为 Calendar 月份是从 0 开始的）  
//            int year = currentCal.get(Calendar.YEAR);  
//            int month = currentCal.get(Calendar.MONTH) + 1;  
//  
//            // 格式化年份和月份为字符串（YYYYMM）  
//            String yearMonthStr = String.format("%04d%02d", year, month);  
//            sqlin.append("'" + yearMonthStr + "',");  
//  
//            // 将当前日期设置为下一个月的第一天  
//            currentCal.add(Calendar.MONTH, 1);  
//            currentCal.set(Calendar.DAY_OF_MONTH, 1);  
//        }  
//  
//        // 删除最后一个逗号并添加括号结束  
//        sqlin.deleteCharAt(sqlin.length() - 1); // 删除最后的逗号  
//        sqlin.append(")");  
//		return sqlin.toString();
//	}
	
	
	private static Map<String,String> getDateIntervalsql(Date startDate,Date endDate){
		if(startDate.compareTo(endDate) == 1) {
			ExceptionUtils.wrappBusinessException("开始期间不能大于结束期间!");
		}
		// 创建起始日期的 Calendar 实例 
        Calendar startCal = Calendar.getInstance();
        startCal.setTime(startDate);
 
        // 创建用于迭代的 Calendar 实例，从起始日期开始  
        Calendar currentCal = Calendar.getInstance();
        currentCal.setTime(startDate);
  
        // 用于构建 SQL IN 子句的 StringBuffer
        StringBuffer wa_periodin = new StringBuffer();
        StringBuffer query_year_monthin = new StringBuffer();
        StringBuffer allin = new StringBuffer();
        allin.append(" in (");
        wa_periodin.append(" in (");
        query_year_monthin.append(" in (");
        // 循环直到当前日期超过结束日期
         while (currentCal.getTime().before(endDate) || currentCal.getTime().equals(endDate)) {
            // 获取年份和月份（月份需要 +1，因为 Calendar 月份是从 0 开始的）
            int year = currentCal.get(Calendar.YEAR);
            int month = currentCal.get(Calendar.MONTH) + 1;
            
            // 格式化年份和月份为字符串（YYYYMM）
            String yearMonthStr = String.format("%04d%02d", year, month);
            //2023年情况特殊，上半年和下半年的奖金在不同的表
            if(year == 2023) {
	            if(month <= 6) {
	            	query_year_monthin.append("'" + yearMonthStr + "',");
	            }else {
	            	wa_periodin.append("'" + yearMonthStr + "',");
	            }
            }else {
            	query_year_monthin.append("'" + yearMonthStr + "',");
            	wa_periodin.append("'" + yearMonthStr + "',");  
            }
           
            allin.append("'" + yearMonthStr + "',");  
            // 将当前日期设置为下一个月的第一天  
            currentCal.add(Calendar.MONTH, 1);  
            currentCal.set(Calendar.DAY_OF_MONTH, 1);  
        }  
        if(wa_periodin.substring(wa_periodin.length()-1).equals("(")) {
        	wa_periodin.append("'1111'");
        }else {
        	 wa_periodin.deleteCharAt(wa_periodin.length() - 1); // 删除最后的逗号  
        }
        wa_periodin.append(")");
        if(query_year_monthin.substring(query_year_monthin.length()-1).equals("(")) {
        	query_year_monthin.append("'1111'");
        }else {
        	query_year_monthin.deleteCharAt(query_year_monthin.length() - 1); // 删除最后的逗号  
        }
        
        query_year_monthin.append(")");
        
        //时间必选，所以最后一位会是逗号
        allin.deleteCharAt(allin.length() - 1); // 删除最后的逗号  
        allin.append(")");
        Map<String,String> map = new HashMap<String,String>();
        map.put("wa_periodin", wa_periodin.toString());
        map.put("query_year_monthin", query_year_monthin.toString());
        map.put("allin", allin.toString());
		return map;
	}
	
	
	/*
	 * 自求多福
	 */
	private ArrayList<Object> queryData(String codein,String startPeriod,String endPeriod, Map<String,String> map,String psncode,String psnname,String codeTypein) throws BusinessException{
		
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT  ");
		sql.append(" sum( ffyf ) AS ffyf,");
		sql.append(" psncode,");
		sql.append(" psnname,");
		sql.append(" hrorgname,");
		sql.append(" deptname,");
		sql.append(" postname,");
		sql.append(" CASE");
		sql.append(" 	WHEN EXISTS(");
		sql.append("	SELECT DISTINCT bd_defdoc1.name");
		sql.append("	FROM");
		sql.append("	hi_psnjob hi_psnjob1");
		sql.append("	LEFT JOIN org_adminorg org_adminorg1 ON hi_psnjob1.pk_org = org_adminorg1.pk_adminorg");
		sql.append("	LEFT JOIN om_post om_post1 ON hi_psnjob1.jobglbdef30 = om_post1.pk_post");
		sql.append("	LEFT JOIN bd_defdoc bd_defdoc1 ON om_post1.glbdef1 = bd_defdoc1.pk_defdoc");
		sql.append("	WHERE");
		sql.append("	hi_psnjob1.dr = 0	AND org_adminorg1.name = hrorgname	AND hi_psnjob1.clerkcode = psncode");
		sql.append("	AND hi_psnjob1.ismainjob = 'N' AND bd_defdoc1.name = 'A' AND hi_psnjob1.endflag = 'N'");
		sql.append("	) THEN 'A' ELSE defname	END AS defname,");
		sql.append(" ismainjob,");
		sql.append(" begindate,");
		sql.append(" enddate,");
		sql.append(" sum( bmcd ) AS bmcd,");
		sql.append(" sum( yfdk ) AS yfdk,");
		sql.append(" sum( gsbt ) AS gsbt,");
		sql.append(" sum( zzbt ) AS zzbt,");
		sql.append(" sum( designbonus ) AS designbonus,");
		sql.append(" sum( marketbonus ) AS marketbonus,");
		sql.append(" sum( awardsbonus ) AS awardsbonus,");
		sql.append(" COALESCE( sum( managementbonus ), 0 ) - COALESCE( sum( yfdk ), 0 ) AS managementbonus,");
		sql.append(" sum( servicebonus ) AS servicebonus,");
		sql.append(" sum( guaranteebonus1 ) AS guaranteebonus1,");
		sql.append(" sum( guaranteebonus2 ) AS guaranteebonus2,");
		sql.append(" sum( specialbonus ) AS specialbonus,");
		sql.append(" sum( allowancebonus ) AS allowancebonus,");
		sql.append(" sum( function_bonus ) AS function_bonus,");
		sql.append(" sum( manage_jsbonus ) AS manage_jsbonus,");
		sql.append(" sum( manage_bdamount ) AS manage_bdamount,");
		sql.append(" sum( share_bonus ) AS share_bonus");
		sql.append(" FROM(");
		sql.append(" SELECT");
		sql.append(" 	NULL AS ffyf,");
		sql.append(" 	hi_psnjob.clerkcode AS psncode,");
		sql.append(" 	bd_psndoc.name AS psnname,");
		sql.append(" 	org_hrorg.name AS hrorgname,");
		sql.append(" 	org_dept.name AS deptname,");
		sql.append(" 	om_posts.postname AS postname,");
		sql.append(" 	bd_defdoc.name AS defname,");
		sql.append(" 	CASE");
		sql.append(" 		hi_psnjob.ismainjob");
		sql.append(" 		WHEN 'Y' THEN");
		sql.append(" 		'主职' ELSE '兼职'");
		sql.append(" 	END AS ismainjob,");
		sql.append(" 	hi_psnjob.begindate AS begindate,");
		sql.append(" 	hi_psnjob.enddate AS enddate,");
		sql.append(" 	NULL AS bmcd,");
		sql.append(" 	NULL AS yfdk,");
		sql.append(" 	NULL AS gsbt,");
		sql.append(" 	NULL AS zzbt,");
		sql.append(" 	NULL AS designbonus,");
		sql.append(" 	NULL AS marketbonus,");
		sql.append(" 	NULL AS awardsbonus,");
		sql.append(" 	NULL AS managementbonus,");
		sql.append(" 	NULL AS servicebonus,");
		sql.append(" 	NULL AS guaranteebonus1,");
		sql.append(" 	NULL AS guaranteebonus2,");
		sql.append(" 	NULL AS specialbonus,");
		sql.append(" 	NULL AS allowancebonus,");
		sql.append(" 	CASE");
		sql.append("		WHEN ROW_NUMBER ( ) OVER ( PARTITION BY bd_psndoc.name, org_hrorg.name, org_dept.name, om_post.postname ORDER BY hi_psnjob.begindate DESC ) = 1 THEN");
		sql.append("		bonus_table.function_bonus");
		sql.append(" 	END AS function_bonus,");
		sql.append(" 	CASE");
		sql.append("		WHEN ROW_NUMBER ( ) OVER ( PARTITION BY bd_psndoc.name, org_hrorg.name, org_dept.name, om_post.postname ORDER BY hi_psnjob.begindate DESC ) = 1 THEN");
		sql.append("		bonus_table.manage_jsbonus");
		sql.append(" 	END AS manage_jsbonus,");
		sql.append(" 	CASE");
		sql.append("		WHEN ROW_NUMBER ( ) OVER ( PARTITION BY bd_psndoc.name, org_hrorg.name, org_dept.name, om_post.postname ORDER BY hi_psnjob.begindate DESC ) = 1 THEN");
		sql.append("		bonus_table.manage_bdamount");
		sql.append(" 	END AS manage_bdamount,");
		sql.append(" 	CASE");
		sql.append("		WHEN ROW_NUMBER ( ) OVER ( PARTITION BY bd_psndoc.name, org_hrorg.name, org_dept.name, om_post.postname ORDER BY hi_psnjob.begindate DESC ) = 1 THEN");
		sql.append(" 		bonus_table.share_bonus");
		sql.append(" 	END AS share_bonus");
		sql.append(" FROM");
		sql.append(" 	bd_psndoc bd_psndoc");
		sql.append(" LEFT JOIN hi_psnjob hi_psnjob ON bd_psndoc.pk_psndoc = hi_psnjob.pk_psndoc");
		sql.append(" LEFT JOIN org_adminorg org_hrorg ON hi_psnjob.pk_org = org_hrorg.pk_adminorg");
		sql.append(" LEFT JOIN org_dept org_dept ON hi_psnjob.pk_dept = org_dept.pk_dept");
		sql.append(" LEFT JOIN om_post om_post ON hi_psnjob.pk_post = om_post.pk_post");
		sql.append(" LEFT JOIN om_post om_posts ON hi_psnjob.jobglbdef30 = om_posts.pk_post");
		sql.append(" LEFT JOIN bd_defdoc bd_defdoc ON om_posts.glbdef1 = bd_defdoc.pk_defdoc");
		sql.append(" LEFT JOIN (");
		sql.append("		SELECT");
		sql.append(" 				vdef1,");
		sql.append(" 				cost_corp,");
		sql.append(" 				cost_dept,");
		sql.append(" 				postname,");
		sql.append(" 				sum(function_bonus) as function_bonus,");
		sql.append(" 				sum(manage_jsbonus) as manage_jsbonus,");
		sql.append(" 				sum(manage_bdamount) as manage_bdamount,");
		sql.append(" 				sum(share_bonus) as share_bonus");
		sql.append(" 		FROM");
		sql.append(" 				th_bonus");
		sql.append("        WHERE");
		sql.append("        		dr = '0'  AND (SUBSTR(workcycle_begin, 1, 7) <= '"+endPeriod+"' AND SUBSTR(workcycle_end, 1, 7) >= '"+startPeriod+"') GROUP BY vdef1,cost_corp,cost_dept,postname");
		sql.append(" 	)bonus_table ON hi_psnjob.clerkcode = bonus_table.vdef1");
		sql.append("	AND COALESCE(org_hrorg.name,'N') = COALESCE(bonus_table.cost_corp,'N')");
		sql.append("	AND COALESCE(org_dept.name,'N') = COALESCE(bonus_table.cost_dept,'N')");
		sql.append("	AND COALESCE(om_post.postname,'N') = COALESCE(bonus_table.postname,'N')");
		sql.append(" WHERE");
		sql.append(" 		bd_psndoc.dr = 0 AND hi_psnjob.dr = 0");
		sql.append("        AND om_posts.postname <> '发薪人员'");
		sql.append("        AND org_hrorg.code " + codein);
		if(psncode != null && !"".equals(psncode)) {
			sql.append(" 	AND	hi_psnjob.clerkcode = '"+psncode+"'");
		}
		if(psnname != null && !"".equals(psnname)) {
			sql.append(" 	AND	bd_psndoc.name like '%"+psnname+"%'");
		}
		sql.append(" AND (( SUBSTR( hi_psnjob.begindate, 1, 7 ) <= '"+endPeriod+"' AND SUBSTR( hi_psnjob.enddate, 1, 7 ) >= '"+startPeriod+"' )OR ( enddate IS NULL ) ) ");
		//拼接2023年上半年部分sql
		
		sql.append(" UNION ALL");
		sql.append(" SELECT * FROM(");
		sql.append(" SELECT");
		sql.append("	COUNT( DISTINCT es2023.query_year_month ) AS ffyf,");
		sql.append(" 	es2023.clerk_code AS psncode,");
		sql.append(" 	es2023.employee_name AS psnname,");
		sql.append(" 	es2023.company AS hrorgname,");
		sql.append(" 	org_dept.name AS deptname,");
		sql.append(" 	om_posts.postname AS postname,");
		sql.append(" 	bd_defdoc.name AS defname,");
		sql.append(" CASE");
		sql.append("	hi_psnjobs.ismainjob");
		sql.append("	WHEN 'Y' THEN");
		sql.append(" 	'主职' ELSE '兼职'");
		sql.append(" END AS ismainjob,");
		sql.append("	hi_psnjobs.begindate AS begindate,");
		sql.append("	hi_psnjobs.enddate AS enddate,");
		sql.append("	SUM( CASE WHEN es2023.cost_category = '部门承担人力成本' THEN es2023.amount END ) AS bmcd,");
		sql.append("	SUM( CASE WHEN es2023.cost_category = '设计预发待扣' THEN es2023.amount END ) + SUM( CASE WHEN es2023.cost_category = '管理预发待扣' THEN es2023.amount END ) AS yfdk,");
		sql.append("	SUM( CASE WHEN es2023.cost_category = '公司管理费用' THEN es2023.amount END ) AS gsbt,");
		sql.append("	SUM( CASE WHEN es2023.cost_category = '资质补贴' THEN es2023.amount END ) AS zzbt,");
		sql.append("	NULL AS designbonus,");
		sql.append("	NULL AS marketbonus,");
		sql.append("	NULL AS awardsbonus,");
		sql.append("	NULL AS managementbonus,");
		sql.append("	NULL AS servicebonus,");
		sql.append("	NULL AS guaranteebonus1,");
		sql.append("	NULL AS guaranteebonus2,");
		sql.append("	NULL AS specialbonus,");
		sql.append("	NULL AS allowancebonus,");
		sql.append("	NULL AS function_bonus,");
		sql.append("	NULL AS manage_jsbonus,");
		sql.append("	NULL AS manage_bdamount,");
		sql.append("	NULL AS share_bonus ");
		sql.append(" FROM");
		sql.append("	EMPLOYEE_SALARY_PRIM2023 es2023");
		sql.append("	LEFT JOIN org_adminorg org_hrorg ON es2023.company = org_hrorg.name");
		sql.append("	LEFT JOIN org_dept org_dept ON es2023.deptcode = org_dept.code");
		sql.append("	LEFT JOIN (");
		sql.append("		SELECT");
		sql.append("			hi_psnjob.clerkcode AS clerkcode,");
		sql.append("			hi_psnjob.pk_org AS pk_org,");
		sql.append("			hi_psnjob.pk_dept AS pk_dept,");
		sql.append("			hi_psnjob.pk_post AS pk_post,");
		sql.append("			om_post.postname AS postname,");
		sql.append("			hi_psnjob.jobglbdef30 AS jobglbdef30,");
		sql.append("			hi_psnjob.begindate AS begindate,");
		sql.append("			hi_psnjob.enddate AS enddate,");
		sql.append("			hi_psnjob.ismainjob AS ismainjob,");
		sql.append("			ROW_NUMBER ( ) OVER (PARTITION BY hi_psnjob.clerkcode,hi_psnjob.pk_org,hi_psnjob.pk_dept,hi_psnjob.pk_post,");
		sql.append("			hi_psnjob.jobglbdef30");
		sql.append("			ORDER BY hi_psnjob.begindate DESC ) AS rn");
		sql.append("		FROM");
		sql.append("			hi_psnjob hi_psnjob");
		sql.append("			LEFT JOIN om_post om_post ON hi_psnjob.pk_post = om_post.pk_post");
		sql.append("	) hi_psnjobs ON es2023.clerk_code = hi_psnjobs.clerkcode ");
		sql.append("		AND COALESCE( org_hrorg.pk_adminorg, 'N' ) = COALESCE( hi_psnjobs.pk_org, 'N' )");
		sql.append("		AND COALESCE( org_dept.pk_dept, 'N' ) = COALESCE( hi_psnjobs.pk_dept, 'N' )");
		sql.append("		AND COALESCE( es2023.position, 'N' ) = COALESCE( hi_psnjobs.postname, 'N' )");
		sql.append("		AND hi_psnjobs.rn = 1");
		sql.append("	LEFT JOIN om_post om_posts ON hi_psnjobs.jobglbdef30 = om_posts.pk_post");
		sql.append("	LEFT JOIN bd_defdoc bd_defdoc ON om_posts.glbdef1 = bd_defdoc.pk_defdoc");
		sql.append(" WHERE");
		sql.append(" 	TO_CHAR(query_year_month, 'YYYYMM') "+ map.get("query_year_monthin"));
		sql.append("	AND om_posts.postname <> '发薪人员'");
		sql.append("    AND org_hrorg.code " + codein);
		if(psncode != null && !"".equals(psncode)) {
			sql.append(" 	AND	es2023.clerk_code = '"+psncode+"'");
		}
		if(psnname != null && !"".equals(psnname)) {
			sql.append(" 	AND	es2023.employee_name like '%"+psnname+"%'");
		}
		sql.append(" GROUP BY");
		sql.append("	es2023.clerk_code,");
		sql.append("	es2023.employee_name,");
		sql.append("	es2023.company,");
		sql.append("	org_dept.name,");
		sql.append("	om_posts.postname,");
		sql.append("	bd_defdoc.name,");
		sql.append("	hi_psnjobs.ismainjob,");
		sql.append("	hi_psnjobs.begindate,");
		sql.append("	hi_psnjobs.enddate)");
		sql.append(" WHERE (bmcd <> 0 OR yfdk<> 0 OR gsbt<> 0 OR zzbt<> 0)	");
		//拼接收入部分sql
		sql.append(" UNION ALL");
		sql.append(" SELECT * FROM(");
		sql.append(" SELECT");
		sql.append("	COUNT( DISTINCT hr_laborcost.wa_period ) AS ffyf,");
		sql.append("	hr_laborcost.workercode AS psncode,");
		sql.append("	hr_laborcost.name AS psnname,");
		sql.append("	org_hrorg.name AS hrorgname,");
		sql.append("	org_dept.name AS deptname,");
		sql.append("	om_posts.postname AS postname,");
		sql.append("	bd_defdoc.name AS defname,");
		sql.append(" 	CASE");
		sql.append("		hi_psnjobs.ismainjob");
		sql.append("		WHEN 'Y' THEN");
		sql.append(" 		'主职' ELSE '兼职'");
		sql.append(" 	END AS ismainjob,");
		sql.append("	hi_psnjobs.begindate AS begindate,");
		sql.append("	hi_psnjobs.enddate AS enddate,");
		sql.append("	SUM( CASE WHEN hr_laborcost.outlaytype = '部门承担人力成本' THEN hr_laborcost.decimalmny END ) AS bmcd,");
		sql.append("	SUM( CASE WHEN hr_laborcost.outlaytype = '设计预发待扣' THEN hr_laborcost.decimalmny END ) + ");
		sql.append("		SUM( CASE WHEN hr_laborcost.outlaytype = '管理预发待扣' THEN hr_laborcost.decimalmny END ) AS yfdk,");
		sql.append("	SUM( CASE WHEN hr_laborcost.outlaytype = '公司管理费用' AND hr_laborcost.wa_type <> '资质补贴' THEN hr_laborcost.decimalmny END ) AS gsbt,");
		sql.append("	SUM( CASE WHEN hr_laborcost.wa_type = '资质补贴' THEN hr_laborcost.decimalmny END ) AS zzbt,");
		sql.append("	NULL AS designbonus,");
		sql.append("	NULL AS marketbonus,");
		sql.append("	NULL AS awardsbonus,");
		sql.append("	NULL AS managementbonus,");
		sql.append("	NULL AS servicebonus,");
		sql.append("	NULL AS guaranteebonus1,");
		sql.append("	NULL AS guaranteebonus2,");
		sql.append("	NULL AS specialbonus,");
		sql.append("	NULL AS allowancebonus,");
		sql.append("	NULL AS function_bonus,");
		sql.append("	NULL AS manage_jsbonus,");
		sql.append("	NULL AS manage_bdamount,");
		sql.append("	NULL AS share_bonus");
		sql.append(" FROM");
		sql.append("	hr_laborcost hr_laborcost");
		sql.append("	LEFT JOIN org_adminorg org_hrorg ON hr_laborcost.cost_org = org_hrorg.pk_adminorg");
		sql.append("	LEFT JOIN org_dept org_dept ON hr_laborcost.cost_dept = org_dept.pk_dept");
		sql.append("	LEFT JOIN om_post om_post ON hr_laborcost.post = om_post.pk_post");
		sql.append("	LEFT JOIN (");
		sql.append("		SELECT");
		sql.append("			clerkcode,");
		sql.append("			pk_org,");
		sql.append("			pk_dept,");
		sql.append("			pk_post,");
		sql.append("			jobglbdef30,");
		sql.append("			begindate,");
		sql.append("			enddate,");
		sql.append("			ismainjob,");
		sql.append("			ROW_NUMBER ( ) OVER ( PARTITION BY clerkcode, pk_org, pk_dept, pk_post, jobglbdef30 ORDER BY begindate DESC ) AS rn");
		sql.append("		FROM");
		sql.append("		hi_psnjob");
		sql.append("		) hi_psnjobs ON hr_laborcost.workercode = hi_psnjobs.clerkcode ");
		sql.append("		AND COALESCE( hr_laborcost.cost_org, 'N' ) = COALESCE( hi_psnjobs.pk_org, 'N' ) ");
		sql.append("		AND COALESCE( hr_laborcost.cost_dept, 'N' ) = COALESCE( hi_psnjobs.pk_dept, 'N' ) ");
		sql.append("		AND COALESCE( hr_laborcost.post, 'N' ) = COALESCE( hi_psnjobs.pk_post, 'N' )");
		sql.append("		AND hi_psnjobs.rn = 1");
		sql.append("	LEFT JOIN om_post om_posts ON hi_psnjobs.jobglbdef30 = om_posts.pk_post");
		sql.append("	LEFT JOIN bd_defdoc bd_defdoc ON om_posts.glbdef1 = bd_defdoc.pk_defdoc");
		sql.append(" WHERE");
		sql.append(" 	hr_laborcost.dr = 0");
		sql.append("	AND wa_period "+ map.get("wa_periodin"));
		sql.append("	AND om_posts.postname <> '发薪人员' ");
		sql.append("    AND org_hrorg.code " + codein);
		if(psncode != null && !"".equals(psncode)) {
			sql.append(" 	AND	hr_laborcost.workercode = '"+psncode+"'");
		}
		if(psnname != null && !"".equals(psnname)) {
			sql.append(" 	AND	hr_laborcost.name like '%"+psnname+"%'");
		}
		sql.append(" GROUP BY");
		sql.append("	hr_laborcost.workercode,");
		sql.append("	hr_laborcost.name,");
		sql.append("	org_hrorg.name,");
		sql.append("	org_dept.name,");
		sql.append("	om_posts.postname,");
		sql.append("	bd_defdoc.name,");
		sql.append("	hi_psnjobs.begindate,");
		sql.append("	hi_psnjobs.enddate,");
		sql.append("	hi_psnjobs.ismainjob)");
		sql.append(" WHERE (bmcd <> 0 OR yfdk<> 0 OR gsbt<> 0 OR zzbt<> 0)");
		//拼接奖金部分sql
		sql.append(" UNION ALL");
		sql.append(" SELECT");
		sql.append("	NULL AS ffyf,");
		sql.append("	hi_psnjob.clerkcode AS psncode,");
		sql.append("	bd_psndoc.name AS psnname,");
		sql.append("	org_hrorg.name AS hrorgname,");
		sql.append("	org_dept.name AS deptname,");
		sql.append("	om_posts.postname AS postname,");
		sql.append("	bd_defdoc.name AS defname,");
		sql.append("	CASE hi_psnjobs.ismainjob WHEN 'Y' THEN '主职' WHEN 'N' THEN '兼职' END AS ismainjob,");
		sql.append("	hi_psnjobs.begindate AS begindate,");
		sql.append("	hi_psnjobs.enddate AS enddate,");
		sql.append("	NULL AS bmcd,");
		sql.append("	NULL AS yfdk,");
		sql.append("	NULL AS gsbt,");
		sql.append("	NULL AS zzbt,");
		sql.append("	sum( designbonus ) AS designbonus,");
		sql.append("	sum( marketbonus ) AS marketbonus,");
		sql.append("	sum( awardsbonus ) AS awardsbonus,");
		sql.append("	sum( managementbonus ) AS managementbonus,");
		sql.append("	sum( servicebonus ) AS servicebonus,");
		sql.append("	sum( guaranteebonus1 ) AS guaranteebonus1,");
		sql.append("	sum( guaranteebonus2 ) AS guaranteebonus2,");
		sql.append("	sum( specialbonus ) AS specialbonus,");
		sql.append("	sum( allowancebonus ) AS allowancebonus,");
		sql.append("	NULL AS function_bonus,");
		sql.append("	NULL AS manage_jsbonus,");
		sql.append("	NULL AS manage_bdamount,");
		sql.append("	NULL AS share_bonus");
		sql.append("	FROM");
		sql.append("		thsj.v_nc_qysr @THSJ_PM_DBLINK v_nc_qysr");
		sql.append("		LEFT JOIN bd_psndoc bd_psndoc ON v_nc_qysr.psndoc_id = bd_psndoc.pk_psndoc");
		sql.append("		LEFT JOIN ( SELECT pk_psndoc, clerkcode, ROW_NUMBER ( ) OVER ( PARTITION BY clerkcode ORDER BY clerkcode ) AS rn FROM hi_psnjob ) hi_psnjob ON bd_psndoc.pk_psndoc = hi_psnjob.pk_psndoc AND hi_psnjob.rn = 1");
		sql.append("		LEFT JOIN org_adminorg org_hrorg ON v_nc_qysr.costcomid = org_hrorg.pk_adminorg");
		sql.append("		LEFT JOIN org_dept org_dept ON v_nc_qysr.costdeptid = org_dept.pk_dept");
		sql.append("		LEFT JOIN om_post om_post1 ON v_nc_qysr.position = om_post1.pk_post");
		sql.append(" 		LEFT JOIN om_post om_posts ON v_nc_qysr.basepostid = om_posts.pk_post");
		sql.append(" 		LEFT JOIN bd_defdoc bd_defdoc ON om_posts.glbdef1 = bd_defdoc.pk_defdoc");
		sql.append("		LEFT JOIN (");
		sql.append("		SELECT pk_psndoc, pk_org, pk_dept, jobglbdef30, begindate, enddate, ismainjob, ");
		sql.append("		ROW_NUMBER() OVER (PARTITION BY pk_psndoc, pk_org, pk_dept, jobglbdef30 ORDER BY begindate DESC) AS rn");
		sql.append("		FROM hi_psnjob");
		sql.append("		) hi_psnjobs ON v_nc_qysr.psndoc_id = hi_psnjobs.pk_psndoc");
		sql.append("		AND v_nc_qysr.costcomid = hi_psnjobs.pk_org");
		sql.append("		AND v_nc_qysr.costdeptid = hi_psnjobs.pk_dept");
		sql.append("		AND v_nc_qysr.basepostid = hi_psnjobs.jobglbdef30");
		sql.append("		AND hi_psnjobs.rn = 1");
		sql.append(" 	WHERE");
		sql.append("	v_nc_qysr.costpaydate "+ map.get("allin"));
		sql.append("	AND om_posts.postname <> '发薪人员' ");
		sql.append("    AND org_hrorg.code " + codein);
		if(psncode != null && !"".equals(psncode)) {
			sql.append(" 	AND	hi_psnjob.clerkcode = '"+psncode+"'");
		}
		if(psnname != null && !"".equals(psnname)) {
			sql.append(" 	AND	bd_psndoc.name like '%"+psnname+"%'");
		}
		sql.append(" GROUP BY");
		sql.append(" hi_psnjob.clerkcode,");
		sql.append(" bd_psndoc.name,");
		sql.append(" org_hrorg.name, ");
		sql.append(" org_dept.name, ");
		sql.append(" om_posts.postname,");
		sql.append(" bd_defdoc.name,");
		sql.append(" hi_psnjobs.begindate,");
		sql.append(" hi_psnjobs.enddate,");
		sql.append(" hi_psnjobs.ismainjob");
		sql.append(" ) ");
		if(codeTypein != null && !"".equals(codeTypein)) {
			sql.append("   WHERE  " + codeTypein);
		}
		sql.append(" GROUP BY psncode,psnname,hrorgname,deptname,postname,defname,ismainjob,begindate,enddate  ORDER BY hrorgname,psncode,begindate");
		return (ArrayList<Object>) IUAPQueryBS.executeQuery(sql.toString(), new ArrayListProcessor());
	}
	
	//查询当前登录人是否在自定义档案中维护
	private String queryDftDocUser(String userCode) throws Exception {
		String sql = "select pk_defdoc from bd_defdoc where pk_defdoclist in(select pk_defdoclist from bd_defdoclist where code in ('THJTGL','THZGSGL')) and enablestate ='2' and code = '"+userCode+"'";
		String pk_defdoc = (String) IUAPQueryBS.executeQuery(sql, new ColumnProcessor());
		return pk_defdoc;
	}
}
