package nc.impl.fa.byzimpl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.hz.utils.BillInfoQueryUtil;
import nc.bs.hz.utils.SendUtil;
import nc.impl.pubapp.pattern.data.bill.BillQuery;
import nc.itf.fa.byzitf.IAssetInfoToByzService;
import nc.itf.fa.prv.IAlter;
import nc.itf.uap.pf.IWorkflowAdmin;
import nc.itf.uap.pf.IplatFormEntry;
import nc.itf.uap.pf.metadata.IFlowBizItf;
import nc.md.data.access.NCObject;
import nc.pubitf.para.ISysInitDAO;
import nc.util.fa.httputil.BillHttpRequestUtil;
import nc.util.fa.httputil.MD5Utils;
import nc.vo.am.addreducestyle.AddreduceStyleVO;
import nc.vo.bd.cust.CustSupplierVO;
import nc.vo.bd.defdoc.DefdocVO;
import nc.vo.bd.material.measdoc.MeasdocVO;
import nc.vo.bd.psn.PsndocVO;
import nc.vo.bd.supplier.SupplierVO;
import nc.vo.fa.alter.AlterBodyVO;
import nc.vo.fa.alter.AlterHeadVO;
import nc.vo.fa.alter.AlterSheetVO;
import nc.vo.fa.alter.AlterVO;
import nc.vo.fa.assetcard.AggCardVO;
import nc.vo.fa.assetcard.CardVO;
import nc.vo.fa.assetcard.CardhistoryVO;
import nc.vo.fa.byzLogVO.ByzLogRcordVO;
import nc.vo.fa.category.CategoryVO;
import nc.vo.fa.depmethod.DepmethodVO;
import nc.vo.fa.deptscale.DeptScaleVO;
import nc.vo.fa.sendVO.AssetcardInfoVO;
import nc.vo.fa.usingstatus.UsingStatusVO;
import nc.vo.org.DeptVO;
import nc.vo.org.FinanceOrgVO;
import nc.vo.pmpub.project.ProjectHeadVO;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.SuperVO;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.sm.UserVO;
import nc.vo.uif2.LoginContext;
import uap.json.JSONArray;
import uap.json.JSONObject;

public class AssetInfoToByzImpl implements IAssetInfoToByzService {

	private String pk_group = "0001H810000000000HS2";
//	private String pk_tradetype = "F1-Cxx-D104";
	private String pk_currtype = "1002Z0100000000001K1";

