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.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;
	
	@SuppressWarnings("deprecation")
	public SocialInsuranceAllInsertDialog() throws Exception {
		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);
		}
		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 + "当月数据已存在不允许重新新增");
				return;
				}
				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 arg0) {
		
	}

	@Override
	public void bodyRowChange(BillEditEvent arg0) {
		
	}

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