package nc.itf.fa.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nc.vo.org.OrgVO;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.comn.NetStreamContext;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.bs.hz.utils.BillInfoQueryUtil;
import nc.bs.hz.utils.SafeObject;
import nc.bs.hz.utils.SendUtil;
import nc.bs.logging.Logger;
import nc.impl.am.db.BillPersistUtil;
import nc.impl.pubapp.pattern.data.bill.BillQuery;
import nc.itf.fa.byzlog.IbyzLogRcord;
import nc.itf.fa.prv.IDeployOut;
import nc.itf.fa.service.IAssetService;
import nc.itf.uap.IUAPQueryBS;
import nc.itf.uap.pf.IPFBusiAction;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.BeanProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.pub.fa.common.manager.VOManager;
import nc.pub.fa.common.util.UseDeptScaleUtils;
import nc.util.fa.httputil.Base64Util;
import nc.util.fa.httputil.BeanUtils;
import nc.vo.am.common.TransportBillVO;
import nc.vo.am.common.util.CollectionUtils;
import nc.vo.am.manager.AccbookManager;
import nc.vo.am.proxy.AMProxy;
import nc.vo.fa.asset.AssetVO;
import nc.vo.fa.assetcard.CardVO;
import nc.vo.fa.assetcard.CardhistoryVO;
import nc.vo.fa.byzLogVO.ByzLogRcordVO;
import nc.vo.fa.deployin.DeployInBodyVO;
import nc.vo.fa.deployin.DeployInHeadVO;
import nc.vo.fa.deployin.DeployInVO;
import nc.vo.fa.deployout.DeployOutHeadVO;
import nc.vo.fa.deployout.DeployOutVO;
import nc.vo.fa.depmethod.DepmethodVO;
import nc.vo.fa.deptscale.DeptScaleVO;
import nc.vo.org.DeptVO;
import nc.vo.org.FinanceOrgVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.uif2.LoginContext;
import nccloud.framework.service.ServiceLocator;
import nccloud.pub.ampub.script.IAppScript4Cloud;
import nccloud.pubitf.pub.pflow.CloudPFlowParamUtil;
import uap.json.JSONArray;
import uap.json.JSONObject;

public class ByzSysAmCallInServlet implements IHttpServletAdaptor {
	IUAPQueryBS service = NCLocator.getInstance().lookup(IUAPQueryBS.class);
	private BaseDAO dao;
	String def1org=null;
	String outorg;
	
	private BaseDAO getDao() {
		if (dao == null)
			dao = new BaseDAO();
		return dao;
	}

