/*
 * @(#)N_36K2_SAVE.java 2010-6-22
 * Copyright 2010 UFIDA Software CO.LTD. All rights reserved.
 */
package nc.bs.pub.action;

import java.util.Hashtable;

import nc.bs.framework.common.NCLocator;
import nc.bs.logging.Logger;
import nc.bs.sf.allocate.AllocateBR;
import nc.bs.sf.allocate.AllocateBankAccBR;
import nc.bs.sf.allocate.AllocateInnerAccBR;
import nc.bs.sf.allocate.busilog.AllocateEditBusiLog;
import nc.bs.sf.allocate.util.AllocateUtil;
import nc.bs.sf.delivery.util.GXDeliveryEventDispatcher;
import nc.bs.sf.pub.tbb.Sf4TbbControlBR;
import nc.itf.sf.allocate.IAllocateManageService;
import nc.itf.sf.pub.tbb.ISF4TbbConst;
import nc.pubitf.tmpub.util.SagasBizPubUtil;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pub.compiler.PfParameterVO;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.pf.IPfRetCheckInfo;
import nc.vo.sf.allocate.AggAllocateVO;
import nc.vo.sf.allocate.AllocateBVO;
import nc.vo.sf.allocate.AllocateEncryptVO;
import nc.vo.sf.allocate.AllocateVO;
import nc.vo.sf.allocate.IAllocateConst;
import nc.vo.sf.allocate.util.AllocatePubUtil;
import nc.vo.sf.allocate.util.AllocateVOUtil;
import nc.vo.tmpub.proxy.TMPubServiceProxy;
import nc.vo.tmpub.util.ArrayUtil;
import nc.vo.tmpub.util.DateUtil;
import nc.vo.tmpub.util.StringUtil;
import nc.vo.tmpub.util.TMBillOrgVUtils;
import nc.vo.uap.pf.PFBusinessException;
import nccloud.pubitf.sf.allocate.AllocateSagaInfoAdapter;

/**
 * TODO 下拨单保存提交动作脚本，手动录入的占帐，下拨核准生成的不预占
 * 
 * @author chengfei
 * @version 1.0 2010-6-22
 * @since NC6.0
 */
public class N_36K2_SAVE extends AllocateDiffVOActionBase {
	private final java.util.Hashtable m_methodReturnHas = new java.util.Hashtable();
	private Hashtable m_keyHas = null;

	/**
	 * N_36K2_SAVE 构造子注解。
	 */
	public N_36K2_SAVE() {
		super();
	}

