package nc.ui.hr.baod_orders.view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import nc.bs.framework.common.NCLocator;
import nc.desktop.ui.WorkbenchEnvironment;
import nc.itf.hr.SocialInsuranceAllMaintain;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.ui.pub.beans.MessageDialog;
import nc.ui.pub.beans.UIButton;
import nc.ui.pub.beans.UIDialog;
import nc.ui.pub.beans.UIPanel;
import nc.ui.pub.beans.UIRefPane;
import nc.ui.pub.bill.BillCardPanel;
import nc.ui.pub.bill.BillEditEvent;
import nc.ui.pub.bill.BillEditListener;
import nc.vo.ecpubapp.pattern.data.ValueUtils;
import nc.vo.pubapp.pattern.pub.PubAppTool;
import nc.vo.uap.rbac.profile.FunctionPermProfileManager;

/**
 * 社保分摊表新增界面
 * @author YaoYu
 *
 */
public class SocialInsuranceAllInsertDialog extends UIDialog implements ActionListener,BillEditListener{

	private static final long serialVersionUID = 1L;
	private SocialInsuranceAllMaintain siaMaintain = NCLocator.getInstance().lookup(SocialInsuranceAllMaintain.class);
	private IUAPQueryBS iuap = (IUAPQueryBS) NCLocator.getInstance().lookup(IUAPQueryBS.class.getName());
	private UIPanel btnUIPanel;
	private BillCardPanel jlcardPanel = null;//卡面面板
	private UIButton btnOK;
	private UIButton btnAddRow;
	private UIButton btnRemoveRow;
	private UIPanel ivjUIPanel = null;
	private String orgCode = null;
	private String orgName = null;
	private String period = null;
	
	@SuppressWarnings("deprecation")
	public SocialInsuranceAllInsertDialog(String orgCode, String orgName,String period) throws Exception {
		this.orgCode = orgCode;
		this.orgName = orgName;
		this.period = period;
		initialize();
	}
	
	private void initialize() {
	    setLayout(new BorderLayout());
	    setSize(new Dimension(1050, 350));
	    this.setResizable(true);
	    add(getUIPanel(), BorderLayout.CENTER);
	    this.addListenerEvent();
	    doAddAction();
	}
	
	
	private UIPanel getUIPanel() {
		if (this.ivjUIPanel == null) {
			this.ivjUIPanel = new UIPanel();
			this.ivjUIPanel.setLayout(new BorderLayout());
			this.ivjUIPanel.setPreferredSize(new Dimension(0, 500));
			this.ivjUIPanel.add(getBtnUIPanel(), BorderLayout.SOUTH);
			this.ivjUIPanel.add(getJlcardPanel(), BorderLayout.CENTER);
		}
		return this.ivjUIPanel;
	}	

	private void addListenerEvent() {
		this.getJlcardPanel().addEditListener(this);
		this.getBtnOK().addActionListener(this);
		this.getBtnAddRow().addActionListener(this);
		this.getBtnRemoveRowRow().addActionListener(this);
	}
	
	private BillCardPanel getJlcardPanel() {
		if(this.jlcardPanel == null){
			this.jlcardPanel = new BillCardPanel();
			this.jlcardPanel.setName("jlcardPanel");
			//根据单据模板编码加载模板
			this.jlcardPanel.loadTemplet("gjjft",null,WorkbenchEnvironment.getInstance().getLoginUser().getPrimaryKey(),
					WorkbenchEnvironment.getInstance().getLoginUser().getPk_org());
			//UIRefPane orgCodeRef = (UIRefPane) this.jlcardPanel.getBodyItem("orgcode").getComponent();
			UIRefPane orgCodeRefs = (UIRefPane) this.jlcardPanel.getBodyItem("contributoryorg").getComponent();
			//节点编码
			String nodeCode = "60H20103";
			//权限组织
			String[] pkorgs = FunctionPermProfileManager.getInstance().getProfile(WorkbenchEnvironment.getInstance().getLoginUser().getUser_code()).getFuncSubInfo(nodeCode).getFuncPermissionPkorgs();
			//公司字段设置组织权限
			//orgCodeRef.getRefModel().setFilterPks(pkorgs);
			//成本归属公司设置组织权限
			orgCodeRefs.getRefModel().setFilterPks(pkorgs);
			
			try {
				String orgId = queyrOrgId(orgName);
				UIRefPane clerkCodeRef = (UIRefPane) this.jlcardPanel.getBodyItem("clerkcode").getComponent();
				// 设置当前组织
				clerkCodeRef.setPk_org(orgId);
			} catch (Exception e) {
				MessageDialog.showHintDlg(this, "提示", e.getMessage());
			}
		}
		return this.jlcardPanel;
	}