	@Override
	public void doAction(HttpServletRequest arg0, @SuppressWarnings("restriction") HttpServletResponse arg1)
			throws ServletException, IOException {
		ISecurityTokenCallback tc = NCLocator.getInstance().lookup(ISecurityTokenCallback.class);
		byte[] tokens = tc.token("__system".getBytes(), "NC".getBytes());
		NetStreamContext.setToken(tokens);
//		NCLocator.getInstance().lookup(ISecurityTokenCallback.class).token("NCSystem".getBytes(), "pfxx".getBytes());
//		InvocationInfoProxy.getInstance().setGroupId("0001H810000000000HS2");
		JSONObject json = null;
		JSONObject reqJson = null;
		DeployInHeadVO hvo = null;
		DeployInBodyVO[] bvo = null;
		String billno = "";
		try {
			json = new JSONObject(requestJson(arg0));
			String checkItemHead[] = new String[] { "def10", "pk_org", "def15", "pk_org_out", "def13", "business_date",
					"deployer", "reason", "pk_bill_src", "bill_code_out", "confirm_flag", "account_currency",
					"billmaketime", "creator", "creationtime", "modifier", "modifiedtime", "def1", "def2" };
			String checkItemBody[] = new String[] { "pk_card_out", "pk_category", "pk_addreducestyle", "pk_mandept",
					"pk_usedept", "pk_usingstatus", "pk_bill_src", "pk_bill_b_src", "business_flag", "paydept_flag",
					"bar_code", "pk_currency", "remark" };
			String head = json.getJSONObject("data").getJSONObject("head").toString();
			String body = json.getJSONObject("data").getJSONArray("bodys").toString();
			// 集团主键可固定：0001H810000000000HS2，单据日期为报文中的单据日期，初始化位置放在查询动作、调用接口或后台脚本之前
			BillInfoQueryUtil.initEnvironment("0001H810000000000HS2",
					new UFDate(new JSONObject(head).getString("business_date")));
			BillInfoQueryUtil.initSysBilltypeCache(new String[] { "HG", "HF", "HC", "HC-01", "HD", "HD-01" });// 有多少个相关的单据类型就要初始化多少个

			checkNeedItem(head, checkItemHead, true);// 校验
			hvo = getHeadVO(head);
			def1org=hvo.getPk_org();
			outorg=hvo.getPk_org_out();
			bvo = getBodyVO(body, checkItemBody);
			DeployInVO aggvo = new DeployInVO();
			aggvo.setParent(hvo);
			aggvo.setChildrenVO(bvo);

			selectAsset_state(aggvo);/**
										 * 校验资产卡片状态是否 调拨在途此校验; 此校验在nc.impl.fa.deployin.DeployInAssetGenerator已有 无法校验则会报
										 * 空指针 无法明确异常，故而再此再进行一次校验
										 */

			LoginContext context = new LoginContext();
			context.setPk_group(InvocationInfoProxy.getInstance().getGroupId());
			context.setPk_loginUser(InvocationInfoProxy.getInstance().getUserId());
			NCLocator.getInstance().lookup(nc.itf.fa.prv.IDeployIn.class).insert(context, aggvo);
			String pk = aggvo.getPrimaryKey();
			DeployInVO ideployIn = NCLocator.getInstance().lookup(nc.itf.fa.prv.IDeployIn.class).queryDeployInVOByPK(pk,
					true);
            
			// 重新更新调出单VO
			JSONObject object = new JSONObject(head);
			String pk_ouy = object.getString("pk_bill_src");
			updateOutVO(pk_ouy, ideployIn);

			// modefy by djy 20220305 方案更改调入不要审批流，直接审批通过态
//			boolean approvalProcess  =nccloud.bs.pub.pf.CloudPfUtil.hasApproveflowDef("HD-01", ideployIn);
//			if(!approvalProcess) {//如果没有审批流
			IPFBusiAction baService = (IPFBusiAction) NCLocator.getInstance().lookup(IPFBusiAction.class.getName());
			baService.processAction("APPROVE", "HD", null, aggvo, context, null);
//			}else {
//				IPFBusiAction baService = (IPFBusiAction) NCLocator.getInstance().lookup(IPFBusiAction.class.getName());
//				baService.processAction("SAVE", "HD", null, aggvo,context, null);
//			}

			// add by djy 20220305完成整条流程才能告诉ARC调入单审批成功：调入单保存---新的资产产生---调入单终审完成
			if (isCreatNewCard(aggvo))
				throw new BusinessException("调入单审批后没有生成新的资产卡片");

			reqJson = new JSONObject();
			billno = (String) aggvo.getParentVO().getAttributeValue("bill_code");
			reqJson.put("status", 1);
			reqJson.put("billpk", aggvo.getPrimaryKey());
			reqJson.put("billno", billno);
			//modefy by djy20220318
			reqJson.put("guid", aggvo.getParentVO().getAttributeValue("def11"));
			reqJson.put("message", "资产调入单据生成成功");

		} catch (Exception e) {
			reqJson = new JSONObject();
			reqJson.put("status", 0);
			reqJson.put("message", "资产调入单据生成失败：" + e.getMessage());
			ExceptionUtils.wrappBusinessException(e.getMessage());
		} finally {
			responseWriter(arg1, reqJson + "");
			IbyzLogRcord ibyzLogRcord = (IbyzLogRcord) NCLocator.getInstance().lookup(IbyzLogRcord.class);
			ByzLogRcordVO byzLogRcordVO = new ByzLogRcordVO();
			byzLogRcordVO.setItf_type("资产调入");
			byzLogRcordVO.setVbillcode(billno);
			byzLogRcordVO.setItfclass("nc.itf.fa.servlet.ByzSysAmCallInServlet");
			byzLogRcordVO.setItfaddress(arg0.getRequestURL() + "");
			byzLogRcordVO.setByztonccparam(SendUtil.unicodeToString(json.toString()));
			byzLogRcordVO.setNcctobyzresult(SendUtil.unicodeToString(reqJson.toString()));
			try {
				ibyzLogRcord.RcordLogBYZ__RequiresNew(byzLogRcordVO);
			} catch (BusinessException e) {
				ExceptionUtils.wrappBusinessException(e.getMessage());
				Logger.error(e.getMessage(), e);
				Logger.error("日志生成失败！！nc.itf.fa.byzlog.IbyzLogRcord");
			}

		}

		String data = Base64Util.decode(json.getString("data"));
		System.out.print(data);
	}