	/*
	 * 备注：平台编写规则类 接口执行类
	 */
	@Override
	public AggAllocateVO runComClassImpl(PfParameterVO vo)
			throws BusinessException {

		try {
			super.m_tmpVo = vo;

			AggAllocateVO aggAllocateVO = (AggAllocateVO) this.getVo();	
			AggAllocateVO dbAggAllocateVO =  new AllocateBR().findAllocate(aggAllocateVO);
			//begin yangjn 增加单据冻结校验
			if(aggAllocateVO.getHead().getPk_allocate_h() != null){
				//单据主键不为null 说明此时为修改状态
				AllocateSagaInfoAdapter adapter = new AllocateSagaInfoAdapter();
				SagasBizPubUtil.checkFrozen(adapter, aggAllocateVO.getHead().getPk_allocate_h());
				
			}	
			//end
			this.setVo(aggAllocateVO);
			new Sf4TbbControlBR<AggAllocateVO>().writeTbbReadyData(
					dbAggAllocateVO,
					ISF4TbbConst.Direction_Negative,
					IAllocateConst.BillType_ALLOCATE);

			// 提交操作需要自己设置审批状态为提交态（或者审批进行中）
			AllocateVO allocateVO = (AllocateVO) (aggAllocateVO).getParentVO();
			AllocateBVO[] allocateBVOs = (AllocateBVO[]) (aggAllocateVO)
					.getChildrenVO();
			//对子表中的组织、集团字段进行赋值  hanlua 2013-07-02
			for (AllocateBVO allocateBVO : allocateBVOs) {
				allocateBVO.setPk_org(allocateVO.getPk_org());
				allocateBVO.setPk_group(allocateVO.getPk_group());
			}
			
			int stroke = 0;
			for (AllocateBVO allocateBVO : allocateBVOs) {
				if (allocateBVO.getStatus() != VOStatus.DELETED) {
					stroke = stroke + 1;
				}
			}
			allocateVO.setStroke(stroke);
			allocateVO.setVbillstatus(IPfRetCheckInfo.COMMIT);
			// 设置单据状态为待审批
			allocateVO.setBillstatus(IAllocateConst.BILLSTATUS_WAITAPPROVE);
			// 必须更新数据库前回写核准单下拨金额

			if (StringUtil.isNotNull(allocateVO.getDecideuser())) {
				AllocatePubUtil.setBillDateTimeByBusiDate(aggAllocateVO,
						AllocateVO.DECIDEDATE,
						new String[] { AllocateVO.DECIDETIME,
								AllocateVO.MODIFIEDTIME });
			}
			if (allocateVO.getSrcbusitype() != null
					&& allocateVO.getSrcbusitype().equals(
							IAllocateConst.SrcBusiType_Apply)) {
				new AllocateBR().writeAllocateAmount2AgreeBill(aggAllocateVO,
						true);
			}
			// 组织多版本处理，制单日期为业务日期
			TMBillOrgVUtils.setOrgV(aggAllocateVO, allocateVO.getDbilldate());

			if (aggAllocateVO.getParentVO().getStatus() != VOStatus.NEW) {
				//xug 修改前
				GXDeliveryEventDispatcher.getInstantiation("aa76ec14-f065-4394-885c-43f34f0c83c6").fireEvent("1003",aggAllocateVO);
				if (StringUtil.isNull(allocateVO.getDecideuser())) {
//					AllocatePubUtil.setBillDateTimeByBusiDate(aggAllocateVO,AllocateVO.ACCEPTDATE, new String[] { AllocateVO.DBILLTIME,AllocateVO.MODIFIEDTIME });
					String[] vls = new String[] {AllocateVO.DBILLTIME,AllocateVO.MODIFIEDTIME };
					if (!ArrayUtil.isNull(vls)) {
						UFDateTime currentTime = DateUtil.getCurrTime();
						for (String timeField : vls) {
							aggAllocateVO.getHead().setAttributeValue(timeField, currentTime);
						}
					}
				}

				allocateVO.setStatus(VOStatus.UPDATED);
				AllocateVOUtil.deleteEbankWrite(aggAllocateVO,dbAggAllocateVO);
				// 先进行验证签名
				TMPubServiceProxy.getCaLogRecordService()
						.checkPerOperationCASignatureByVO(
								dbAggAllocateVO,
								AllocateEncryptVO.class);

				aggAllocateVO = getAllocateManageService()
						.addAllocateCaSignRecord(aggAllocateVO);

				// 设置对账码
				AllocateUtil.setBankCodeAndCheckSingleForEdit(aggAllocateVO);
				aggAllocateVO = new AllocateBR().saveAllocate(aggAllocateVO);
				//登记修改业务操作日志
				new AllocateEditBusiLog().writeBusiLog(aggAllocateVO);
				//xug 修改后 资金下拨
				GXDeliveryEventDispatcher.getInstantiation("aa76ec14-f065-4394-885c-43f34f0c83c6").fireEvent("1004",aggAllocateVO);
			} else {
				//xug 新增前
				GXDeliveryEventDispatcher.getInstantiation("aa76ec14-f065-4394-885c-43f34f0c83c6").fireEvent("1001",aggAllocateVO);
//				AllocatePubUtil.setBillDateTimeByBusiDate(aggAllocateVO,AllocateVO.ACCEPTDATE, new String[] { AllocateVO.DBILLTIME,AllocateVO.CREATIONTIME });
				String[] vls = new String[] { AllocateVO.DBILLTIME,AllocateVO.CREATIONTIME };
				if (!ArrayUtil.isNull(vls)) {
					UFDateTime currentTime = DateUtil.getCurrTime();
					for (String timeField : vls) {
						aggAllocateVO.getHead().setAttributeValue(timeField, currentTime);
					}
				}
				aggAllocateVO = getAllocateManageService().addAggAllocateVO(
						aggAllocateVO);
				//xug 新增后
				GXDeliveryEventDispatcher.getInstantiation("aa76ec14-f065-4394-885c-43f34f0c83c6").fireEvent("1002",aggAllocateVO);
			}
			// 手工录入的进行内部账户、银行账处理\
			new AllocateInnerAccBR()
					.writeInnerAccRealTimeBalance(dbAggAllocateVO,aggAllocateVO,-1);
			new AllocateBankAccBR().writeBankAccRealTimeBalance(dbAggAllocateVO,aggAllocateVO);
			new Sf4TbbControlBR<AggAllocateVO>().writeTbbReadyData(
					aggAllocateVO, ISF4TbbConst.Direction_Plus,
					IAllocateConst.BillType_ALLOCATE);
			// if (allocateVO.getSrcbusitype().equals(
			// IAllocateConst.SrcBusiType_Hand)
			// || allocateVO.getSrcbusitype().equals(
			// IAllocateConst.SrcBusiType_Apply)
			// || allocateVO.getSrcbusitype().equals(
			// IAllocateConst.SrcBusiType_CommissionBack)
			// || allocateVO.getSrcbusitype().equals(
			// IAllocateConst.SrcBusiType_PS)) {
			//
			// }

			return aggAllocateVO;
		} catch (Exception ex) {
			if (ex instanceof BusinessException)
				throw (BusinessException) ex;
			else
				throw new PFBusinessException(ex.getMessage(), ex);
		}
	}

	/**
	 * 得到管理服务实现对象
	 * 
	 * @return
	 */
	public IAllocateManageService getAllocateManageService() {
		try {
			return (IAllocateManageService) NCLocator.getInstance().lookup(
					IAllocateManageService.class.getName());
		} catch (Exception ex) {
			Logger.error(ex);
			return null;
		}
	}

	/*
	 * 备注：平台编写原始脚本
	 */
	@Override
	public String getCodeRemark() {
		return "	\n";
	}

	/*
	 * 备注：设置脚本变量的HAS
	 */
	private void setParameter(String key, Object val) {
		if (m_keyHas == null) {
			m_keyHas = new Hashtable();
		}
		if (val != null) {
			m_keyHas.put(key, val);
		}
	}

}
