package nc.bs.hz.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nc.bcmanage.bs.IBusiCenterManageService;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.pf.pub.PfDataCache;
import nc.itf.fa.byzitf.IAssetInfoToByzService;
import nc.itf.fa.byzlog.IbyzLogRcord;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.jdbc.framework.processor.BeanProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.pub.fa.dep.IReduceSimulateDep;
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.asset.AssetVO;
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.usingstatus.UsingStatusVO;
import nc.vo.org.DeptVO;
import nc.vo.org.FinanceOrgVO;
import nc.vo.org.OrgVO;
import nc.vo.pmpub.project.ProjectHeadVO;
import nc.vo.pub.BusinessException;
import nc.vo.pub.billtype.BilltypeVO;
import nc.vo.pub.lang.UFBoolean;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.sm.UserVO;

public class BillInfoQueryUtil {

	static IUAPQueryBS service = NCLocator.getInstance().lookup(IUAPQueryBS.class);
	
	public static IAssetInfoToByzService getSevice() {	
		return NCLocator.getInstance().lookup(IAssetInfoToByzService.class);
	}
	
//	public void sendAssetcardInfoToBYZ(AggCardVO[] aggvos) throws Exception {
//		new AssetcardInfoSendToBYZImpl().sendToByz(aggvos);
//	}
//	