	@Override
	public String sendArc(AggCardVO[] aggvoss) throws Exception {
		String result = null;
		// 因为报文字段超长度，批量传递时，分成每50个卡片传一次
		int splitSize = 50;// 分割的块大小
		Object[] subAry = splitAry(aggvoss, splitSize);// 分割后的子块数组
		for (Object obj : subAry) {
			AggCardVO[] aggvos = (AggCardVO[]) obj;
			String[] type = new String[] { "handin", "4A00", "HJ-01", "HJ-02", "HO", "HM", "HC", "HD" };
			List<String> typeList = new ArrayList<>(Arrays.asList(type));
			AssetcardInfoVO[] cardInfoVOs = new AssetcardInfoVO[aggvos.length];
			List<String> pk = new ArrayList<String>();
			List<String> code = new ArrayList<String>();
			// 日志vo
			ByzLogRcordVO logvo = new ByzLogRcordVO();
			logvo.setItf_type("资产卡片同步ARC");
			logvo.setItfclass("nc.itf.fa.byzitf.IAssetcardInfoSendToBYZ");
			int k = 0;
			for (AggCardVO aggvo : aggvos) {

				AssetcardInfoVO cardInfoVO = new AssetcardInfoVO();
				CardVO headvo = (CardVO) aggvo.getParentVO();
				// 处理def21,有时候模板传进来def21默认Y
//				headvo.setDef21("N");
				// 公司过滤，部分公司不对接ARC
				if (!BillInfoQueryUtil.isARC(headvo.getPk_org()))
					continue;
				/*
				 * 只同步handin=手工录入;4A00=设备卡片生成;HJ-01=工程转固单;HJ-02=采购转固单;HO=资产合并；HM=资产拆分
				 * ;HD=调入;HC=调出才同步给碧优资， 其他的来源不同步
				 */
				if (!typeList.contains(headvo.getBill_source()))
					continue;
				if (headvo.getBill_source().equals("HD") || headvo.getBill_source().equals("HO")
						|| headvo.getBill_source().equals("HM") || headvo.getBill_source().equals("HC")) {
					if (!"IDISARC".equals(headvo.getDef70())) {
						continue;
					}
				}

				SuperVO[] supervos = (SuperVO[]) aggvo.getChildren(CardhistoryVO.class);
				CardhistoryVO[] cardhistoryvos = new CardhistoryVO[supervos.length];
				boolean flag = false;
				for (int i = 0; i < supervos.length; i++) {
					cardhistoryvos[i] = (CardhistoryVO) supervos[i];
					// 只同步在役状态
					if (!"exist".equals(cardhistoryvos[i].getAsset_state())) {
						flag = true;
						break;
					}
					//只取laststate_flag =Y,modefy by djy20220317
					if(cardhistoryvos[i].getLaststate_flag()!=null
							&&!cardhistoryvos[i].getLaststate_flag().booleanValue())
						continue;	
				}

				if (flag)
					continue;

				if (headvo.getBill_source().equals("HD"))
					cardInfoVO.setPk_oldcard(BillInfoQueryUtil.getOldPk(headvo.getPk_card()));

				Set<String> nameset = new HashSet<>();
				for (Field field : cardInfoVO.getClass().getDeclaredFields()) {
					nameset.add(field.getName());
				}

				// 资产卡片表头信息映射
				for (Field field : headvo.getClass().getDeclaredFields()) {
					field.setAccessible(true);
					String name = field.getName();
					if (nameset.contains(name)) {
						name = name.substring(0, 1).toUpperCase() + name.substring(1);
						Method m = cardInfoVO.getClass().getMethod("set" + name, String.class);
						m.invoke(cardInfoVO, field.get(headvo) == null ? "" : field.get(headvo) + "");
					}
				}

				// 资产卡片多账簿历史信息映射
				for (Field field : cardhistoryvos[0].getClass().getDeclaredFields()) {
					field.setAccessible(true);
					String name = field.getName();
					if (nameset.contains(name)) {
						name = name.substring(0, 1).toUpperCase() + name.substring(1);
						Method m = cardInfoVO.getClass().getMethod("set" + name, String.class);
						m.invoke(cardInfoVO,
								field.get(cardhistoryvos[0]) == null ? "" : field.get(cardhistoryvos[0]) + "");
					}
				}

				// 处理没有映射字段
				cardInfoVO = handItemNotinvoke(cardInfoVO);
				cardInfoVOs[k] = cardInfoVO;
				pk.add(headvo.getPk_card());
				code.add(headvo.getAsset_code());
				k++;
			}

			JSONObject sendjson = createJson(cardInfoVOs);
			if (sendjson.getJSONArray("data").length() == 0)
				return null;
			ISysInitDAO InitDAO = NCLocator.getInstance().lookup(ISysInitDAO.class);
			String url = InitDAO.getSysInitTempVO("cardtobyz").getDefaultvalue();
			logvo.setPk_bill(pk.toString());
			logvo.setVbillcode(code.toString());
			logvo.setNcctobyzparam(SendUtil.unicodeToString(sendjson.toString()));
			logvo.setItfaddress(url);

			// 发送数据
			result = BillHttpRequestUtil.sendPost(url, SendUtil.unicodeToString(sendjson.toString()));
			JSONObject rejson = new JSONObject(result);
			try {
				if (rejson.getInt("code") == 500)
					throw new BusinessException("ARC返回信息：" + rejson.getString("msg"));
				// 打上单据标识
				BillInfoQueryUtil.updateStatus("H0", pk.toArray(new String[0]));
			} catch (Exception e) {
				ExceptionUtils.wrappBusinessException(e.getMessage());
			} finally {
				logvo.setByztonccresult(rejson.getString("msg"));
				BillInfoQueryUtil.insertlog(logvo);
			}
		}
		return result;
	}

