package nc.uapbd.service.rest.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import uap.json.JSONArray;
import uap.json.JSONObject;
import nc.pub.sap.constant.SapConstants;
import nc.pub.sap.sort.SapVOSort;
import nc.pub.sap.utils.SapUtils;
import nc.vo.jcom.lang.StringUtil;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.IAttributeMeta;
import nc.vo.pub.SuperVO;
import nc.vo.pub.VOStatus;
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.model.meta.entity.vo.Attribute;
import nc.vo.sap.syproconfig.SyProConfigBVO;

public class JsonTools {
	
	
	/**
	 * 适用于DIRECTION_SAP2NC的情况，当协同配置中第三方系统发送的json字符串中的字段名称和NC vo中的字段名称不相同时使用
	 * @param voClass
	 * @param jsonObjects
	 * @param headConfigMap
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws BusinessException
	 */
	@SuppressWarnings({ "unchecked"})
	public static List<CircularlyAccessibleValueObject> setRecValues(Class<? extends CircularlyAccessibleValueObject> voClass, JSONArray jsonObjects,HashMap<String, ArrayList<String>> headConfigMap) throws InstantiationException, IllegalAccessException, BusinessException {
		CircularlyAccessibleValueObject recvo=voClass.newInstance();				
		nc.vo.pubapp.pattern.model.meta.entity.vo.ModelVOMeta model =
				(nc.vo.pubapp.pattern.model.meta.entity.vo.ModelVOMeta)((SuperVO)recvo).getMetaData();
		IAttributeMeta[] iMeta = model.getAttributes();	
		List<CircularlyAccessibleValueObject> lisc = new ArrayList<CircularlyAccessibleValueObject>();
		int length = jsonObjects.length();
		for (int i = 0; i < length; i++) {
			Iterator<String> it;
			String attributeName;
			Object value;
			JSONObject jsonObject = jsonObjects.getJSONObject(i);
			CircularlyAccessibleValueObject vo = voClass.newInstance();
			it = (Iterator<String>) jsonObject.keys();
			while (it.hasNext()) {
				attributeName = it.next();
				if (StringUtil.isEmptyWithTrim(attributeName)) {
					continue;
				}
				value = jsonObject.get(attributeName);
				if (JSONObject.NULL==value||value == null || StringUtil.isEmptyWithTrim(value.toString())) {
					continue;
				}
				
				/*//把json中的attributeName通过协同配置转换成NC的字段名称
				HashMap<String, ArrayList<String>> headConfigMap = null;
				//查询公式配置信息
				headConfigMap = getFormulas(formulasCode, SapConstants.DIRECTION_SAP2NC);*/
				//NC字段编码
				ArrayList<String> nc_field_headList = headConfigMap.get(SapConstants.NC_FIELD_CODE);
				//SAP字段编码
				ArrayList<String> sap_field_headList = headConfigMap.get(SapConstants.SAP_FIELD_CODE);
				
				for(int k=0;k<sap_field_headList.size();k++){
					if (attributeName.equalsIgnoreCase(sap_field_headList.get(k).trim())) {			
						attributeName = nc_field_headList.get(k);
						break;
					}
				}
				
				for (int j = 0; j < iMeta.length; j++) {													
					Attribute field=(Attribute)iMeta[j];
					String  attriname=field.getName();
					nc.vo.pub.JavaType type=field.getJavaType();
					
					if (attributeName.equalsIgnoreCase(attriname.trim())) {						
						if (type.name().equals("String")) {
							vo.setAttributeValue(attributeName, value);
						} else if (type.name().equals("Integer")) {
							vo.setAttributeValue(attributeName,
									Integer.parseInt(value.toString()));
						} else if (type.name().equals("UFDouble")) {
							vo.setAttributeValue(attributeName, new UFDouble(
									value.toString()));
						} else if (type.name().equals("UFBoolean")) {
							vo.setAttributeValue(attributeName, new UFBoolean(
									value.toString()));
						} else if (type.name().equals("UFDate")) {
							vo.setAttributeValue(attributeName, new UFDate(
									value.toString()));
						} else if (type.name().equals("UFDateTime")) {
							vo.setAttributeValue(attributeName, new UFDateTime(
									value.toString()));
						} else {
							vo.setAttributeValue(attributeName, value);
						}
						break;
					}
				}
			}
			//VO状态
			vo.setStatus(VOStatus.NEW);
			lisc.add(vo);
		}
		return lisc;
	}
	