	/**
	 * 判断是否推送ARC
	 * 
	 * @param pk_org
	 * @return
	 */
	public static Boolean isARC(String pk_org) {
		String sql = "SELECT DEF52 FROM ORG_ORGS WHERE PK_ORG = ?";
		SQLParameter parameter = new SQLParameter();
		parameter.addParam(pk_org);
		Boolean result = null;
		try {
			result = SafeObject.toBoolean(service.executeQuery(sql, parameter, new ColumnProcessor()));
			if (result == null)
				throw new BusinessException("没有找到对应的财务组织");
		} catch (BusinessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 组织_业务单元_财务组织
	 * 
	 * @param pk_org
	 * @return
	 */
	public static FinanceOrgVO selectOrg(String pk_org) {
		String sql = "SELECT * from org_financeorg_v where dr = 0 and pk_financeorg = '" + pk_org + "' and dr = 0";
		FinanceOrgVO result = null;
		try {
			result = (FinanceOrgVO) service.executeQuery(sql, new BeanProcessor(FinanceOrgVO.class));
			if (result == null)
				throw new BusinessException("没有找到对应的财务组织");
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	public static OrgVO selectOrgByPK(String pk_org) {
		String sql = "SELECT * from org_orgs where dr = 0 and pk_org = '" + pk_org + "' and dr = 0";
		OrgVO result = null;
		try {
			result = (OrgVO) service.executeQuery(sql, new BeanProcessor(OrgVO.class));
			if (result == null) {
				FinanceOrgVO financeOrgVO = selectOrg(pk_org);
				if (financeOrgVO == null) {
					throw new BusinessException("没有找到对应的财务组织");
				}
				result = new OrgVO();
				result.setPk_vid(financeOrgVO.getPk_vid());
			}

		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 自定义档案 查询法人
	 * 
	 * @param pk_defdoc
	 * @return
	 */
	public static DefdocVO selectDefVO(String pk_defdoc) {
		String sql = "select * from bd_defdoc where pk_defdoclist=(select pk_defdoclist from bd_defdoclist where code='SSFR' and nvl(dr,0)=0) and nvl(dr,0)=0  and enablestate=2 "
				+ "and pk_defdoc='" + pk_defdoc + "'";
		DefdocVO result = null;
		try {
			result = (DefdocVO) service.executeQuery(sql, new BeanProcessor(DefdocVO.class));
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 人员基本信息
	 * 
	 * @param pk_psndoc
	 * @return
	 */
	public static PsndocVO selectPsndoc(String pk_psndoc) {
		String sql = "SELECT * from bd_psndoc where dr = 0 and pk_psndoc  = '" + pk_psndoc + "' and dr = 0";
		PsndocVO result = null;
		try {
			result = (PsndocVO) service.executeQuery(sql, new BeanProcessor(PsndocVO.class));
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 增减方式
	 * 
	 * @param pk_addreducestyle
	 * @return
	 */
	public static AddreduceStyleVO selectAddreducestyle(String pk_addreducestyle) {
		String sql = "SELECT * from pam_addreducestyle where dr = 0 and pk_addreducestyle  = '" + pk_addreducestyle
				+ "' and dr = 0 and enablestate=2";
		AddreduceStyleVO result = null;
		try {
			result = (AddreduceStyleVO) service.executeQuery(sql, new BeanProcessor(AddreduceStyleVO.class));
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 供应商基本信息
	 * 
	 * @param bd_supplier
	 * @return
	 */
	public static SupplierVO selectSupplier(String pk_supplier) {
		String sql = "SELECT * from bd_supplier where dr = 0 and pk_supplier='" + pk_supplier
				+ "' and dr = 0 and enablestate=2";
		SupplierVO result = null;
		try {
			result = (SupplierVO) service.executeQuery(sql, new BeanProcessor(SupplierVO.class));
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 供应商基本信息
	 * 
	 * @param code
	 * @return
	 */
	public static String selectSupplierCode(String code) {
		String sql = "SELECT pk_supplier from bd_supplier where dr = 0 and code='" + code
				+ "' and dr = 0 and enablestate=2";
		String result = null;
		try {
			result = (String) service.executeQuery(sql, new ColumnProcessor());
			if (result == null) {
				throw new BusinessException("没有找到编码为：" + code + "的供应商");
			}
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * HR部门
	 * 
	 * @param pk_dept
	 * @return
	 */
	public static DeptVO selectDept(String pk_dept) {
		String sql = "SELECT * from org_dept where dr = 0 and pk_dept= '" + pk_dept + "' and dr = 0";
		DeptVO result = null;
		try {
			result = (DeptVO) service.executeQuery(sql, new BeanProcessor(DeptVO.class));
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 使用部门
	 * 
	 * @param pk_dept
	 * @return
	 */
	public static DeptVO selectUserDept(String pk_usedept) {
		String sql = "select * from org_dept where dr=0 and pk_dept =(SELECT pk_dept from fa_deptscale where dr = 0 and link_key= '" + pk_usedept + "')";
		DeptVO result = null;
		try {
			result = (DeptVO) service.executeQuery(sql, new BeanProcessor(DeptVO.class));
			if(result==null)
				result=selectDept(pk_usedept);
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}
	
	/**
	 * 使用部门
	 * 
	 * @param pk_dept
	 * @return
	 */
	public static DeptScaleVO selectScDept(String link) {
		String sql = "SELECT * from fa_deptscale where dr = 0 and link_key= '" + link + "'";
		DeptScaleVO result = null;
		try {
			result = (DeptScaleVO) service.executeQuery(sql, new BeanProcessor(DeptScaleVO.class));
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}
	
	/**
	 * HR部门
	 * 
	 * @param code
	 * @return
	 */
	public static String selectPDept(String code,String pk_org) {
		String sql = "SELECT pk_dept  from org_dept where dr = 0 and code= '" + code + "' and pk_org='"+pk_org+"'";
		String result = null;
		try {
			result = (String) service.executeQuery(sql, new ColumnProcessor());
			if (result == null)
				throw new BusinessException("没有找到编码为：" + code + "的使用部门");

		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 资产类别
	 * 
	 * @param pk_category
	 * @return
	 */
	public static CategoryVO selectCategory(String pk_category) {
		String sql = "SELECT * from fa_category where dr = 0 and pk_category= '" + pk_category + "'";
		CategoryVO result = null;
		try {
			result = (CategoryVO) service.executeQuery(sql, new BeanProcessor(CategoryVO.class));
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 资产类别
	 * 
	 * @param code
	 * @return
	 */
	public static String getCategory(String code) {
		String sql = "SELECT pk_category  from fa_category where dr = 0 and cate_code = '" + code + "'";
		String result = null;
		try {
			result = (String) service.executeQuery(sql, new ColumnProcessor());
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 使用状况
	 * 
	 * @param pk_usingstatus 使用状况PK
	 * @return 使用状况VO
	 */
	public static UsingStatusVO selectUsingstatus(String pk_usingstatus) {
		String sql = "SELECT * from fa_usingstatus where dr = 0 and pk_usingstatus= '" + pk_usingstatus
				+ "' and dr = 0";
		UsingStatusVO result = null;
		try {
			result = (UsingStatusVO) service.executeQuery(sql, new BeanProcessor(UsingStatusVO.class));
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 使用状况
	 * 
	 * @param code 使用状况code
	 * @return
	 */
	public static String selectUsingstatusCode(String code) {
		String sql = "SELECT pk_usingstatus  from fa_usingstatus where dr = 0 and status_code= '" + code
				+ "' and dr = 0";
		String result = null;
		try {
			result = (String) service.executeQuery(sql, new ColumnProcessor());
			if (result == null)
				throw new BusinessException("没有找到编码为：" + code + "的使用状况");
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 折旧方法
	 * 
	 * @param pk_depmethod 折旧方法PK
	 * @return 折旧VO
	 */
	public static DepmethodVO selectDepmethod(String pk_depmethod) {
		String sql = "SELECT * from fa_depmethod where dr = 0 and pk_depmethod= '" + pk_depmethod + "' and dr = 0";
		DepmethodVO result = null;
		try {
			result = (DepmethodVO) service.executeQuery(sql, new BeanProcessor(DepmethodVO.class));
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 折旧方法
	 * 
	 * @param pk_depmethod 折旧方法Code
	 * @return 折旧VO
	 */
	public static DepmethodVO selectDepmethodByCode(String pk_depmethod) {
		String sql = "SELECT * from fa_depmethod where dr = 0 and DEPMETHOD_CODE= '" + pk_depmethod + "' and dr = 0";
		DepmethodVO result = null;
		try {
			result = (DepmethodVO) service.executeQuery(sql, new BeanProcessor(DepmethodVO.class));
			if (result == null) {
				result = selectDepmethod(pk_depmethod);
			}
			if (result == null)
				throw new BusinessException("没有找到对应的折旧方法");
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 项目档案
	 * 
	 * @param pk_jobmngfil 项目PK
	 * @return 项目VO
	 */
	public static ProjectHeadVO selectProject(String pk_jobmngfil) {
		String sql = "SELECT * from bd_project where dr = 0 and pk_project  = '" + pk_jobmngfil + "' and dr = 0";
		ProjectHeadVO result = null;
		try {
			result = (ProjectHeadVO) service.executeQuery(sql, new BeanProcessor(ProjectHeadVO.class));
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 项目档案
	 * 
	 * @param code 项目erp编码
	 * @return 项目VO
	 */
	public static String selectErpProject(String code) {
		String sql = "SELECT pk_project from bd_project where dr = 0 and def6  = '" + code + "' and dr = 0";
		String result = null;
		try {
			result = (String) service.executeQuery(sql, new ColumnProcessor());
			if (result == null)
				throw new BusinessException("没有找到项目erp编码为：" + code + "的项目");
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 计量单位
	 * 
	 * @param pk_measdoc 计量的单位PK
	 * @return 计量单位VO
	 */
	public static MeasdocVO selectMeasdoc(String pk_measdoc) {
		String sql = "SELECT * from bd_measdoc where dr = 0 and pk_measdoc  = '" + pk_measdoc + "' and dr = 0";
		MeasdocVO result = null;
		try {
			result = (MeasdocVO) service.executeQuery(sql, new BeanProcessor(MeasdocVO.class));
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 用户
	 * 
	 * @param pk_user
	 * @return
	 */
	public static UserVO selectUser(String pk_user) {
		String sql = "SELECT * from sm_user where dr = 0 and cuserid  = '" + pk_user + "' and dr = 0 and enablestate=2";
		UserVO result = null;
		try {
			result = (UserVO) service.executeQuery(sql, new BeanProcessor(UserVO.class));
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 客商
	 * 
	 * @param pk_cust_sup
	 * @return
	 */
	public static CustSupplierVO selectCustsupplier(String pk_cust_sup) {
		String sql = "SELECT * from bd_cust_supplier where dr = 0 and pk_cust_sup  = '" + pk_cust_sup + "' and dr = 0";
		CustSupplierVO result = null;
		try {
			result = (CustSupplierVO) service.executeQuery(sql, new BeanProcessor(CustSupplierVO.class));
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 资产卡片
	 * 
	 * @param pk_card
	 * @return
	 */
	public static AssetVO selectCard(String pk_card) {
		String sql = "SELECT * from fa_card where dr = 0 and pk_card = '" + pk_card + "' and dr = 0";
		AssetVO result = null;
		try {
			result = (AssetVO) service.executeQuery(sql, new BeanProcessor(AssetVO.class));
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;

	}

	/**
	 * 变动类型
	 * 
	 * @param
	 * @return
	 */
	public static Map<String, String> getAlterItemValue() {
		Map<String, String> map = new HashMap<String, String>();
		// 标准变更类型部分
		map.put("BD01", "originvalue");
		map.put("BD02", "localoriginvalue");
		map.put("BD03", "accudep");
		map.put("BD04", "pk_ownerorg_v");
		map.put("BD05", "pk_mandept_v");
		map.put("BD06", "pk_equiporg_v");
		map.put("BD07", "usedept");
		map.put("BD08", "pk_assetuser");
		map.put("BD09", "naturemonth");
		map.put("BD10", "pk_usingstatus");
		map.put("BD11", "pk_depmethod");
		map.put("BD12", "salvagerate");
		map.put("BD13", "salvage");
		map.put("BD14", "card_num");
		map.put("BD15", "pk_category");
		map.put("BD16", "position");
		map.put("BD17", "pk_assetgroup");
		map.put("BD18", "pk_addreducestyle");
		map.put("BD19", "paydept_flag");
		map.put("BD20", "allworkloan");
		map.put("BD21", "accuworkloan");
		map.put("BD22", "workloanunit");
		map.put("BD23", "pk_jobmngfil");
		map.put("BD24", "provider");
		map.put("BD25", "asset_code");
		map.put("BD26", "spec");
		map.put("BD27", "card_model");
		map.put("BD28", "install_fee");
		map.put("BD29", "currmoney");
		map.put("BD30", "tax_cost");
		map.put("BD31", "revalued_amount");
		map.put("BD32", "dismant_cost");
		map.put("BD33", "other_cost");
		map.put("BD34", "tax_input");
		map.put("BD35", "license");
		map.put("BD36", "nettonnage");
		map.put("BD37", "fundorigin");
		map.put("BD38", "soillevel");
		map.put("BD39", "soilarea");
		map.put("BD40", "archarea");
		map.put("BD41", "quantity");
		map.put("BD42", "measureunit");
		map.put("BD43", "contrator");
		map.put("BD44", "machinepower");
		map.put("BD45", "machinequan");
		map.put("BD46", "leave_date");
		map.put("BD47", "producer");
		map.put("BD48", "assetsuit_code");
		map.put("BD49", "assetsuit_code");

		// 用户自定义
		map.put("BD60", "def18");

		// 用户自定义部分 涉及到缓存用不了
//		UserdefitemVO[] assetDefItems = UserDefUtils4Cloud.queryUserdefitem("fa.asset");
//		if (assetDefItems != null && assetDefItems.length != 0) {
//			int i = 49;
//			int var4 = assetDefItems.length;
//			for (int var5 = 0; var5 < var4; ++var5) {
//				++i;
//				String showName = MultiLanguageUtil.getMultiLanguageValue(assetDefItems[var5], "showname");
//
//				if (showName == null) {
//					showName = assetDefItems[var5].getShowname();
//				}
//				map.put("BD" + i, showName);
//			}
//		}
		return map;
	}

	/**
	 * 初始化平台单据类型缓存
	 * 
	 * @param billtypcodes
	 * @throws BusinessException
	 */
	public static void initSysBilltypeCache(String billtypecodes[]) throws BusinessException {

		HashMap<String, BilltypeVO> hashMap = new HashMap<String, BilltypeVO>();
		for (String billtypecode : billtypecodes) {
			String sql = "select * from bd_billtype where pk_billtypecode like '%" + billtypecode + "%' "
					+ "and nvl(dr,0)=0";
			ArrayList<BilltypeVO> billtypeVOs = (ArrayList<BilltypeVO>) new BaseDAO().executeQuery(sql,
					new BeanListProcessor(BilltypeVO.class));
			if (billtypeVOs != null && billtypeVOs.size() > 0) {
				for (int i = 0; i < billtypeVOs.size(); i++) {
					hashMap.put(billtypeVOs.get(i).getPk_billtypecode(), billtypeVOs.get(i));
				}
			}
		}
		PfDataCache.getVersionSensitiveCache().put(PfDataCache.STR_BILLTYPEINFO, hashMap);// 设置单据类型缓存,需要在缓存中获取单据类型信息
	}

	public static void initEnvironment(String pk_group, UFDate dbilldate) throws BusinessException {
		IBusiCenterManageService busiCenterManageService=NCLocator.getInstance().lookup(IBusiCenterManageService.class);
		InvocationInfoProxy.getInstance().setUserDataSource(busiCenterManageService.getAvailableBusiCenterDsNames()[0]);
		String pk_sysuser = InvocationInfoProxy.getInstance().getUserId();
//		  String pk_sysgroup = InvocationInfoProxy.getInstance().getGroupId();
		if ("".equals(pk_sysuser) || pk_sysuser == null || pk_sysuser.length() == 0 || "#UAP#".equals(pk_sysuser)) {
			InvocationInfoProxy.getInstance().setUserId(getPK_syscreater());
		}
//		InvocationInfoProxy.getInstance().setUserDataSource("NCCDATA");
		// if ("".equals(pk_sysgroup) || pk_sysgroup == null || pk_sysgroup.length() ==
		// 0) {
		InvocationInfoProxy.getInstance().setGroupId(pk_group);
		// }
		//设置数据源
//		IBusiCenterManageService busiCenterManageService=NCLocator.getInstance().lookup(IBusiCenterManageService.class);
//		if("design".equals(busiCenterManageService.getAvailableBusiCenterDsNames()[0]))
//			InvocationInfoProxy.getInstance().setUserDataSource("design");
//		else if(busiCenterManageService.getAvailableBusiCenterDsNames()[0]==null)
			
//		else
//			InvocationInfoProxy.getInstance().setUserDataSource(busiCenterManageService.getAvailableBusiCenterDsNames()[0]);
		
		String groupno = (String) getValueByWhere("org_group", "groupno", " pk_group='" + pk_group + "'");
		InvocationInfoProxy.getInstance().setGroupNumber(groupno);
		if (dbilldate != null) {
			InvocationInfoProxy.getInstance().setBizDateTime(dbilldate.getMillis());
		} else {
			InvocationInfoProxy.getInstance().setBizDateTime(new UFDateTime().getMillis());
		}
	}

	/**
	 * 根据表、where条件查询具体字段的值
	 * 
	 * @param tablename 表名
	 * @param returnkey 返回字段名称
	 * @param strWhere  where条件
	 * @return
	 * @throws BusinessException
	 */
	public static Object getValueByWhere(String tablename, String returnkey, String strWhere) throws BusinessException {
		String sql = "select " + returnkey + " from " + tablename + " where nvl(dr,0)=0 ";
		// if(key!=null){
		// sql+=" and "+key+"='"+value+"'";
		// }
		if (strWhere != null) {
			sql += " and " + strWhere;
		}
		Object valueobject = getDAO().executeQuery(sql, new ColumnProcessor());
		return valueobject;
	}

	private static BaseDAO baseDAO;

	public static BaseDAO getDAO() {
		if (baseDAO == null) {
			baseDAO = new BaseDAO();
		}
		return baseDAO;
	}

	public static String getPK_syscreater() throws DAOException {
		String sql = "select cuserid from sm_user where nvl(dr,0)=0 and enablestate=2 and user_code='ARC'";
		return (String) getDAO().executeQuery(sql, new ColumnProcessor());
	}

	/**
	 * 交易类型
	 * 
	 * @param pk_billtypecode
	 * @return
	 */
	public static String getPk_tradetype(String pk_billtypecode) {
		try {
			String sql = "select pk_billtypeid  from bd_billtype where nvl(dr,0)=0 and pk_billtypecode='"
					+ pk_billtypecode + "'";
			return (String) getDAO().executeQuery(sql, new ColumnProcessor());
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return null;
	}

	/**
	 * 获取使用状态主键
	 * 
	 * @param name
	 * @return
	 */
	public static String getUseStatus(String name) {
		String pk = null;
		try {
//			select pk_usingstatus from fa_usingstatus where status_name = '在用'
			String sql = "select pk_usingstatus from fa_usingstatus where nvl(dr,0)=0 and status_name = '" + name + "'";
			pk = (String) getDAO().executeQuery(sql, new ColumnProcessor());
			if (pk == null)
				throw new BusinessException("没有找到该使用状态：" + name);
			return pk;
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return null;
	}

	/**
	 * 通过卡片主键获取账簿主键
	 * 
	 * @param cardPk
	 * @return
	 */
	public static String getAccountingBookPk(String cardPk) {
		String pk = null;
		try {
			String sql = "select org_accountingbook.pk_accountingbook\r\n" + "  from org_accountingbook\r\n"
					+ "  left join fa_card\r\n" + "    on org_accountingbook.pk_relorg = fa_card.pk_org\r\n"
					+ " where fa_card.pk_card = '" + cardPk + "'";
//			select org_accountingbook.pk_accountingbook  from org_accountingbook left join fa_card on org_accountingbook.pk_relorg = fa_card.pk_org where fa_card.pk_card = '1001H8100000001GBEDF'
			pk = (String) getDAO().executeQuery(sql, new ColumnProcessor());
			if (pk == null)
				throw new BusinessException("无法通过" + cardPk + "获取账簿主键");
			return pk;
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return null;
	}

	/**
	 * 变动原因
	 * 
	 * @param pk_reason
	 * @return
	 */
	public static String getFa_reason(String reasoncode) {
		String pk = null;
		try {
			String sql = "select pk_reason  from fa_reason where nvl(dr,0)=0 and reason_code='" + reasoncode + "'";
			pk = (String) getDAO().executeQuery(sql, new ColumnProcessor());
			if (pk == null)
				throw new BusinessException("没有找到变动原因编码：" + reasoncode + "对应的变动原因");
			return pk;
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return null;
	}

	/**
	 * 减少原因
	 * 
	 * @param reasoncode
	 * @return
	 */
	public static String getFaReduceReason(String reasoncode) {
		String pk = null;
		try {
			String sql = "select pk_reason  from fa_reason where nvl(dr,0)=0 and reason_type = 2 and reason_code='"
					+ reasoncode + "'";
			pk = (String) getDAO().executeQuery(sql, new ColumnProcessor());
			if (pk == null)
				throw new BusinessException("没有找到减少原因编码：" + reasoncode + "对应的减少原因");
			return pk;
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return null;
	}

//	select * from fa_card where pk_card = '1001T6100000001AWIHT' AND dr = 0
	public static AssetVO getFaCard(String cardPk) {
		String sql = "select * from fa_card where pk_card = '" + cardPk + "' AND dr = 0";
		AssetVO result = null;
		try {
			result = (AssetVO) service.executeQuery(sql, new BeanProcessor(AssetVO.class));
			if (result == null) {
				throw new BusinessException("没有找到该卡片" + cardPk + "的信息");
			}
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}

	/**
	 * 获取折旧信息
	 * 
	 * @param cardPk
	 * @return
	 */
	public static CardhistoryVO getFaCardHistory(String cardPk) {
		/*
		 * select * from fa_cardhistory where pk_card = '1001T6100000001AWIHT' and dr =
		 * 0 and asset_state = 'exist' and ts = (select max(ts) from fa_cardhistory
		 * where pk_card = '1001T6100000001AWIHT' and dr = 0 and asset_state = 'exist')
		 */

		String sql = "select *\r\n" + "  from fa_cardhistory\r\n" + " where pk_card = '" + cardPk + "'\r\n"
				+ "   and dr = 0\r\n" + "   and asset_state = 'exist'\r\n" + "   and ts = (select max(ts)\r\n"
				+ "               from fa_cardhistory\r\n" + "              where pk_card = '" + cardPk + "'\r\n"
				+ "                and dr = 0\r\n" + "                and asset_state = 'exist')";
		CardhistoryVO result = null;
		try {
			result = (CardhistoryVO) service.executeQuery(sql, new BeanProcessor(CardhistoryVO.class));
			if (result == null) {
				throw new BusinessException("没有找到该卡片" + cardPk + "的折旧信息");
			}
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return result;
	}
	
	//计算折旧
	public static Map<String, Object> handlerDep(String[] pk_cards, String pk_group, String pk_org, String pk_accbook,
			UFDate business_date, UFBoolean isCardSim) throws BusinessException{
		return NCLocator.getInstance().lookup(IReduceSimulateDep.class).handlerSimDep(pk_cards, pk_group, pk_org, pk_accbook,
				business_date, isCardSim);
	}
	

	/**
	 * 增加或减少方式
	 * 
	 * @param addOrReduceStyle
	 * @return
	 */
	public static String getFaAddOrReduceStyle(String addOrReduceStyle) {
		String pk = null;
		try {
			String sql = "select pk_addreducestyle from pam_addreducestyle where nvl(dr,0)=0 and style_code ='"
					+ addOrReduceStyle + "'";
			pk = (String) getDAO().executeQuery(sql, new ColumnProcessor());
			if (pk == null)
				throw new BusinessException("没有找到增加或减少方式编码：" + addOrReduceStyle + "对应的增加或减少方式");
			return pk;
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return null;
	}

//	select pk_addreducestyle from pam_addreducestyle where 1 = 1 and dr = 0 and style_code like '02%' and style_code = '0206'

	/**
	 * 查询单位
	 * 
	 * @param unitCode
	 * @return
	 */
	public static String getUnit(String unitCode) {
		String pk = null;
		try {
			String sql = "select pk_cust_sup from bd_cust_supplier where nvl(dr,0)=0 and code ='" + unitCode + "'";
			pk = (String) getDAO().executeQuery(sql, new ColumnProcessor());
//			if (pk == null)
//				throw new BusinessException("没有找到单位编码：" + unitCode + "对应的单位");
			return pk;
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return null;
	}
//	select pk_cust_sup from bd_cust_supplier where 1 = 1 and code = 'F1319'

	/**
	 * 插入接口日志
	 */
	public static void insertlog(ByzLogRcordVO logvo) {
		try {
			NCLocator.getInstance().lookup(IbyzLogRcord.class).RcordLogBYZ__RequiresNew(logvo);
		} catch (BusinessException e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
	}

	/**
	 * 币种
	 */
	public static String getBdcurrtypename(String pk_currtype) {
		String name = "";
		try {
			String sql = "select name from bd_currtype where nvl(dr,0)=0 and pk_currtype='" + pk_currtype + "'";
			name = (String) getDAO().executeQuery(sql, new ColumnProcessor());
		} catch (BusinessException e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return name;
	}

	/**
	 * 币种
	 */
	public static String getBdcurrtypenameByName(String pk_currtype) {
		String name = "";
		try {
			String sql = "select pk_currtype from bd_currtype where nvl(dr,0)=0 and name='" + pk_currtype + "'";
			name = (String) getDAO().executeQuery(sql, new ColumnProcessor());
		} catch (BusinessException e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return name;
	}

	/**
	 * 人员
	 * 
	 * @param pk_billtypecode
	 * @return
	 */
	public static String getPsndoc(String code) {
		String pk = "";
		try {
			String sql = "select pk_psndoc from bd_psndoc where nvl(dr,0)=0 and enablestate=2 and code='" + code + "'";
			pk = (String) getDAO().executeQuery(sql, new ColumnProcessor());
			if (pk == null)
				throw new BusinessException("没有找到人员编码：" + code + "对应的人员");
			return pk;
		} catch (Exception e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return null;
	}

	/**
	 * 请求返回处理
	 */
	public static 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 static 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();
	}

	// NNC成功同步ARC单据打标识
	public static void updateStatus(String type, String[] pks) {
		StringBuilder sql = new StringBuilder("update ");
		String table = null;
		String id = null;
		String def="def10";
		if ("H0".equals(type)) {
			table = "fa_cardsub";
			id = "pk_card";
			def="def21";
		}
		if ("HG".equals(type)) {
			table = "fa_alter";
			id = "pk_alter";
			def="def19";
		}
		if ("HM".equals(type)) {
			table = "fa_assetsplit";
			id = "pk_assetsplit";
		}
		if ("HO".equals(type)) {
			table = "fa_assetcombin";
			id = "pk_assetcombin";
		}
		if (table == null || id == null || pks == null || pks.length == 0)
			return;
		sql.append(table).append(" set "+def+"='Y' where nvl(dr,0)=0 and ").append(id + " in(");
		for (int i = 0; i < pks.length; i++) {
			if (i != pks.length - 1)
				sql.append("'" + pks[i] + "',");
			else
				sql.append("'" + pks[i] + "')");

		}

		BaseDAO dao = new BaseDAO();
		try {
			dao.executeUpdate(sql.toString());
		} catch (DAOException e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
	}

	// 查询就卡片pk
	/**
	 * 新卡片pk
	 */
	public static String getOldPk(String newpk) {
		String pk = "";
		try {
			String sql = "select pk_card from fa_deployout_b where "
					+ "pk_deployout_b  =(select pk_bill_b_src  from fa_deployin_b where dr=0 and  pk_card_in='" + newpk
					+ "') and dr=0";
			pk = (String) getDAO().executeQuery(sql, new ColumnProcessor());
		} catch (BusinessException e) {
			ExceptionUtils.wrappBusinessException(e.getMessage());
		}
		return pk;
	}

	// 判断是否同法人
	public static boolean isSameDef51(String pk_org1, String pk_org2) throws BusinessException {
		boolean flag = false;
		IUAPQueryBS query = NCLocator.getInstance().lookup(IUAPQueryBS.class);
		String sqlin = "select def51 from org_orgs where dr=0 and enablestate=2 and pk_org='" + pk_org1 + "'";
		String sqlout = "select def51 from org_orgs where dr=0 and enablestate=2 and pk_org='" + pk_org2 + "'";
		String def51in = (String) query.executeQuery(sqlin, new ColumnProcessor());
		String def51out = (String) query.executeQuery(sqlout, new ColumnProcessor());
		if(def51in==null||def51out==null)
			throw new BusinessException("调入或者调出组织没有在业务单元维护def51的法人信息");
		if (def51in.equals(def51out))
			flag = true;
		return flag;
	}
	
	/**
	 * 获取账簿
	 * @param org
	 * @return
	 * @throws BusinessException
	 */
	public static String getAccountingbook(String org) throws BusinessException {
		
		String sql = "SELECT pk_accountingbook FROM org_accountingbook WHERE pk_relorg = ?";
		SQLParameter parameter = new SQLParameter();
		parameter.addParam(org);
		String result = SafeObject.toString(getDAO().executeQuery(sql, parameter, new ColumnProcessor()));
		if (result == null) {
			throw new DAOException("通过pk_org:"+org+"没有找到该该账簿");
		}
		return result;
	}
	
	public static UFDate getdeloutdate(String pk_out) throws BusinessException {
		String sql = "SELECT business_date FROM  fa_deployout WHERE dr=0 and pk_deployout ='"+pk_out+"'";
		String date = (String) getDAO().executeQuery(sql, new ColumnProcessor());
		if(date==null)
			throw new BusinessException("没有找到调出单的业务日期，请联系管理员");
		return 	new UFDate(date);
	}
}
