package nc.ui.wa.ruleex.action;

import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;

import nc.hr.utils.ResHelper;
import nc.ui.hr.uif2.action.HrAction;
import nc.ui.hr.uif2.action.SaveAction;
import nc.ui.pub.beans.MessageDialog;
import nc.ui.uif2.IShowMsgConstant;
import nc.ui.uif2.ShowStatusBarMsgUtil;
import nc.ui.uif2.UIState;
import nc.ui.wa.ruleex.model.WaRuleModel;
import nc.ui.wa.ruleex.view.WaRuleForm;
import nc.vo.hrwa.waruleex.AggWageformExVO;
import nc.vo.hrwa.waruleex.WageformExVO;
import nc.vo.hrwa.waruleex.WageformdetExVO;

/**
 * WaRuleSaveAction<BR>
 * <BR>
 *
 * @author: xuhw
 * @date: 2009-11-10
 * @since: eHR V6.0
 * @走查人:
 * @走查日期:
 * @修改人:
 * @修改日期:
 */
public class WaRuleSaveAction extends SaveAction
{
	@Override
	public void doAction(ActionEvent e) throws Exception
	{
		Object value = getEditor().getValue();
		validate(value);
		WaRuleModel waRuleModel = (WaRuleModel) getModel();
		try
		{
			((WaRuleForm) getEditor()).getBillCardPanel().stopEditing();
			// 重新整合聚合vo
			WageformdetExVO[] wageRuleVOArr = (WageformdetExVO[]) ((WaRuleForm) getEditor()).getBillCardPanel().getBillModel().getBodyValueVOs(WageformdetExVO.class.getName());
			if (wageRuleVOArr == null || wageRuleVOArr.length == 0)
			{
				ShowStatusBarMsgUtil.showErrorMsg(ResHelper.getString("60130adjmtc", "060130adjmtc0241")/*保存失败！*/, ResHelper.getString("60130payrule","060130payrule0006")/*@res "表体数据不能为空！"*/, getContext());
				putValue(HrAction.MESSAGE_AFTER_ACTION, ResHelper.getString("60130adjmtc", "060130adjmtc0241")/*保存失败！*/);
				return;
			}
			checkSameRule(wageRuleVOArr);
			waRuleModel.reMakeAggVO(value, wageRuleVOArr);
			if (waRuleModel.isCopyStatus())
			{
				// 复制表状态
				// 设置组织
				((WageformExVO) ((AggWageformExVO) value).getParentVO()).setPk_org(getModel().getContext().getPk_org());
				waRuleModel.copyTable(value);
			}
			else if (waRuleModel.getUiState() == UIState.ADD)
			{
				// 新增
				waRuleModel.add(value);
			}
			else if (getModel().getUiState() == UIState.EDIT)
			{
				// 修改
				waRuleModel.update(value);
			}
			// 复制成功后，清空复制表标识
			waRuleModel.setCopyStatus(false);
			waRuleModel.setUiState(UIState.NOT_EDIT);
//			ShowStatusBarMsgUtil.showStatusBarMsg(IShowMsgConstant.getSaveSuccessInfo(), getContext());
		}
		finally
		{
			// 清空Model中的缓存
			waRuleModel.clear();
		}
		putValue(HrAction.MESSAGE_AFTER_ACTION, IShowMsgConstant.getSaveSuccessInfo());
	}

	private void checkSameRule(WageformdetExVO[] wageRuleVOArr){
		Map<String,WageformdetExVO> map = new HashMap<String,WageformdetExVO>();
		for(int i = 0 ;i<wageRuleVOArr.length;i++){
			if(map.containsKey(wageRuleVOArr[i].getVformula())){
				MessageDialog.showHintDlg(getModel().getContext().getEntranceUI(), null, ResHelper.getString("60130payrule","060130payrule0007")/*@res "规则公式中存在重复的公式。"*/);
				return;
			}
			map.put(wageRuleVOArr[i].getVformula(), wageRuleVOArr[i]);
		}
	}
}