	private UIPanel getBtnUIPanel() {
		if (this.btnUIPanel == null) {
			this.btnUIPanel = new nc.ui.pub.beans.UIPanel();
			//btnUIPanel.add(this.getBtnAddRow(), this.getBtnAddRow().getName());
			//btnUIPanel.add(this.getBtnRemoveRowRow(), this.getBtnRemoveRowRow().getName());
			this.btnUIPanel.add(this.getBtnOK(), this.getBtnOK().getName());
		}
		return this.btnUIPanel;
	}
	
	private UIButton getBtnAddRow() {
	    if (this.btnAddRow == null) {
	    	this.btnAddRow = new UIButton();
	        this.btnAddRow.setName("btnAddRow");
	        this.btnAddRow.setText("新增行");
	    }
	    return this.btnAddRow;
	}
	
	private UIButton getBtnRemoveRowRow() {
	    if (this.btnRemoveRow == null) {
	    	this.btnRemoveRow = new UIButton();
	    	this.btnRemoveRow.setName("btnRemoveRow");
	    	this.btnRemoveRow.setText("删除行");
	    }
	    return this.btnRemoveRow;
	}


	private UIButton getBtnOK() {
		if (this.btnOK == null) {
			this.btnOK = new UIButton();
			this.btnOK.setName("btnOK");
			this.btnOK.setText("确定(Y)");
		}
		return this.btnOK;
	}

	private void doOKAction() {
		try {
			BillCardPanel cp = this.jlcardPanel;
			//判断必填项
			this.jlcardPanel.dataNotNullValidate();	

			//循环表单行数
			for (int i = 0; i < cp.getRowCount(); i++) {
				String tableName = ValueUtils.getString(cp.getBodyValueAt(i, "tablename"));//表
				//String orgCode = queyrOrgCode(ValueUtils.getString(cp.getBodyValueAt(i, "orgcode")));//公司
				String contributoryOrgName = ValueUtils.getString(cp.getBodyValueAt(i, "contributoryorg"));//成本归属公司
				//String period = ValueUtils.getString(cp.getBodyValueAt(i, "period"));//年月
				String clerkCode = ValueUtils.getString(cp.getBodyValueAt(i, "clerkcode"));//员工编号
				String clerkName = ValueUtils.getString(cp.getBodyValueAt(i, "clerkname"));//姓名
				String basicssum = ValueUtils.getString(cp.getBodyValueAt(i, "basicssum"));//缴纳基数
				String staffsum = ValueUtils.getString(cp.getBodyValueAt(i, "staffsum"));//个人部分
				String orgsum = ValueUtils.getString(cp.getBodyValueAt(i, "orgsum"));//公司部分
				String mark = ValueUtils.getString(cp.getBodyValueAt(i, "mark"));//备注
				//contributoryOrgName可能存在为空的情况,拼接的时候会把null拼接到新的字符串，使用三目运算处理改问题
				contributoryOrgName = contributoryOrgName == null ? "" : contributoryOrgName;
				String combinedField = tableName + contributoryOrgName + clerkCode + clerkName;
				if(queryTable(orgCode, period, combinedField)) {
					MessageDialog.showHintDlg(this, "提示", "成本归属公司:" +contributoryOrgName+ ",员工编号：" + clerkCode + ",员工姓名："+clerkName+",当月数据已存在不允许重复新增");
				return;
				}
				if(tableName.equals("表一：由个人承担")) {
					queryTableOne(orgCode, period, contributoryOrgName, clerkCode, clerkName);
				}
				if(tableName.equals("表二：由外部公司承担")) {
					queryTableTwo(orgCode, period, contributoryOrgName, clerkCode, clerkName);
				}
				if(tableName.equals("表三：由部门承担或全额公司承担")) {
					queryTableThree(orgCode, period, contributoryOrgName, clerkCode, clerkName);
				}
				if(tableName.equals("表四：个人部分已在集团内其他公司扣除")) {
					queryTableFour(orgCode, period, contributoryOrgName, clerkCode, clerkName);
				}
				if(tableName.equals("表五：月薪工资表中当月扣当月缴纳")) {
					queryTableFive(orgCode, period, contributoryOrgName, clerkCode, clerkName);
				}
				if(tableName.equals("表六：实际已缴当月工资个人部分未扣")) {
					queryTableSix(orgCode, period, contributoryOrgName, clerkCode, clerkName);
				}
				if(tableName.equals("表七：实际未缴当月工资个人部分已扣")) {
					queryTableSeven(orgCode, period, contributoryOrgName, clerkCode, clerkName);
				}
				StringBuilder insertSQL = new StringBuilder("INSERT INTO accumulation_fund VALUES (");
				insertSQL.append("'").append("社保分摊表").append("', ");
				insertSQL.append("'").append(orgCode).append("', ");
				insertSQL.append("'").append(period).append("', ");
				insertSQL.append("'").append(combinedField).append("', ");
				insertSQL.append(getString(contributoryOrgName)).append(", ");
				insertSQL.append(getString(clerkCode)).append(", ");
				insertSQL.append(getString(clerkName)).append(", ");
				insertSQL.append(getString(basicssum)).append(", ");
				insertSQL.append(getString(staffsum)).append(", ");
				insertSQL.append(getString(orgsum)).append(", ");
				insertSQL.append(getString(mark)).append(", ");
				insertSQL.append("sysdate,");
				insertSQL.append("null)");
				siaMaintain.executeBaseDAO(insertSQL.toString());
			}
			//关闭弹框
			this.dispose();
		} catch (Exception e) {
			MessageDialog.showHintDlg(this, "提示", e.getMessage());
		}
	}

	
	/**
	 *往最后一行插入一行
	 */
	private void doAddAction() {
		 this.jlcardPanel.getBillModel().addLine();
	}
	
