package nc.util.arap.arc;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.arap.byzitf.IbyzLogRcord;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.jdbc.framework.processor.BeanProcessor;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.am.addreducestyle.AddreduceStyleVO;
import nc.vo.arap.arc.ByzLogRcordVO;
import nc.vo.bd.cust.CustSupplierVO;
import nc.vo.bd.defdoc.DefdocVO;
import nc.vo.bd.psn.PsndocVO;
import nc.vo.bd.supplier.SupplierVO;
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.UFDate;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;
import nc.vo.sm.UserVO;

public class ArapArcUtil {

	static IUAPQueryBS service = NCLocator.getInstance().lookup(IUAPQueryBS.class);
	
	/**
	 * 组织_业务单元_财务组织
	 * 
	 * @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 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_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 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_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_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 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 {
		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());
		}
		// if ("".equals(pk_sysgroup) || pk_sysgroup == null || pk_sysgroup.length() ==
		// 0) {
		InvocationInfoProxy.getInstance().setGroupId(pk_group);
		// }

		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;
	}

	/**
	 * 插入接口日志
	 */
	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 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();
	}
}
