package nc.ui.wa.ruleex.view;

import java.util.HashMap;
import java.util.Map;

import javax.swing.ListSelectionModel;

import nc.bs.logging.Logger;
import nc.hr.utils.ResHelper;
import nc.ui.hr.uif2.view.HrBillFormEditor;
import nc.ui.pub.beans.MessageDialog;
import nc.ui.pub.beans.ValueChangedEvent;
import nc.ui.pub.beans.ValueChangedListener;
import nc.ui.pub.bill.BillEditEvent;
import nc.ui.pub.bill.BillEditListener;
import nc.ui.pub.bill.BillItem;
import nc.ui.uif2.AppEvent;
import nc.ui.uif2.UIState;
import nc.ui.uif2.model.AppEventConst;
import nc.ui.wa.ruleex.formular.IWaRuleVariableFactory;
import nc.ui.wa.ruleex.model.WaRuleModel;
import nc.vo.hr.func.HrFormula;
import nc.vo.hrwa.waruleex.WageformExVO;
import nc.vo.hrwa.waruleex.WageformdetExVO;
import nccloud.commons.lang.StringUtils;

/**
 * 薪资规则表卡片界面<BR>
 * <BR>
 *
 * @author: xuhw
 * @date: 2009-11-10
 * @since: eHR V6.0
 * @走查人:
 * @走查日期:
 * @修改人:
 * @修改日期:
 */
public class WaRuleForm extends HrBillFormEditor implements BillEditListener, ValueChangedListener
{
	/**
	 * @author xuhw on 2010-4-15
	 */
	private static final long serialVersionUID = 201004150505L;
	private WaRuleFormulaRefPane referPanlFormula;
	
	private static Map<String,String> formulaToStrs = new HashMap<String,String>();

	@Override
	public void initUI()
	{
		super.initUI();
		// 去掉排序功能
		getBillCardPanel().getBillTable().removeSortListener();
		getBillCardPanel().getBillTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		//20151214 shenliangc NCdp205559130  薪资规则，新增一行后，填入数据用回车换行，第二行行号为空，保存时报错
		//去掉回车增行、子表表体右键。
		getBillCardPanel().getBodyPanel().setAutoAddLine(false);
		getBillCardPanel().getBodyPanel().setBBodyMenuShow(false);
	}
	

	@Override
	public void handleEvent(AppEvent event)
	{

		super.handleEvent(event);


		if (AppEventConst.MODEL_INITIALIZED.equalsIgnoreCase(event.getType()))
		{
			((WaRuleModel) getModel()).setAggWaGradeVos(null);
//			if (getModel().getContext().getPk_org() != null)
			{
				BillItem item = this.getBillCardPanel().getBodyItem(WageformdetExVO.VFORMULASTR);
				item.setComponent(getFormulaRefPane());
			}
		}
		
		if (AppEventConst.SHOW_EDITOR.equalsIgnoreCase(event.getType())
				||AppEventConst.SELECTED_DATE_CHANGED == event.getType()||
				AppEventConst.SELECTION_CHANGED == event.getType()|| "nc.ui.pub.bill.BillItemHyperlinkListener".equals(event.getType()))
		{
			changeNvalueDecimalDigits();
			
			int row = getBillCardPanel().getBillModel().getRowCount();
			for(int i=0;i<row;i++){
				String formula = getValueAt(i, WageformdetExVO.VFORMULA) == null ? null : getValueAt(i, WageformdetExVO.VFORMULA).toString();
				if(StringUtils.isNotEmpty(formula)){
					String value = formulaToStrs.get(formula);
					if(null==formulaToStrs.get(formula)){
					    value = getFormulaRefPane().getFormulaDialog()
								.getBusinessLang(formula);
					    formulaToStrs.put(formula, value);
					}
					//String value = getFormulaRefPane().getFormulaDialog().getBusinessLang(formula);
					getBillCardPanel().getBillModel().setValueAt(value, i, WageformdetExVO.VFORMULASTR);
				}
			}


			
			getBillCardPanel().getHeadItem(WageformExVO.IFLDDECIMAL).setEnabled(false);
			
			synchronizeDataFromModel();
	            
	        //showMeUp();
		}

		if (WaRuleModel.EVENT_COPY.equalsIgnoreCase(event.getType()))
		{
			getBillCardPanel().getHeadItem(WageformExVO.PK_ORG).setValue(getModel().getContext().getPk_org());
			changeNvalueDecimalDigits();
		}
		if (getModel().getUiState() == UIState.EDIT
				|| (getModel().getUiState() == UIState.ADD && !((WaRuleModel) getModel()).isCopyStatus())) {
			changeNvalueDecimalDigits();
		}

	}
//	
//	protected void onSelectedDataChanged() {
//		synchronizeDataFromModel();
//		showMeUp();
//	} 
	
	
	private void changeNvalueDecimalDigits(){
		Object obj = getBillCardPanel().getHeadItem(WageformExVO.IFLDDECIMAL).getValueObject();
		if(obj!=null){
			int idecimal =  (Integer)obj;
			getBillCardPanel().getBodyItem(WageformdetExVO.NVALUE).setDecimalDigits(idecimal);

		}
	}