	/**
	 * 删除最后一行
	 */
	private void doRemoveAction() {
		this.jlcardPanel.delLine();
	}
	
	
	@Override
	public void afterEdit(BillEditEvent e) {
		try {
//			if("orgcode".equals(e.getKey())) {
//				String pk_org = String.valueOf(e.getValue());
//				UIRefPane clerkCodeRef = (UIRefPane) this.jlcardPanel.getBodyItem("clerkcode").getComponent();
//				// 设置当前组织
//				clerkCodeRef.setPk_org(pk_org);
//			}
			if("clerkcode".equals(e.getKey())) {
				String clerkcode = String.valueOf(e.getValue());
				if(clerkcode != null) {
					String sql = "SELECT name FROM bd_psndoc WHERE pk_psndoc = '"+clerkcode+"'";
					String clerkname = (String) iuap.executeQuery(sql, new ColumnProcessor());
					//赋值姓名
					this.jlcardPanel.setBodyValueAt(clerkname, 0, "clerkname");
				}else {
					//清空姓名
					this.jlcardPanel.setBodyValueAt(null, 0, "clerkname");
				}
				
			}
		} catch (Exception e1) {
			MessageDialog.showHintDlg(this, "提示", e1.getMessage());
		}
	}

	@Override
	public void bodyRowChange(BillEditEvent arg0) {
		this.jlcardPanel.setBodyValueAt(orgName, 0, "orgcode");
		this.jlcardPanel.setBodyValueAt(period, 0, "period");
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == this.getBtnOK()) {
			// 确定按钮执行事件
			this.doOKAction();
		}else if (e.getSource() == this.getBtnAddRow()) {
			// 新增行按钮执行事件
			this.doAddAction();
		}else {
			// 删除行按钮执行事件
			this.doRemoveAction();
		}	
	}
	
	/**
	 * 将Object转换成适用sql拼接字符
	 * @param value
	 * @return
	 */
	private String getString(Object value) {
		if("".equals(value) || value == null) {
			return null;
		}
		return "'"+value+"'";
		
	}
	
	/**
	 * 查询个人承担是否存在数据
	 * @param orgCode 财务组织
	 * @param period 年月
	 * @param contributoryOrgName 成本归属公司
	 * @param clerkCode 员工号
	 * @param clerkName 姓名
	 * @throws Exception
	 */
	private void queryTableOne(String orgCode, String period, String contributoryOrgName, String clerkCode, String clerkName) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT clerkcode");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" NULL AS orgname,");
		sql.append(" t.CLERKCODE as clerkcode,");
		sql.append(" T1.CLERKNAME as clerkname,");
		sql.append(" sum( nvl( t.VALUE, 0 ) ) AS orgsum,");
		sql.append(" NULL AS staffsum,");
		sql.append(" t1.ENDOWMENT_BASE AS basicssum,");
		sql.append(" t1.mark as mark");
		sql.append(" from NC6337.v_data_xz_gjjshare t");
		sql.append(" left join NC6337.V_SUM_TB_HR_SOCIAL_SECURITY t1 on t1.CLERKCODE=t.CLERKCODE and t1.PAY_MONTH||'-01'=t.ym");
		sql.append(" where");
		sql.append(" t.key = '社保公司税后扣款' and t.VALUE <> 0 and t.ym='" + period + "'||'-01' and t1.ORGCODE='" + orgCode + "' and t1.ENDOWMENT_BASE is not null");
		sql.append(" group by ROWNUM,t.CLERKCODE, T1.CLERKNAME,t.ym,t1.ENDOWMENT_BASE,t1.mark");
		sql.append(" ) where clerkcode ='"+clerkCode+"' AND clerkname = '"+clerkName+"'");
		if(!PubAppTool.isNull(contributoryOrgName)) {
			sql.append(" AND orgname = '"+contributoryOrgName+"'");
		}
		if (iuap.executeQuery(sql.toString(), new ColumnProcessor()) != null) {
			throw new Exception("成本归属公司:" +contributoryOrgName+ ",员工编号：" + clerkCode + ",员工姓名："+clerkName+",当月数据已存在不允许重复新增");
		}
	}
	
	/**
	 * 查询个人承担是否存在数据
	 * @param orgCode 财务组织
	 * @param period 年月
	 * @param contributoryOrgName 成本归属公司
	 * @param clerkCode 员工号
	 * @param clerkName 姓名
	 * @throws Exception
	 */
	private void queryTableTwo(String orgCode, String period, String contributoryOrgName, String clerkCode, String clerkName) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT clerkcode");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" NULL AS orgname,");
		sql.append(" clerkcode,");
		sql.append(" clerkname,");
		sql.append(" endowment_base AS basicssum,");
		sql.append(" so_staff_sum AS staffsum,");
		sql.append(" so_org_sum 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(" ) where clerkcode ='"+clerkCode+"' AND clerkname = '"+clerkName+"'");
		if(!PubAppTool.isNull(contributoryOrgName)) {
			sql.append(" AND orgname = '"+contributoryOrgName+"'");
		}
		if (iuap.executeQuery(sql.toString(), new ColumnProcessor()) != null) {
			throw new Exception("成本归属公司:" +contributoryOrgName+ ",员工编号：" + clerkCode + ",员工姓名："+clerkName+",当月数据已存在不允许重复新增");
		}
	}
	
	/**
	 * 查询由部门承担或全额公司承担是否存在数据
	 * @param orgCode 财务组织
	 * @param period 年月
	 * @param contributoryOrgName 成本归属公司
	 * @param clerkCode 员工号
	 * @param clerkName 姓名
	 * @throws Exception
	 */
	private void queryTableThree(String orgCode, String period, String contributoryOrgName, String clerkCode, String clerkName) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT clerkcode");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" NULL AS orgname,");
		sql.append(" t2.clerkcode AS clerkcode,");
		sql.append(" t2.clerkname AS clerkname,");
		sql.append(" t2.endowment_base AS basicssum,");
		sql.append(" t2.so_staff_sum AS staffsum,");
		sql.append(" t2.so_org_sum AS orgsum,");
		sql.append(" NULL AS mark");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" T.Endowment_Base,T.CLERKCODE,T.CLERKNAME,T.so_org_sum,T.so_staff_sum,T.ORGCODE,T.PAY_MONTH");
		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 SELECT");
		sql.append(" t1.Endowment_Base,t1.CLERKCODE,t1.CLERKNAME,t1.so_org_sum,t1.so_staff_sum,T1.ORGCODE,t1.PAY_MONTH ");
		sql.append(" FROM");
		sql.append(" NC6337.V_SUM_TB_HR_SOCIAL_SECURITY_D t1");
		sql.append(" WHERE");
		sql.append(" t1.MARK LIKE '%表三%'");
		sql.append(" ) t2");
		sql.append(" WHERE");
		sql.append(" t2.PAY_MONTH = '" + period + "' AND t2.ORGCODE = '" + orgCode + "'");
		sql.append(" ) where clerkcode ='"+clerkCode+"' AND clerkname = '"+clerkName+"'");
		if(!PubAppTool.isNull(contributoryOrgName)) {
			sql.append(" AND orgname = '"+contributoryOrgName+"'");
		}
		if (iuap.executeQuery(sql.toString(), new ColumnProcessor()) != null) {
			throw new Exception("成本归属公司:" +contributoryOrgName+ ",员工编号：" + clerkCode + ",员工姓名："+clerkName+",当月数据已存在不允许重复新增");
		}
	}
	
	/**
	 * 查询个人部分已在集团内其他公司扣除是否存在数据
	 * @param orgCode 财务组织
	 * @param period 年月
	 * @param contributoryOrgName 成本归属公司
	 * @param clerkCode 员工号
	 * @param clerkName 姓名
	 * @throws Exception
	 */
	private void queryTableFour(String orgCode, String period, String contributoryOrgName, String clerkCode, String clerkName) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT clerkcode");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" salocation AS orgname,");
		sql.append(" clerkcode,");
		sql.append(" clerkname,");
		sql.append(" endowment_base AS basicssum,");
		sql.append(" so_staff_sum AS staffsum,");
		sql.append(" so_org_sum AS orgsum,");
		sql.append(" mark");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" t.CLERKCODE,T1.CLERKNAME,t.ym,decode( t.c_23, '青岛天华易境建筑设计有限公司', 0, sum( nvl( t.VALUE, 0 ) ) ) AS sum_per_cost,");
		sql.append(" t.c_23 AS salocation,decode( t.c_23, '青岛天华易境建筑设计有限公司', t1.so_org_sum + t1.so_staff_sum, t1.so_org_sum ) AS so_org_sum,");
		sql.append(" t1.so_staff_sum,t1.ENDOWMENT_BASE,T1.MARK");
		sql.append(" FROM");
		sql.append(" NC6337.v_data_xz_gjjshare t");
		sql.append(" LEFT JOIN NC6337.V_SUM_TB_HR_SOCIAL_SECURITY t1 ON t1.CLERKCODE = t.CLERKCODE AND t1.PAY_MONTH || '-01' = t.ym");
		sql.append(" WHERE t.key = '社保个人合计'  AND t.VALUE <> 0 AND t.ym = '" + period + "' || '-01' AND t1.ORGCODE = '" + orgCode + "' AND t1.PAY_SOS_ORG <> t.c_23");
		sql.append(" GROUP BY ROWNUM,t.CLERKCODE,T1.CLERKNAME,t.ym,t1.ENDOWMENT_BASE,t1.so_org_sum,t1.so_staff_sum,t.c_23,T1.MARK");
		sql.append(" ORDER BY t.c_23");
		sql.append(" ) t11");
		sql.append(" ) where clerkcode ='"+clerkCode+"' AND clerkname = '"+clerkName+"'");
		if(!PubAppTool.isNull(contributoryOrgName)) {
			sql.append(" AND orgname = '"+contributoryOrgName+"'");
		}
		if (iuap.executeQuery(sql.toString(), new ColumnProcessor()) != null) {
			throw new Exception("成本归属公司:" +contributoryOrgName+ ",员工编号：" + clerkCode + ",员工姓名："+clerkName+",当月数据已存在不允许重复新增");
		}
	}
	
	/**
	 * 查询月薪工资表中当月扣当月缴纳是否存在数据
	 * @param orgCode 财务组织
	 * @param period 年月
	 * @param contributoryOrgName 成本归属公司
	 * @param clerkCode 员工号
	 * @param clerkName 姓名
	 * @throws Exception
	 */
	private void queryTableFive(String orgCode, String period, String contributoryOrgName, String clerkCode, String clerkName) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT clerkcode");
		sql.append(" FROM");
		sql.append(" (SELECT ");
		sql.append(" costorgname AS orgname,");
		sql.append(" clerkcode,");
		sql.append(" clerkname,");
		sql.append(" endowment_base AS basicssum,");
		sql.append(" so_staff_sum AS staffsum,");
		sql.append(" so_org_sum AS orgsum,");
		sql.append(" mark");
		sql.append(" FROM");
		sql.append(" (SELECT t.CLERKCODE,T1.CLERKNAME,t.ym,sum( nvl( t.VALUE, 0 ) ) AS sum_per_cost,T13.Name AS costorgname,t.c_23 AS salocation,");
		sql.append(" t1.so_org_sum - nvl( t15.sum_per_cost, 0 ) - nvl( t16.SO_ORG_SUM, 0 ) AS so_org_sum,t1.so_staff_sum,t1.ENDOWMENT_BASE,t1.mark");
		sql.append(" FROM");
		sql.append(" NC6337.v_data_xz_gjjshare t");
		sql.append(" LEFT JOIN NC6337.V_SUM_TB_HR_SOCIAL_SECURITY t1 ON t1.CLERKCODE = t.CLERKCODE AND t1.PAY_MONTH || '-01' = t.ym");
		sql.append(" LEFT JOIN (");
		sql.append(" SELECT t12.CLERK_CODE,t12.NC_PK_POST");
		sql.append(" FROM");
		sql.append(" nc6337.monthly_position_gjj t12");
		sql.append(" WHERE");
		sql.append(" t12.month = to_char( last_day( to_date( '" + period + "', 'yyyy-mm' ) ), 'yyyy-mm-dd' )");
		sql.append(" ) T12 ON t12.CLERK_CODE = t.CLERKCODE");
		sql.append(" LEFT JOIN nc6337.om_post t14 ON t14.pk_post = t12.NC_PK_POST");
		sql.append(" LEFT JOIN nc6337.org_corp T13 ON T13.Pk_Corp = t14.pk_org");
		sql.append(" LEFT JOIN nc6337.person_afford_sbgjj t15 ON t15.CLERKCODE = t.CLERKCODE AND t.YM = t15.ym");
		sql.append(" LEFT JOIN nc6337.DEPT_AFFORD_SBGJJ t16 ON t16.CLERKCODE = t.CLERKCODE AND t.YM = t16.PAY_MONTH ");
		sql.append(" WHERE");
		sql.append(" t.key IN ( '社保个人合计', '费用调整社保', '社保个人扣款', '费用调整社保T' )AND t.VALUE <> 0 AND t.ym = '" + period + "' || '-01' ");
		sql.append(" AND t1.ORGCODE = '" + orgCode + "'AND t1.PAY_SOS_ORG = t.c_23");
		sql.append(" AND t.CLERKCODE NOT IN ( SELECT t11.WORKERCODE FROM nc6337.v_hr_allocationratio_gjjshareF t11 WHERE t11.WA_PERIOD = '" + period + "' || '-01' )");
		sql.append(" GROUP BY t.CLERKCODE,T1.CLERKNAME,t.ym,t1.ENDOWMENT_BASE,t1.so_org_sum - nvl( t15.sum_per_cost, 0 ) - nvl( t16.SO_ORG_SUM, 0 ),");
		sql.append(" t1.so_staff_sum,T13.Name,t.c_23,t1.mark");
		sql.append(" 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.so_org_sum, 0 ) * nvl( t.perc, 0 ), 3 ) AS so_org_sum,round( nvl( t1.so_staff_sum, 0 ) * nvl( t.perc, 0 ), 3 ) AS so_staff_sum,");
		sql.append(" t1.Endowment_Base,t1.mark");
		sql.append(" FROM");
		sql.append(" nc6337.v_hr_allocationratio_gjjshareF t");
		sql.append(" LEFT JOIN nc6337.V_SUM_TB_HR_SOCIAL_SECURITY t1 ON t1.CLERKCODE = t.WORKERCODE AND t1.PAY_MONTH || '-01' = t.WA_PERIOD");
		sql.append(" LEFT JOIN ( SELECT DISTINCT T5.CODE, T5.NAME, t5.pk_corp FROM nc6337.ORG_CORP T5 ) T6 ON T6.pk_corp = T.COST_ORG");
		sql.append(" WHERE");
		sql.append(" t.WA_PERIOD = '" + period + "' || '-01' AND t1.CLERKNAME IS NOT NULL AND t1.ORGCODE = '" + orgCode + "'");
		sql.append(" 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,'上海天华' AS salocation,");
		sql.append(" decode( t1.mark, '资质人员', t1.so_org_sum + t1.so_staff_sum, t1.so_org_sum ) AS so_org_sum,0 AS so_staff_sum,");
		sql.append(" t1.Endowment_Base,t1.mark");
		sql.append(" FROM");
		sql.append(" NC6337.V_SUM_TB_HR_SOCIAL_SECURITY_D t1");
		sql.append(" WHERE");
		sql.append(" t1.MARK IN ( '资质人员', '上海公司承担' )AND t1.PAY_MONTH = '" + period + "'AND t1.ORGCODE = '" + orgCode + "')");
		sql.append(" ) where clerkcode ='"+clerkCode+"' AND clerkname = '"+clerkName+"'");
		if(!PubAppTool.isNull(contributoryOrgName)) {
			sql.append(" AND orgname = '"+contributoryOrgName+"'");
		}
		if (iuap.executeQuery(sql.toString(), new ColumnProcessor()) != null) {
			throw new Exception("成本归属公司:" +contributoryOrgName+ ",员工编号：" + clerkCode + ",员工姓名："+clerkName+",当月数据已存在不允许重复新增");
		}
	}
	
	/**
	 * 查询实际已缴纳当月工资个人部分未扣是否存在数据
	 * @param orgCode 财务组织
	 * @param period 年月
	 * @param contributoryOrgName 成本归属公司
	 * @param clerkCode 员工号
	 * @param clerkName 姓名
	 * @throws Exception
	 */
	private void queryTableSix(String orgCode, String period, String contributoryOrgName, String clerkCode, String clerkName) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT");
		sql.append(" clerkcode");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" orgname,");
		sql.append(" clerkcode,");
		sql.append(" clerkname,");
		sql.append(" endowment_base AS basicssum,");
		sql.append(" so_staff_sum AS staffsum,");
		sql.append(" so_org_sum AS orgsum,");
		sql.append(" mark");
		sql.append(" FROM");
		sql.append(" (SELECT t1.CLERKCODE,t1.CLERKNAME,t1.Endowment_Base,t1.so_org_sum,t1.so_staff_sum,t1.mark,T13.Name AS orgname");
		sql.append(" FROM");
		sql.append(" nc6337.V_SUM_TB_HR_SOCIAL_SECURITY t1");
		sql.append(" LEFT JOIN (SELECT t12.CLERK_CODE,t12.NC_PK_POST FROM nc6337.monthly_position_gjj t12 WHERE");
		sql.append(" t12.month = to_char( last_day( to_date( '" + period + "', 'yyyy-mm' ) ), 'yyyy-mm-dd' )");
		sql.append(" ) T12 ON t12.CLERK_CODE = t1.CLERKCODE");
		sql.append(" LEFT JOIN nc6337.om_post t14 ON t14.pk_post = t12.NC_PK_POST");
		sql.append(" LEFT JOIN nc6337.org_corp T13 ON T13.Pk_Corp = t14.pk_org");
		sql.append(" WHERE");
		sql.append(" t1.CLERKCODE NOT IN (SELECT t2.CLERKCODE FROM(SELECT t.CLERKCODE,sum( nvl( t.VALUE, 0 ) ) AS sumVALUE");
		sql.append(" FROM NC6337.v_data_xz_gjjshare t WHERE t.key IN ( '社保个人合计', '社保个人扣款' ) AND t.ym = '" + period + "' || '-01'");
		sql.append(" GROUP BY t.CLERKCODE ");
		sql.append(" ) t2 WHERE t2.sumVALUE > 0)");
		sql.append(" AND T1.PK_POST NOT IN ( SELECT T3.PK_POST FROM NC6337.om_post t3 WHERE T3.postname IN ( '残保金人员', '资质人员' ) )");
		sql.append(" AND t1.out_org IS NULL AND t1.Endowment_Base <> 0 AND t1.PAY_MONTH = '" + period + "' AND t1.ORGCODE = '" + orgCode + "'");
		sql.append(" UNION ALL SELECT");
		sql.append(" t1.CLERKCODE,t1.CLERKNAME,t1.Endowment_Base,t1.so_org_sum,t1.so_staff_sum,t1.mark,T13.Name AS orgname");
		sql.append(" FROM nc6337.V_SUM_TB_HR_SOCIAL_SECURITY_D t1 LEFT JOIN (SELECT t12.CLERK_CODE,t12.NC_PK_POST FROM");
		sql.append(" nc6337.monthly_position_gjj t12");
		sql.append(" WHERE");
		sql.append(" t12.month = to_char( last_day( to_date( '" + period + "', 'yyyy-mm' ) ), 'yyyy-mm-dd' ) ");
		sql.append(" ) T12 ON t12.CLERK_CODE = t1.CLERKCODE");
		sql.append(" LEFT JOIN nc6337.om_post t14 ON t14.pk_post = t12.NC_PK_POST");
		sql.append(" LEFT JOIN nc6337.org_corp T13 ON T13.Pk_Corp = t14.pk_org");
		sql.append(" WHERE");
		sql.append(" t1.mark LIKE '%表六%' ");
		sql.append(" AND t1.PAY_MONTH = '" + period + "' AND t1.ORGCODE = '" + orgCode + "')");
		sql.append(" ) where clerkcode ='"+clerkCode+"'");
		if(!PubAppTool.isNull(contributoryOrgName)) {
			sql.append(" AND orgname = '"+contributoryOrgName+"' AND clerkname = '"+clerkName+"'");
		}
		if (iuap.executeQuery(sql.toString(), new ColumnProcessor()) != null) {
			throw new Exception("成本归属公司:" +contributoryOrgName+ ",员工编号：" + clerkCode + ",员工姓名："+clerkName+",当月数据已存在不允许重复新增");
		}
	}
	
	/**
	 * 查询实际未缴当月工资个人部分已扣是否存在数据
	 * @param orgCode 财务组织
	 * @param period 年月
	 * @param contributoryOrgName 成本归属公司
	 * @param clerkCode 员工号
	 * @param clerkName 姓名
	 * @throws Exception
	 */
	private void queryTableSeven(String orgCode, String period, String contributoryOrgName, String clerkCode, String clerkName) throws Exception {
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT");
		sql.append(" clerkcode");
		sql.append(" FROM");
		sql.append(" (SELECT");
		sql.append(" orgname,");
		sql.append(" clerkcode,");
		sql.append(" clerkname,");
		sql.append(" endowment_base AS basicssum,");
		sql.append(" so_staff_sum AS staffsum,");
		sql.append(" so_org_sum AS orgsum,");
		sql.append(" mark");
		sql.append(" FROM");
		sql.append(" (SELECT t1.CLERKCODE,t1.CLERKNAME,t1.Endowment_Base,( t16.sumvalue - t1.so_staff_sum ) AS so_staff_sum,");
		sql.append(" 0 AS so_org_sum,T13.Name AS orgname,t1.mark");
		sql.append(" FROM");
		sql.append(" nc6337.V_SUM_TB_HR_SOCIAL_SECURITY t1");
		sql.append(" LEFT JOIN (SELECT t12.CLERK_CODE,t12.NC_PK_POST FROM nc6337.monthly_position_gjj t12 WHERE");
		sql.append(" t12.month = to_char( last_day( to_date( '" + period + "', 'yyyy-mm' ) ), 'yyyy-mm-dd' )");
		sql.append(" ) T12 ON t12.CLERK_CODE = t1.CLERKCODE");
		sql.append(" LEFT JOIN nc6337.om_post t14 ON t14.pk_post = t12.NC_PK_POST");
		sql.append(" LEFT JOIN nc6337.org_corp T13 ON T13.Pk_Corp = t14.pk_org");
		sql.append(" LEFT JOIN nc6337.person_deduction_sbgjj t16 ON t16.CLERKCODE = t1.CLERKCODE AND t1.pay_month || '-01' = t16.ym");
		sql.append(" WHERE");
		sql.append(" t1.CLERKCODE IN (SELECT t2.CLERKCODE FROM (SELECT t.CLERKCODE,sum( nvl( t.VALUE, 0 ) ) AS sumVALUE FROM");
		sql.append(" NC6337.v_data_xz_gjjshare t WHERE t.key IN ( '社保个人扣款', '社保个人合计' ) AND t.ym = '" + period + "' || '-01'");
		sql.append(" GROUP BY t.CLERKCODE");
		sql.append(" ) t2 WHERE t2.sumVALUE > 0)");
		sql.append(" AND T1.PK_POST NOT IN ( SELECT T3.PK_POST FROM NC6337.om_post t3 WHERE T3.postname IN ( '残保金人员', '资质人员' ) )");
		sql.append(" AND t1.out_org IS NULL AND t1.Endowment_Base <> 0 AND ( t16.sumvalue - t1.so_staff_sum ) > 0");
		sql.append(" AND t1.PAY_MONTH = '" + period + "' AND t1.ORGCODE = '" + orgCode + "'");
		sql.append(" UNION ALL SELECT");
		sql.append(" t1.CLERKCODE,t1.CLERKNAME,t1.Endowment_Base,t1.so_staff_sum,t1.so_org_sum,T13.Name AS orgname,t1.mark");
		sql.append(" FROM");
		sql.append(" nc6337.V_SUM_TB_HR_SOCIAL_SECURITY_D t1");
		sql.append(" LEFT JOIN (SELECT t12.CLERK_CODE,t12.NC_PK_POST FROM nc6337.monthly_position_gjj t12 WHERE");
		sql.append(" t12.month = to_char( last_day( to_date( '" + period + "', 'yyyy-mm' ) ), 'yyyy-mm-dd' ) ");
		sql.append(" ) T12 ON t12.CLERK_CODE = t1.CLERKCODE");
		sql.append(" LEFT JOIN nc6337.om_post t14 ON t14.pk_post = t12.NC_PK_POST");
		sql.append(" LEFT JOIN nc6337.org_corp T13 ON T13.Pk_Corp = t14.pk_org");
		sql.append(" WHERE");
		sql.append(" t1.mark LIKE '%表七%'");
		sql.append(" AND t1.PAY_MONTH = '" + period + "' AND t1.ORGCODE = '" + orgCode + "')");
		sql.append(" ) where clerkcode ='"+clerkCode+"'");
		if(!PubAppTool.isNull(contributoryOrgName)) {
			sql.append(" AND orgname = '"+contributoryOrgName+"' AND clerkname = '"+clerkName+"'");
		}
		if (iuap.executeQuery(sql.toString(), new ColumnProcessor()) != null) {
			throw new Exception("成本归属公司:" +contributoryOrgName+ ",员工编号：" + clerkCode + ",员工姓名："+clerkName+",当月数据已存在不允许重复新增");
		}
	}
	
	/**
	 * 查询中间表是否存在数据
	 * @param orgCode 查询组织
	 * @param period 查询期间
	 * @param combinedField 小标题名字+小标题组织+员工号+姓名组合
	 * @return
	 * @throws Exception
	 */
	private Boolean queryTable(String orgCode, String period,String combinedField) 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 = '" + combinedField + "'");
		sql.append(" AND orgcode = '" + orgCode + "' AND period = '" + period + "' ");
		if (iuap.executeQuery(sql.toString(), new ColumnProcessor()) == null) {
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * 根据组织名称查询组织编码
	 * @param orgName
	 * @return
	 * @throws Exception
	 */
	public String queyrOrgCode(String orgName) throws Exception {
		String sql = "select code from org_financeorg where name ='"+orgName+"' and enablestate = '2' and dr = 0";
		return  (String) iuap.executeQuery(sql.toString(), new ColumnProcessor());
	}
	
	/**
	 * 根据组织名称查询组织主键
	 * @param orgName
	 * @return
	 * @throws Exception
	 */
	public String queyrOrgId(String orgName) throws Exception {
		String sql = "select pk_financeorg from org_financeorg where name ='"+orgName+"' and enablestate = '2' and dr = 0";
		return  (String) iuap.executeQuery(sql.toString(), new ColumnProcessor());
	}
}