	private DeployInBodyVO[] getBodyVO(String string, String[] checkItem) throws Exception {
		JSONArray jsonArr;
		DeployInBodyVO[] bvo = null;
		try {
			jsonArr = new JSONArray(string);
			bvo = new DeployInBodyVO[jsonArr.length()];
			for (int i = 0; i < jsonArr.length(); i++) {
				checkNeedItem(jsonArr.get(i).toString(), checkItem, false);
				bvo[i] = BeanUtils.JSONObjectToVO(DeployInBodyVO.class, jsonArr.get(i).toString());

				JSONObject jsonData = new JSONObject(jsonArr.get(i).toString());
				DepmethodVO depmethodVO = BillInfoQueryUtil.selectDepmethodByCode(jsonData.getString("pk_depmethod"));
				if (depmethodVO != null) {// 获取折旧方法
					bvo[i].setPk_depmethod(depmethodVO.getPk_depmethod());
				}

				// add by djy20220316
				bvo[i].setPk_assetuser(BillInfoQueryUtil.getPsndoc(bvo[i].getPk_assetuser()));
				if (bvo[i].getPk_usedept() != null) {
//					DeptVO usedeptvo = BillInfoQueryUtil.selectUserDept(bvo[i].getPk_usedept());
//					if (usedeptvo == null) {
//						String pd=BillInfoQueryUtil.selectPDept(bvo[i].getPk_usedept(),def1org);
//						if(pd==null)
//							throw new BusinessException("根据pk_usedept:" + bvo[i].getPk_usedept() + "，匹配不到对应的使用部门");
//						else {
							Map<String, DeptScaleVO[]> saveAllVos = new HashMap<String, DeptScaleVO[]>();
							List<DeptScaleVO> deptVO = new ArrayList<DeptScaleVO>();
							Map<String, String> keyAndLink = null;
							DeptScaleVO scalevo = new DeptScaleVO();
							scalevo.setTotalscale(new UFDouble(100));
							scalevo.setUsescale(new UFDouble(100));
							scalevo.setPk_dept(BillInfoQueryUtil.selectPDept(bvo[i].getPk_usedept(),def1org));
//							bvo[i].setDeptscalevo((new DeptScaleVO[] { scalevo }));
							deptVO.add(scalevo);
							String viewKey = 0 + "viewkey";
							saveAllVos.put(viewKey, CollectionUtils.toArray(deptVO));
							keyAndLink = UseDeptScaleUtils.insertBatch(saveAllVos);
							String link_key = keyAndLink.get(viewKey);
//							bvo[i].setPk_dept_key("pk_usedept");
							bvo[i].setPk_usedept(link_key);
//						}
//					}
				}
				//add by djy 20220316
				DeptVO mandetvo=selectMangeDept(bvo[i].getPk_mandept(),def1org);
				bvo[i].setPk_mandept(mandetvo.getPk_dept());
				bvo[i].setPk_mandept_v(mandetvo.getPk_vid());
			
				bvo[i].setCard_code(selectCardCodeByPK_CAR_OUT(bvo[i].getPk_card_out()));// 资产卡片
				bvo[i].setPk_category(selectTypeByCATE_CODE(bvo[i].getPk_category()));// 资产类别
				bvo[i].setPk_currency(BillInfoQueryUtil.getBdcurrtypenameByName(jsonData.getString("pk_currency")));
				// add by dxr
				if (jsonData.has("def3")) {
					bvo[i].setDef3(BillInfoQueryUtil.selectErpProject(jsonData.getString("def3")));
				}
				bvo[i].setPk_accbook_out(BillInfoQueryUtil.getAccountingBookPk(jsonData.getString("pk_card_out")));
				bvo[i].setPk_addreducestyle(
						BillInfoQueryUtil.getFaAddOrReduceStyle(jsonData.getString("pk_addreducestyle")));
				bvo[i].setPk_usingstatus(BillInfoQueryUtil.selectUsingstatusCode(jsonData.getString("pk_usingstatus")));
				// 获取调出资产卡片的折旧信息
				CardhistoryVO cardhistoryVO = BillInfoQueryUtil.getFaCardHistory(jsonData.getString("pk_card_out"));
				//add by djy20220402 算实际的累计折旧
				Map<String, Object> mapdep=new HashMap<String, Object>();
				String[] pks=new String[] {jsonData.getString("pk_card_out")};
				String accbook=BillInfoQueryUtil.getAccountingbook(outorg);
				UFDate date=BillInfoQueryUtil.getdeloutdate(jsonData.getString("pk_bill_src"));
				mapdep=BillInfoQueryUtil.handlerDep(pks,"0001H810000000000HS2",
						outorg,accbook,date,UFBoolean.FALSE);
				if(mapdep.get("simulateAccudep")==null||
						((HashMap)mapdep.get("simulateAccudep")).get(jsonData.getString("pk_card_out"))==null)
					throw new Exception("计算累计折旧有误，请联系管理员");			
				cardhistoryVO.setAccudep((UFDouble) ((HashMap)mapdep.get("simulateAccudep")).get(jsonData.getString("pk_card_out")));
				
				
				AssetVO cardVO = BillInfoQueryUtil.getFaCard(jsonData.getString("pk_card_out"));
				if (cardhistoryVO == null || cardVO == null)
					throw new BusinessException("没有找到调出单资产卡片的折旧信息");
//				if (cardhistoryVO != null&&cardVO!=null) {
				bvo[i].setPk_depmethod(cardhistoryVO.getPk_depmethod());
				bvo[i].setDeploy_price(cardhistoryVO.getOriginvalue());
				bvo[i].setOriginvalue(cardhistoryVO.getOriginvalue());
				bvo[i].setLocaloriginvalue(cardhistoryVO.getLocaloriginvalue());
				bvo[i].setAccudep(cardhistoryVO.getAccudep());
				// 净值
				UFDouble jz = cardhistoryVO.getLocaloriginvalue() == null ? new UFDouble("0.00")
						: cardhistoryVO.getLocaloriginvalue().sub(
								cardhistoryVO.getAccudep() == null ? new UFDouble("0.00") : cardhistoryVO.getAccudep());
				// 净额
				UFDouble je = jz.sub(cardhistoryVO.getPredevaluate() == null ? new UFDouble("0.00")
						: cardhistoryVO.getPredevaluate());
				bvo[i].setNetvalue(jz);
				bvo[i].setPredevaluate(cardhistoryVO.getPredevaluate());
				bvo[i].setNetrating(je);
				bvo[i].setSalvagerate(cardhistoryVO.getSalvagerate());
				bvo[i].setSalvage(cardhistoryVO.getSalvage());
				bvo[i].setServicemonth(cardhistoryVO.getServicemonth());
				bvo[i].setUsedmonth(cardhistoryVO.getUsedmonth());
				bvo[i].setBegin_date((UFDate) cardVO.getAttributeValue("begin_date"));
				bvo[i].setDep_start_date(cardhistoryVO.getDep_start_date());
				bvo[i].setDep_end_date(cardhistoryVO.getDep_end_date());
				bvo[i].setNaturemonth(cardhistoryVO.getNaturemonth());
				bvo[i].setTax_input(cardhistoryVO.getTax_input());
				bvo[i].setAllworkloan(cardhistoryVO.getAllworkloan());
				bvo[i].setAccuworkloan(cardhistoryVO.getAccuworkloan());
				bvo[i].setWorkloanunit(cardhistoryVO.getWorkloanunit());
				bvo[i].setClose_date((UFDate) cardVO.getAttributeValue("close_date"));
//				}
              //add by djy 20220317增加管理公司
				bvo[i].setDef1(def1org);
			}
		} catch (ParseException e) {

			e.printStackTrace();
		}
		return bvo;
	}

