package nc.service.rest.utils;

import java.util.Map;
import nc.md.MDBaseQueryFacade;
import nc.md.data.access.NCObject;
import nc.md.model.IBean;
import nc.md.model.IBusinessEntity;
import nc.md.persist.framework.MDPersistenceService;
import nc.vo.bd.meta.IBDObject;
import nc.vo.bd.meta.NCObject2BDObjectAdapter;
import nc.vo.pub.BusinessException;

/**
 * <b> 转成 IBDObject工具类 </b>
 * 用于根据 classid 翻译编码或主键
 * 2020-11-20
 * @version NCC2005
 */
public class TransIBDObjectUtil {

	/**
	 * 通过classid 和 编码 转成 IBDObject
	 * 
	 * @param classid
	 * @param codes
	 * @return
	 * @throws ClassNotFoundException
	 * @throws BusinessException
	 */
	public static IBDObject[] transIBDObjectByCode(String classid, String[] codes)
			throws ClassNotFoundException, BusinessException {
		if (codes == null || codes.length == 0) {
			return null;
		}
		IBean bean = MDBaseQueryFacade.getInstance().getBeanByID(classid);
		String className = bean.getFullClassName();
		Class<?> clazz = TransIBDObjectUtil.class.getClassLoader().loadClass(className);
		Map<String, String> namePathMap = ((IBusinessEntity) bean).getBizInterfaceMapInfo(IBDObject.class.getName());
		String codeField = namePathMap.get("code"); // 编码字段名

		String whereStr = codeField + " in (" + createInSql(codes) + ")";
		if ("nc.vo.bd.defdoc.DefdocVO".equals(className)) { // 自定义档案：添加档案类型条件
			whereStr = whereStr + " and pk_defdoclist = '" + bean.getID() + "'";
		}

		Object[] objs = MDPersistenceService.lookupPersistenceQueryService().queryBillOfNCObjectByCond(clazz, whereStr,
				true);
		return TransIBDObjectUtil.transVOIBDObjectByBean(bean, objs);
	}

	/**
	 * VO 转换为 IOBject接口
	 * 
	 * @param classid
	 * @param vos
	 * @return
	 * @throws MetaDataException
	 */
	public static IBDObject[] transVOIBDObjectByBean(IBean bean, Object[] vos) {
		if (bean == null) {
			return null;
		}
		if (vos == null) {
			return null;
		}
		IBDObject[] objs = new IBDObject[vos.length];
		for (int i = 0; i < objs.length; i++) {
			Map<String, String> name_path_map = ((IBusinessEntity) bean)
					.getBizInterfaceMapInfo(IBDObject.class.getName());
			objs[i] = new NCObject2BDObjectAdapter(NCObject.newInstance(vos[i]), name_path_map);
		}
		return objs;
	}

	/**
	 * 拼接SQL IN语句
	 * 
	 * @param paramsSet
	 * @return
	 */
	public static String createInSql(String[] params) {
		if (params == null || params.length == 0) {
			return "''";
		}
		StringBuffer inSql = new StringBuffer();
		for (int i = 0; i < params.length; i++) {
			String param = params[i] == null ? "" : params[i];
			inSql.append(i == params.length - 1 ? ("'" + param + "'") : ("'" + param + "',"));
		}
		return inSql.toString();
	}

}