	@Override
	public boolean canBeHidden()
	{
		if (getModel().getUiState() == UIState.ADD || getModel().getUiState() == UIState.EDIT)
		{
			return false;
		}
		return super.canBeHidden();
	}

	/**
	 * 获取条件设置参照面板
	 *
	 * @return
	 */
	protected WaRuleFormulaRefPane getFormulaRefPane()
	{
		try
		{
			if (referPanlFormula == null)
			{
				referPanlFormula = new WaRuleFormulaRefPane(getModel(), this);
				HrFormula formula = new HrFormula();
				referPanlFormula.setFormula(formula);
				referPanlFormula.setAutoCheck(false);
			}
			else
			{
				referPanlFormula.setEditorDialog();
			}
		}
		catch (Exception ex)
		{
			Logger.error(ex.getMessage(), ex);
			MessageDialog.showHintDlg(getModel().getContext().getEntranceUI(), null, ResHelper.getString("60130payrule","060130payrule0013")/*@res "获取条件设置参照面板异常。"*/);
			return null;
		}
		referPanlFormula.getUITextField().setEditable(false);
		return referPanlFormula;
	}

	@Override
	public void afterEdit(BillEditEvent e)
	{
		//编辑公式后，同时更新公式和公式显示内容字段
		if (WageformdetExVO.VFORMULASTR.equals(e.getKey()))
		{
			String ScirptLang = "";
			String busiDes = "";
			if (referPanlFormula.getFormula() != null)
			{
				ScirptLang = referPanlFormula.getFormula().getScirptLang();
				busiDes = referPanlFormula.getFormula().getBusinessLang();
			}

			if (ScirptLang != null)
			{
				if (ScirptLang.indexOf(IWaRuleVariableFactory.WA_CRITERION) != -1)
				{
					//将“@*@”去掉。  reg = @.*?@
					String regexpress = "@.*?@";
					ScirptLang = ScirptLang.replaceAll(regexpress, "");
					//ScirptLang = ScirptLang.substring(ScirptLang.lastIndexOf(IWaRuleVariableFactory.RIGHT_SEPERATOR) + 1);
				}
			}

			this.getBillCardPanel().getBillModel().setValueAt(ScirptLang, e.getRow(), WageformdetExVO.VFORMULA);
			this.getBillCardPanel().getBillModel().setValueAt(busiDes, e.getRow(), WageformdetExVO.VFORMULASTR);
		}
		//liang 编辑小数位数时，重新设置公式的值
		if(WageformExVO.IFLDDECIMAL.equals(e.getKey())){
			Object obj = getBillCardPanel().getHeadItem(WageformExVO.IFLDDECIMAL).getValueObject();
			if(obj == null ||obj.toString().length()==0){
				getBillCardPanel().getHeadItem(WageformExVO.IFLDDECIMAL).setValue("0");
			}
			int idecimal =  (Integer)getBillCardPanel().getHeadItem(WageformExVO.IFLDDECIMAL).getValueObject();
			getBillCardPanel().getBodyItem(WageformdetExVO.NVALUE).setDecimalDigits(idecimal);
		//	getBillCardPanel().getBodyItem(WageformdetVO.NVALUE).setConverter(new UFDoubleDecimalConverter(idecimal));
		}
	}

	@Override
	public void bodyRowChange(BillEditEvent e)
	{
		getBillCardPanel().stopEditing();
		int row = getBillCardPanel().getBillTable().getSelectedRow();
		HrFormula formula = new HrFormula();
		formula.setScirptLang(getValueAt(row, WageformdetExVO.VFORMULA) == null ? null : getValueAt(row, WageformdetExVO.VFORMULA).toString());
		//formula.setBusinessLang(getValueAt(row, WageformdetVO.VFORMULASTR) == null ? null : getValueAt(row, WageformdetVO.VFORMULASTR).toString());
		referPanlFormula.setFormula(formula);
	}

	private Object getValueAt(int rowIndex, String strKey)
	{
		return getBillCardPanel().getBillModel().getValueAt(rowIndex, strKey);
	}

	/**
	 * @author xuhw on 2010-6-24
	 * @see nc.ui.pub.beans.ValueChangedListener#valueChanged(nc.ui.pub.beans.ValueChangedEvent)
	 */
	@Override
	public void valueChanged(ValueChangedEvent event)
	{

	}
}