	private DeployInHeadVO getHeadVO(String json) throws Exception {
		DeployInHeadVO vo = new DeployInHeadVO();
		vo = BeanUtils.JSONObjectToVO(DeployInHeadVO.class, json);
		vo.setBill_type("HD"); /**
								 * 此两处HD,HD-01为必须项,否则查询不出来 需要注意的是,若本地环境自由态0 有HD-01则会报错
								 * 后续此代码提交至测试环境查看是否会报错;注:同张单据在测试环境则 不报错
								 */
		vo.setTransi_type("HD-01");
		vo.setPk_group(getPk_group(vo.getPk_org()));
		vo.setStatus(2);// 设置为新增状态使脚本能自动保存再提交
		OrgVO pk_org = BillInfoQueryUtil.selectOrgByPK((String) vo.getPk_org());// 财务组织
		if (pk_org != null) {
			vo.setPk_org_v(pk_org.getPk_vid());
		}
		vo.setPk_org_in(vo.getPk_org());
		vo.setBillmaker(BillInfoQueryUtil.getPK_syscreater());// 制单人
		JSONObject jsonData = new JSONObject(json);
		vo.setAccount_currency(BillInfoQueryUtil.getBdcurrtypenameByName(jsonData.getString("account_currency")));// 币种
		vo.setPk_org_out_v(selectOutOrg_V(vo.getPk_org_out()));
		// add by dxr
		vo.setPk_org_in_v(vo.getPk_org_v());
		vo.setPk_transitype("0001H81000000000DN9M");
		vo.setCreator(BillInfoQueryUtil.getPK_syscreater());

		// 判断调出调入组织是否同一个法人
		if (BillInfoQueryUtil.isSameDef51(vo.getPk_org(), vo.getPk_org_out()))
			vo.setDef12("Y");
		//add by djy 20220319
		else
			vo.setDef12("N");
//		vo.setAttributeValue("bill_status_in", 0);
		vo.setDef10(vo.getDef1());
		vo.setDef11(vo.getDef2());
//		vo.setDef12(vo.getDef5());
		
		vo.setDef1(null);
		vo.setDef2(null);
//		vo.setDef5(null);
		return vo;
	}