	// 处理没有映射字段
	public AssetcardInfoVO handItemNotinvoke(AssetcardInfoVO cardInfoVO) {
		/*
		 * 固定资产净值=期末固定资产原值-期末累计折旧 固定资产净额=固定资产原值-累计折旧-减值准备
		 */
		UFDouble jz = new UFDouble(cardInfoVO.getLocaloriginvalue() == null ? "0.00" : cardInfoVO.getLocaloriginvalue())
				.sub(new UFDouble(cardInfoVO.getAccudep() == null ? "0.00" : cardInfoVO.getAccudep()));
		cardInfoVO.setNetvalue(jz.toString());

		UFDouble je = new UFDouble(cardInfoVO.getLocaloriginvalue() == null ? "0.00" : cardInfoVO.getLocaloriginvalue())
				.sub(new UFDouble(cardInfoVO.getAccudep() == null ? "0.00" : cardInfoVO.getAccudep()))
				.sub(new UFDouble(cardInfoVO.getPredevaluate() == null ? "0.00" : cardInfoVO.getPredevaluate()));
		cardInfoVO.setNetrating(je.toString());

		MeasdocVO meaddocvo = BillInfoQueryUtil.selectMeasdoc(cardInfoVO.getMeasureunit());
		if (meaddocvo != null)
			cardInfoVO.setMeasureunit(meaddocvo.getName());
		FinanceOrgVO finaceorgvo = BillInfoQueryUtil.selectOrg(cardInfoVO.getPk_org());
		if (finaceorgvo != null) {
			cardInfoVO.setOrg_orgs_code(finaceorgvo.getCode());
			cardInfoVO.setOrg_orgs_name(finaceorgvo.getName());
		}

		DefdocVO defdocvo = BillInfoQueryUtil.selectDefVO(cardInfoVO.getDef13());
		if (defdocvo != null) {
			cardInfoVO.setLegal_person_code(defdocvo.getCode());
			cardInfoVO.setLegal_person_name(defdocvo.getName());
		}
		AddreduceStyleVO stylevo = BillInfoQueryUtil.selectAddreducestyle(cardInfoVO.getPk_addreducestyle());
		if (stylevo != null)
			cardInfoVO.setPk_addreducestyle(stylevo.getStyle_code());

		SupplierVO supplervo = BillInfoQueryUtil.selectSupplier(cardInfoVO.getProvider());
		if (supplervo != null) {
			cardInfoVO.setProvider_code(supplervo.getCode());
			cardInfoVO.setProvider_name(supplervo.getName());
		}

		DeptVO deptvo = BillInfoQueryUtil.selectUserDept(cardInfoVO.getPk_usedept());
		if (deptvo != null) {
			cardInfoVO.setPk_usedept_code(deptvo.getCode());
			cardInfoVO.setPk_usedept_name(deptvo.getName());
		}

		DeptVO gdeptvo = BillInfoQueryUtil.selectDept(cardInfoVO.getPk_mandept());
		if (gdeptvo != null) {
			cardInfoVO.setPk_mandept_code(gdeptvo.getCode());
			cardInfoVO.setPk_mandept_name(gdeptvo.getName());
		}

		CategoryVO categoryVO = BillInfoQueryUtil.selectCategory(cardInfoVO.getPk_category());
		if (categoryVO != null)
			cardInfoVO.setPk_category(categoryVO.getCate_code());
		UsingStatusVO usingStatusVO = BillInfoQueryUtil.selectUsingstatus(cardInfoVO.getPk_usingstatus());
		if (usingStatusVO != null)
			cardInfoVO.setPk_usingstatus(usingStatusVO.getStatus_name());

		DepmethodVO depmethodVO = BillInfoQueryUtil.selectDepmethod(cardInfoVO.getPk_depmethod());
		if (depmethodVO != null)
			cardInfoVO.setPk_depmethod(depmethodVO.getDepmethod_code());

		ProjectHeadVO projectvo = BillInfoQueryUtil.selectProject(cardInfoVO.getPk_jobmngfil());
		if (projectvo != null) {
			cardInfoVO.setBd_project_code(projectvo.getProject_code());
			cardInfoVO.setBd_project_name(projectvo.getProject_name());
			cardInfoVO.setBd_project_erp(projectvo.getDef6());
		}

		UserVO userVO = BillInfoQueryUtil.selectUser(cardInfoVO.getBillmaker());
		if (userVO != null) {
			cardInfoVO.setBillmaker(userVO.getUser_name());
		}

		UserVO usermodefyVO = BillInfoQueryUtil.selectUser(cardInfoVO.getModifier());
		if (usermodefyVO != null) {
			cardInfoVO.setBillmaker(usermodefyVO.getUser_name());
		}

		CustSupplierVO custCbSupplierVO = BillInfoQueryUtil.selectCustsupplier(cardInfoVO.getContrator());
		if (custCbSupplierVO != null) {
			cardInfoVO.setContrator(custCbSupplierVO.getName());
		}

		CustSupplierVO custPrSupplierVO = BillInfoQueryUtil.selectCustsupplier(cardInfoVO.getProducer());
		if (custPrSupplierVO != null) {
			cardInfoVO.setProducer(custPrSupplierVO.getName());
		}
		cardInfoVO.setPk_currency(BillInfoQueryUtil.getBdcurrtypename(cardInfoVO.getPk_currency()));

		PsndocVO psvo = BillInfoQueryUtil.selectPsndoc(cardInfoVO.getPk_assetuser());
		if (psvo != null) {
			cardInfoVO.setPk_assetuser_code(psvo.getCode());
			cardInfoVO.setPk_assetuser_name(psvo.getName());
		}

		return cardInfoVO;
	}