	@SuppressWarnings("unchecked")
	public static HashMap<String,ArrayList<String>> getFormulas(String code,int direction) throws BusinessException{
		StringBuffer sqlstr = new StringBuffer("");
		sqlstr.append("item = (select pk_head").append("\r\n");
		sqlstr.append("  from sap_syproconfig").append("\r\n");
		sqlstr.append(" where billno = '");
		sqlstr.append(code);
		sqlstr.append("'").append("\r\n");
		sqlstr.append("   and nvl(dr, 0) = 0) and nvl(dr, 0) = 0 and isenable_sn='Y'"); 
		List<SyProConfigBVO> syProConfigBVOs = (List<SyProConfigBVO>)SapUtils.getQueryBS().retrieveByClause(SyProConfigBVO.class, sqlstr.toString());
		if(syProConfigBVOs!=null && syProConfigBVOs.size()>0){
			HashMap<String,ArrayList<String>> formulasMap = new HashMap<String,ArrayList<String>>();
			//非空字段
			ArrayList<String> notNullField = new ArrayList<String>();
			//SAP->NC ？ NC->SAP 公式
			ArrayList<String> formula = new ArrayList<String>();
			//NC字段编码
			ArrayList<String> nc_field_code = new ArrayList<String>();
			//NC字段名称
			ArrayList<String> nc_field_name = new ArrayList<String>();
			//SAP字段编码
			ArrayList<String> sap_field_code = new ArrayList<String>();
			Collections.sort(syProConfigBVOs, new SapVOSort(direction));
			for(SyProConfigBVO syProConfigBVO:syProConfigBVOs){
				if(SapConstants.DIRECTION_SAP2NC==direction){
					//SAP->NC
					if(syProConfigBVO.getIsenable_sn().booleanValue()){
						if(!syProConfigBVO.getNullflag().booleanValue()){
							notNullField.add(syProConfigBVO.getField_code());
							nc_field_name.add(syProConfigBVO.getField_name());
						}
						formula.add(syProConfigBVO.getFormula_sn());
					}
					
					nc_field_code.add(syProConfigBVO.getField_code());
					
					sap_field_code.add(syProConfigBVO.getField_code_sap());
					
				}else if(SapConstants.DIRECTION_NC2SAP==direction){
					//NC->SAP
					if(syProConfigBVO.getIsenable_ns().booleanValue()){
						formula.add(syProConfigBVO.getFormula_ns());
						nc_field_code.add(syProConfigBVO.getField_code());
						sap_field_code.add(syProConfigBVO.getField_code_sap());
					}
				}
			}
			formulasMap.put(SapConstants.NOTNULL_FIELD_KEY, notNullField);
			formulasMap.put(SapConstants.FORMULA_KEY, formula);
			formulasMap.put(SapConstants.NC_FIELD_CODE, nc_field_code);
			formulasMap.put(SapConstants.SAP_FIELD_CODE, sap_field_code);
			formulasMap.put(SapConstants.NC_FIELD_NAME, nc_field_name);
			return formulasMap;
		}
		return null;
	}
	
	public static JSONObject BatchSimpleVOToJson(List<? extends CircularlyAccessibleValueObject> simpleVOList,ArrayList<String> nc_field_headList,ArrayList<String> sap_field_headList){
		String nc_field;
		String sap_field;
		Object value;

		JSONObject billJsonObj = new JSONObject();
		JSONArray headArray = new JSONArray();	
		
		for(CircularlyAccessibleValueObject simpleVO:simpleVOList){
			JSONObject headJsonObj = new JSONObject();	
			for(int i=0;i<nc_field_headList.size();i++){
				
				nc_field = nc_field_headList.get(i);
				sap_field = sap_field_headList.get(i);
				
				value = simpleVO.getAttributeValue(nc_field);
				value = value==null?"":("N".equals(value+"")?"":("Y".equals(value+"")?"X":value));
				
				headJsonObj.put(sap_field, value+"");
			}
			headArray.put(headJsonObj);
		}
		
		
		billJsonObj.put("retmsg", headArray);
		
		return billJsonObj;
	}
}