	public String requestJson(HttpServletRequest request) {
		StringBuilder sb = new StringBuilder();
		try {
			request.setCharacterEncoding("utf-8");
			BufferedReader reader = request.getReader();
			char[] buff = new char[1024];
			int len;
			while ((len = reader.read(buff)) != -1) {
				sb.append(buff, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	public void responseWriter(HttpServletResponse response, String returnJson) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type", "application/json; charset=utf-8");
		PrintWriter writer = response.getWriter();
		writer.write(returnJson);
		writer.close();
	}

	/**
	 * 校验放入的数据是否有null，如果有则 抛出异常不储存数据
	 * 
	 * @param jsonDataByInteface
	 * @param type
	 * @throws BusinessException
	 * @throws ParseException
	 */
	public void checkNeedItem(String jsonData, String[] checkItem, boolean isTrue)
			throws BusinessException, ParseException {
		JSONObject object = new JSONObject(jsonData);
		for (int i = 0; i < checkItem.length; ++i) {
			if (object.get(checkItem[i]) == null || "".equals(object.get(checkItem[i])) || "~".equals(checkItem[i])) {
				throw new BusinessException(checkItem[i] + "是null ,请插入数据");
			}
		}
		if (isTrue) {// 根据boolean判断是否是表头
			String src_id = object.getString("def2");// 来源单据号
			String pk_bill_src = object.getString("pk_bill_src");// 调出单主键

			String month = object.getString("business_date");// 月份
			selectOnlyID(src_id);
			selectThisMonthByID(month, pk_bill_src);// 是否本月调出调入

		}
	}

	/**
	 * 检查唯一来源单据
	 * 
	 * @param src_id
	 * @throws BusinessException
	 */
	private void selectOnlyID(String src_id) throws BusinessException {
		String sql = "select count(PK_DEPLOYIN) from FA_DEPLOYIN where def11 = '" + src_id + "' and dr = 0";
		Integer number = (Integer) getDao().executeQuery(sql, new ColumnProcessor());
		if (number != 0) {
			throw new BusinessException("字段 def2 来源单据号已存在");
		}
	}

	/**
	 * 根据来源单据ID检查是否本月调出调入
	 * 
	 * @param Month
	 * @throws BusinessException
	 */
	private void selectThisMonthByID(String month, String pk_bill_src) throws BusinessException {
		StringBuffer sql = new StringBuffer();
		sql.append("select count(PK_DEPLOYOUT)  from FA_DEPLOYOUT where PK_DEPLOYOUT = '").append(pk_bill_src)
				.append("' and dr = 0").append(" and BUSINESS_DATE <= to_char(last_day(TO_DATE(('").append(month)
				.append("')||'','yyyy-mm-dd HH24:MI:SS')), 'yyyy-mm-dd HH24:MI:SS')").append("and BUSINESS_DATE <='")
				.append(month).append("'");
		Integer number = (Integer) getDao().executeQuery(sql.toString(), new ColumnProcessor());
		if (number == 0) {
			throw new BusinessException("请检查调出单调出日期是否在同一月份,或调入时间是否小于调出时间");
		}

	}

	private void selectAsset_state(DeployInVO billVO) throws BusinessException {
		String pk_org_in = (String) billVO.getParentVO().getAttributeValue(DeployInHeadVO.PK_ORG);
		String pk_org_out = (String) billVO.getParentVO().getAttributeValue(DeployInHeadVO.PK_ORG_OUT);
		UFDate bizDateIn = (UFDate) billVO.getParentVO().getAttributeValue(DeployInHeadVO.BUSINESS_DATE);
		// 调出单表体卡片主键
		String[] card_out_pks = VOManager.getAttributeValueArray(billVO.getChildrenVO(), DeployInBodyVO.PK_CARD_OUT);
//		// 调入组织可以使用的所有账簿PK
//		Set<String> inOrgBookPkSet = AccbookManager.queryBookIDsByOrg(
//				pk_org_in, bizDateIn.toString());
		Set<String> outOrgBookPkSet = AccbookManager.queryBookIDsByOrg(pk_org_out, bizDateIn.toString());
		// 查询所有未被减少的账簿卡片
		AssetVO[] assetVOs = AMProxy.lookup(IAssetService.class)
				.queryDeploywayAssetVO(CollectionUtils.convertToArray(outOrgBookPkSet, new String[0]), card_out_pks);
		if (assetVOs == null)
			throw new BusinessException("该表体卡片状态不在调拨在途,请检查数据");
	}

	private String getPk_group(String pk_org) throws Exception {
		String sql = "SELECT PK_GROUP FROM ORG_ORGS WHERE PK_ORG = '" + pk_org + "' AND NVL(DR,0) = 0";
		String result = getColumn(sql, pk_org);
		if (result == null) {
			throw new BusinessException("没有找到该财务组织版本(pk_org),请检查数据:" + pk_org);
		}
		return result;
	}

	/**
	 * 资产编码
	 * 
	 * @param pk_card_out
	 * @return
	 * @throws Exception
	 */
	private String selectCardCodeByPK_CAR_OUT(String pk_card_out) throws Exception {
		String sql = "select card_code from fa_card where pk_card = '" + pk_card_out + "' and nvl (dr,0) = 0";
		String result = getColumn(sql, pk_card_out);
		if (result == null) {
			throw new BusinessException("没有找到资产编码(card_code),请检查数据");
		}
		return result;
	}

	/**
	 * 查询资产类别
	 * 
	 * @param cate_code
	 * @return
	 * @throws Exception
	 */
	private String selectTypeByCATE_CODE(String cate_code) throws Exception {
		String sql = "select  pk_category  from fa_category where nvl(dr,0) = 0 and cate_code='" + cate_code + "'";
		String result = getColumn(sql, cate_code);
		if (result == null) {
			sql = "select  pk_category  from fa_category where nvl(dr,0) = 0 and pk_category='" + cate_code + "'";
			result = getColumn(sql, cate_code);
			if (result == null)
				throw new BusinessException("没有找到资产类别(card_code),请检查数据");
		}
		return result;
	}

	private String selectOutOrg_V(String out_org_v) throws Exception {
		String sql = "select   pk_vid  from org_financeorg_v where   pk_financeorg  = '" + out_org_v + "'";
		String result = getColumn(sql, out_org_v);
		if (result == null) {
			result = out_org_v;
		}
		return result;
	}

	private String getColumn(String sql, String code) throws Exception {
		return SafeObject.toString(getDao().executeQuery(sql, new ColumnProcessor()));
	}

	private void updateOutVO(String pk_out, DeployInVO inBillVO) throws BusinessException {
		List<DeployOutVO> deployOutList = new ArrayList<DeployOutVO>();
		DeployOutVO[] deployOutVO = NCLocator.getInstance().lookup(IDeployOut.class).queryDeployOutVOByPKs(pk_out);

		((DeployOutHeadVO) deployOutVO[0].getParentVO()).setPk_deployin(inBillVO.getParentVO().getPrimaryKey());

		// 更新
		deployOutVO[0].getParentVO().setStatus(VOStatus.UPDATED);
		deployOutVO[0].getParentVO().setAttributeValue(DeployOutHeadVO.BILL_CODE_IN,
				((DeployInHeadVO) inBillVO.getParentVO()).getBill_code());
		deployOutList.add(deployOutVO[0]);

		// 最终批量更新
		if (null != deployOutList && deployOutList.size() > 0) {
			new BillPersistUtil().update(deployOutList.toArray(new DeployOutVO[0]));
		}
	}

	// 判断有没有产生新的资产
	private boolean isCreatNewCard(DeployInVO aggvo) {
		boolean flag = false;
		// 查询事务里面最新的agg,传进来的不是最新的
		BillQuery<DeployInVO> qy = new BillQuery<DeployInVO>(DeployInVO.class);
		DeployInVO[] aggvos = qy.query(new String[] { aggvo.getPrimaryKey() });
		DeployInBodyVO[] bodyvos = (DeployInBodyVO[]) aggvos[0].getChildrenVO();
		if (bodyvos == null || bodyvos.length == 0)
			flag = true;
		for (DeployInBodyVO bodyvo : bodyvos) {
			if (bodyvo.getPk_card_in() == null)
				flag = true;
		}
		return flag;
	}
	
	public  DeptVO selectMangeDept(String pk_mandept,String pk_org) {
		String sql = "select * from org_dept where dr=0 and code='"+pk_mandept+"' and pk_org='"+pk_org+"'";
		DeptVO result = null;
		try {
			result = (DeptVO) service.executeQuery(sql, new BeanProcessor(DeptVO.class));
			if(result==null)
				throw new BusinessException("没有找到编码为："+pk_mandept+"对应的管理部门");
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}
}