	public JSONObject createJson(AssetcardInfoVO[] cardInfoVOs) {
		try {
			ISysInitDAO InitDAO = NCLocator.getInstance().lookup(ISysInitDAO.class);
			Map<String, Object> sendMap = new HashMap<String, Object>();

			List<JSONObject> sendmapList = new ArrayList<JSONObject>();
			for (AssetcardInfoVO cardInfoVO : cardInfoVOs) {
				if (cardInfoVO != null)
					sendmapList.add(new JSONObject(getSendMap(cardInfoVO)));
			}

			JSONArray jsonArray = new JSONArray(sendmapList);

//			jsonArray.put(new JSONObject(getSendMap(cardInfoVO)));
			long timestamp = System.currentTimeMillis();
			String key = InitDAO.getSysInitTempVO("appkey").getDefaultvalue();
			String appid = InitDAO.getSysInitTempVO("appid").getDefaultvalue();
//			JSONObject vojsonobject = (JSONObject) JSONObject.toJSON(cardInfoVO);
			sendMap.put("appid", appid);
			sendMap.put("time", timestamp);
			sendMap.put("token", MD5Utils.MD5Upper(appid + key + timestamp));
//			sendjsonobject.put("data", Base64Util.encode(jsonArray.toString()));
			sendMap.put("data", jsonArray);
			JSONObject sendjsonobject = new JSONObject(sendMap);
			return sendjsonobject;
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return null;
	}

	@Override
	public AlterVO assetCardRecBYZ(JSONObject jsonobjet) throws Exception {
		JSONObject jsonohead = jsonobjet.getJSONObject("head");
		AlterVO aggvoAlter = new AlterVO();
		AlterHeadVO headvoAlter = new AlterHeadVO();
		String pk_org = jsonohead.getString("pk_org_v");
		// 初始化
		BillInfoQueryUtil.initEnvironment("0001H810000000000HS2", new UFDate(jsonohead.getString("business_date")));
		BillInfoQueryUtil.initSysBilltypeCache(new String[] { "HG", "H0", "HG-00", "HZ" });
		LoginContext context = new LoginContext();
		context.setPk_group(InvocationInfoProxy.getInstance().getGroupId());
		context.setPk_loginUser(InvocationInfoProxy.getInstance().getUserId());

		FinanceOrgVO finaceorgvo = BillInfoQueryUtil.selectOrg(pk_org);
//		InvocationInfoProxy.getInstance().setGroupId(pk_group);
		List<String> showAlterKeyList = new ArrayList<String>();
		String[] type = new String[] { "BD60", "BD10", "BD07", "BD08", "BD05", "BD16", "BD23", "BD27" };
		List<String> typeList = new ArrayList<>(Arrays.asList(type));

		headvoAlter.setPk_org(pk_org);
		headvoAlter.setPk_org_v(finaceorgvo.getPk_vid());
//		headvoAlter.setBusiness_date(new UFDate(jsonohead.getString("business_date").substring(0, 10)));
		headvoAlter.setBusiness_date(new UFDate(jsonohead.getString("business_date")));
		headvoAlter.setBillmaker(BillInfoQueryUtil.getPK_syscreater());
		headvoAlter.setCreator(BillInfoQueryUtil.getPK_syscreater());
		headvoAlter.setCreationtime(new UFDateTime());
		headvoAlter.setBill_type("HG");
		headvoAlter.setBill_status(0);
		headvoAlter.setPk_transitype(BillInfoQueryUtil.getPk_tradetype("HG-00"));
		headvoAlter.setDef1(jsonohead.getString("def1"));
		headvoAlter.setDef4(jsonohead.getString("def4"));
		headvoAlter.setBillmaketime(new UFDateTime());
		headvoAlter.setTransi_type("HG-00");
		headvoAlter.setPk_group(pk_group);

		JSONArray bodys = jsonobjet.getJSONArray("bodys");
		AlterBodyVO[] alterbody = new AlterBodyVO[bodys.length()];

		for (int i = 0; i < bodys.length(); i++) {
			JSONObject body = (JSONObject) bodys.get(i);
			AlterBodyVO bodyvo = new AlterBodyVO();
			String pk_card = body.getString("pk_card");
			bodyvo.setPk_org(pk_org);
			bodyvo.setPk_org_v(finaceorgvo.getPk_vid());
			bodyvo.setIstrace(UFBoolean.FALSE);
			bodyvo.setPk_currency(pk_currtype);
			bodyvo.setPk_card(pk_card);
			bodyvo.setPk_reason(BillInfoQueryUtil.getFa_reason(body.getString("pk_reason")));
			bodyvo.setPk_group(pk_group);
			JSONArray items = body.getJSONArray("items");
			AlterSheetVO[] altersheet = new AlterSheetVO[items.length()];
			for (int j = 0; j < items.length(); j++) {
				AlterSheetVO sheetvo = new AlterSheetVO();
				JSONObject item = (JSONObject) items.get(j);
				// 获取对应的变项目值
				if (!typeList.contains(item.get("pk_fa_alters")))
					throw new BusinessException("变动类型：" + item.get("pk_fa_alters") + "不在财务允许的范围内");

				String value = BillInfoQueryUtil.getAlterItemValue().get(item.get("pk_fa_alters"));
				showAlterKeyList.add(value);
				if ("pk_assetuser".equals(value)) {
					if (item.getString("pk_name_before") != null && !"".equals(item.getString("pk_name_before")))
						bodyvo.setAttributeValue(value + "_before",
								BillInfoQueryUtil.getPsndoc(item.getString("pk_name_before")));
					if (item.getString("pk_name_after") != null && !"".equals(item.getString("pk_name_after")))
						bodyvo.setAttributeValue(value + "_after",
								BillInfoQueryUtil.getPsndoc(item.getString("pk_name_after")));
				} else if ("pk_jobmngfil".equals(value)) {
					if (item.getString("pk_name_before") != null && !"".equals(item.getString("pk_name_before")))
						bodyvo.setAttributeValue(value + "_before",
								BillInfoQueryUtil.selectErpProject(item.getString("pk_name_before")));
					if (item.getString("pk_name_after") != null && !"".equals(item.getString("pk_name_after")))
						bodyvo.setAttributeValue(value + "_after",
								BillInfoQueryUtil.selectErpProject(item.getString("pk_name_after")));
				} else if ("pk_usingstatus".equals(value)) {
					if (item.getString("pk_name_before") != null && !"".equals(item.getString("pk_name_before")))
						bodyvo.setAttributeValue(value + "_before",
								BillInfoQueryUtil.selectUsingstatusCode(item.getString("pk_name_before")));
					if (item.getString("pk_name_after") != null && !"".equals(item.getString("pk_name_after")))
						bodyvo.setAttributeValue(value + "_after",
								BillInfoQueryUtil.selectUsingstatusCode(item.getString("pk_name_after")));
				} else if ("usedept".equals(value) || "pk_mandept_v".equals(value)) {
					if (item.getString("pk_name_before") != null && !"".equals(item.getString("pk_name_before")))
						if ("usedept".equals(value)) {
							String lin = BillInfoQueryUtil.getFaCardHistory(pk_card).getPk_usedept();
							bodyvo.setOld_deptscalevos(new DeptScaleVO[] { BillInfoQueryUtil.selectScDept(lin) });
							bodyvo.setAttributeValue(value + "_before", lin);
						} else
							bodyvo.setAttributeValue(value + "_before",
									BillInfoQueryUtil.selectPDept(item.getString("pk_name_before"), pk_org));
					if (item.getString("pk_name_after") != null && !"".equals(item.getString("pk_name_after")))
						if ("usedept".equals(value)) {
							DeptScaleVO scalevo = new DeptScaleVO();
							scalevo.setTotalscale(UFDouble.ZERO_DBL);
							scalevo.setUsescale(new UFDouble(100));
							scalevo.setPk_dept(BillInfoQueryUtil.selectPDept(item.getString("pk_name_after"),pk_org));
							bodyvo.setNew_deptscalevos((new DeptScaleVO[] { scalevo }));
						} else
							bodyvo.setAttributeValue(value + "_after",
									BillInfoQueryUtil.selectPDept(item.getString("pk_name_after"), pk_org));

				} else if ("pk_assetuser".equals(value)) {
					if (item.getString("pk_name_before") != null && !"".equals(item.getString("pk_name_before")))
						bodyvo.setAttributeValue(value + "_before",
								BillInfoQueryUtil.getPsndoc(item.getString("pk_name_before")));
					if (item.getString("pk_name_after") != null && !"".equals(item.getString("pk_name_after")))
						bodyvo.setAttributeValue(value + "_after",
								BillInfoQueryUtil.getPsndoc(item.getString("pk_name_after")));
				} else {
					if (item.getString("pk_name_before") != null && !"".equals(item.getString("pk_name_before")))
						bodyvo.setAttributeValue(value + "_before", item.getString("pk_name_before"));
					if (item.getString("pk_name_after") != null && !"".equals(item.getString("pk_name_after")))
						bodyvo.setAttributeValue(value + "_after", item.getString("pk_name_after"));
				}

				altersheet[j] = sheetvo;
			}
			bodyvo.setAltersheetvos(altersheet);
			alterbody[i] = bodyvo;
		}
		aggvoAlter.setParentVO(headvoAlter);
		aggvoAlter.setChildrenVO(alterbody);

		aggvoAlter.setShowAlterKeyList(showAlterKeyList);
		// 保存
		NCLocator.getInstance().lookup(IAlter.class).insert(null, aggvoAlter, showAlterKeyList);
		boolean approvalProcess = nccloud.bs.pub.pf.CloudPfUtil.hasApproveflowDef("HG-00", aggvoAlter);
		// 提交
		if (approvalProcess)
			NCLocator.getInstance().lookup(IplatFormEntry.class).processAction("SAVE", "HG", null, aggvoAlter, null,
					null);
		else {
			BillQuery<AlterVO> query = new BillQuery<AlterVO>(AlterVO.class);
			AlterVO[] newagg = query.query(new String[] { aggvoAlter.getPrimaryKey() });
			NCLocator.getInstance().lookup(IplatFormEntry.class).processAction("APPROVE", "HG", null, newagg[0], null,
					null);
		}
		return aggvoAlter;
	}

	public Map<String, String> getSendMap(AssetcardInfoVO cardInfoVO)
			throws IllegalArgumentException, IllegalAccessException {
		Map<String, String> map = new HashMap<String, String>();
		for (Field field : cardInfoVO.getClass().getDeclaredFields()) {
			field.setAccessible(true);
			map.put(field.getName(), field.get(cardInfoVO) == null ? "" : field.get(cardInfoVO) + "");
		}
		return map;
	}

	@Override
	public void terminateWorkflow(AggregatedValueObject aggvo, int iWorkflowtype) throws BusinessException {
		// TODO Auto-generated method stub
		NCObject ncObj = NCObject.newInstance(aggvo);
		IFlowBizItf itf = (IFlowBizItf) ncObj.getBizInterface(IFlowBizItf.class);

		NCLocator.getInstance().lookup(IWorkflowAdmin.class).terminateWorkflow(itf.getBillId(),
				itf.getTranstype() == null ? itf.getBilltype() : itf.getTranstype(), itf.getBillNo(), iWorkflowtype);
	}

	private static Object[] splitAry(AggCardVO[] ary, int subSize) {
		int count = ary.length % subSize == 0 ? ary.length / subSize : ary.length / subSize + 1;

		List<List<AggCardVO>> subAryList = new ArrayList<List<AggCardVO>>();

		for (int i = 0; i < count; i++) {
			int index = i * subSize;
			List<AggCardVO> list = new ArrayList<AggCardVO>();
			int j = 0;
			while (j < subSize && index < ary.length) {
				list.add(ary[index++]);
				j++;
			}
			subAryList.add(list);
		}

		Object[] subAry = new Object[subAryList.size()];

		for (int i = 0; i < subAryList.size(); i++) {
			List<AggCardVO> subList = subAryList.get(i);
			AggCardVO[] subAryItem = new AggCardVO[subList.size()];
			for (int j = 0; j < subList.size(); j++) {
				subAryItem[j] = subList.get(j);
			}
			subAry[i] = subAryItem;
		}
		return subAry;
	}
}
