package com.sagacloud.utils;

import com.google.common.base.Strings;
//import com.sagacloud.json.JSONObject;
//import com.sagacloud.json.JSONValue;
import com.alibaba.fastjson.*;
import com.sagacloud.utils.tables.ObjectTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * Created by wushengzong on 2017/4/19.
 */

public class CommonMethods {
	private static final Logger log = LoggerFactory.getLogger(CommonMethods.class);
	public static String[] idCharArr = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E",
			"F", "G", "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
	public static short idLength = 5;

	public static JSONObject queryData(String projectId, String jsonStr, String tbName) {

		if (Strings.nullToEmpty(jsonStr).trim().isEmpty()) {
			jsonStr = "{}";
		}
		JSONObject bodyNode = JSONObject.parseObject(jsonStr);
		if (bodyNode.get("criteria") == null) {
			return DpUtils.errorJson("json格式错误，没有criteria.");
		}
		JSONObject cNode = (JSONObject) bodyNode.get("criteria");
		JSONObject json = JSONObject.parseObject("{\"QueryType\":\"select\"}");
		cNode.put("building", projectId.substring(2, projectId.length()));
		json.put("Database", OssUtils.getProperty("fjd.database.name"));
		json.put("Datatable", tbName);
		json.put("Criteria",cNode);
		try {
			JSONObject re = ZillionAgentProvider.GetAgent().Query(json);
			return re;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("param="+json.toString()+", err="+Arrays.toString(e.getStackTrace()));
			return DpUtils.errorJson(Arrays.toString(e.getStackTrace()));
		}
	}
	
	public static JSONObject queryData(String projectId, String jsonStr, String tbName, boolean pjLocalId) {

		if (Strings.nullToEmpty(jsonStr).trim().isEmpty()) {
			jsonStr = "{}";
		}
		JSONObject bodyNode = JSONObject.parseObject(jsonStr);
		if (bodyNode.get("criteria") == null) {
			return DpUtils.errorJson("json格式错误，没有criteria.");
		}
		String building = projectId.substring(2, projectId.length());
        if(pjLocalId) {
        	building = ObjectUtil.getProjLocalID(building);
        }
		JSONObject cNode = (JSONObject) bodyNode.get("criteria");
		JSONObject json = JSONObject.parseObject("{\"QueryType\":\"select\"}");
		cNode.put("building", building);
		json.put("Database", OssUtils.getProperty("fjd.database.name"));
		json.put("Datatable", tbName);
		json.put("Criteria",cNode);
		try {
			JSONObject re = ZillionAgentProvider.GetAgent().Query(json);
			return re;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("param="+json.toString()+", err="+Arrays.toString(e.getStackTrace()));
			return DpUtils.errorJson(Arrays.toString(e.getStackTrace()));
		}
	}

	/**
	 * 生成随机ID
	 * @param genArr  ID中可能出现的字符集合
	 * @param length	生成目标ID的长度
	 * @return 生成的ID
	 */
	public static String generateRandomId(String[] genArr, short length)
	{
		if(genArr == null || genArr.length == 0 || length < 1)
			return "";
		long randMax = (long)Math.pow((double) genArr.length, (double) length);
		Random random = new Random();
		long value = Math.abs(random.nextLong()) % randMax;
		StringBuilder sb = decimalToObject(genArr, value);
		if(sb.length() < length)
        {
            for(; sb.length() < length; sb.insert(0, genArr[0]));
        }
        return sb.toString();
	}

	/**
	 * 将十进制的数字转化成genArr.length进制的数
	 * @param genArr	ID中可能出现的字符集合
	 * @param value	要被转换的10进制数
	 * @return	目标字符串
	 */
	public static StringBuilder decimalToObject(String[] genArr, long value)
	{
		int length = genArr.length;
		StringBuilder sb = new StringBuilder();
		for(; value > 0; value/=length)
		{
			int index = (int) (value % length);
			sb.insert(0, genArr[index]);
		}
		return sb;
	}

	public static String getProject(String projectId, boolean needPjPrefix) {
	    try {
            if ((projectId.startsWith(Const.OBJ_TYPE_PROJECT) && needPjPrefix) || (!projectId.startsWith(Const.OBJ_TYPE_PROJECT) && !needPjPrefix))
                return projectId;
            else if (projectId.startsWith(Const.OBJ_TYPE_PROJECT))
                return projectId.substring(2);
            else
                return String.join("", Const.OBJ_TYPE_PROJECT, projectId);
        }catch (Exception ex)
        {
            return projectId;
        }
	}

	public static String getIdByObjTabel(JSONObject singleObj) {
		return CommonUtil.combineId(singleObj.getString(ObjectTable.KEY_PJ_ID),
				singleObj.getString(ObjectTable.KEY_OBJ_TYPE), singleObj.getString(ObjectTable.KEY_OBJ_ID));
	}

	public static JSONArray composeUpdateQRCodeArray(Map<String, String> idFilekeyMap) {
		JSONArray arr = new JSONArray();
		for(String id : idFilekeyMap.keySet()){
			JSONObject singleObj = new JSONObject();
			singleObj.put("id", id);
			JSONObject infos = new JSONObject();
			String infoKey = getQRCodeKeyById(id);
			if(infoKey == null)
				continue;
			JSONArray qrCodeArr = new JSONArray();
			JSONObject singleValue = new JSONObject();
			singleValue.put("value", idFilekeyMap.get(id));
			qrCodeArr.add(singleValue);
			infos.put(infoKey, qrCodeArr);
			singleObj.put("infos", infos);
			arr.add(singleObj);
		}
		return arr;
	}

	public static String getQRCodeKeyById(String id) {
		switch (id.substring(0, 2)){
			case Const.OBJ_TYPE_EQUIPMENT:
			case Const.OBJ_TYPE_EQUIPMENT_COMPONENT:
			case Const.OBJ_TYPE_PROPERTY:
				return "EquipQRCode";
			case Const.OBJ_TYPE_SPACE:
			case Const.OBJ_TYPE_ISPACE:
				return "RoomQRCode";
		}
		return null;
	}
}
