package com.sobot.network.http.upload;

import android.text.TextUtils;

import com.sobot.network.http.model.UploadFileResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class SobotCommonGsonUtil {

    public static SobotUploadModel jsonToCommonModel(String json) {
        if (TextUtils.isEmpty(json))
            return null;
        SobotUploadModel bean = new SobotUploadModel();
        try {
            JSONObject jsonObject = new JSONObject(json);
            if (jsonObject.has("code")) {
                bean.setCode(filterNull(jsonObject.optString("code")));
            }
            if ("1".equals(filterNull(jsonObject.optString("code")))) {
                SobotUploadModelBase base = new SobotUploadModelBase();
                JSONObject data = jsonObject.getJSONObject("data");
                if (data.has("status")) {
                    base.setStatus(filterNull(data.optString("status")));
                }
                if (data.has("switchFlag")) {
                    base.setSwitchFlag(filterNull(data.optString("switchFlag")));
                }

                if (data.has("msg")) {
                    base.setMsg(filterNull(data.optString("msg")));
                }
                bean.setData(base);
            }
            if (jsonObject.has("msg")) {
                bean.setMsg(filterNull(jsonObject.optString("msg")));
            }
        } catch (JSONException e) {
//            e.printStackTrace();
        }
        return bean;
    }

    public static UploadFileResult obtainUploadFileResult(String json) {
        if (TextUtils.isEmpty(json)) {
            return null;
        }
        UploadFileResult data;
        try {
            JSONObject jsonObject = new JSONObject(json);
            data = new UploadFileResult();
            data.setMsgId(jsonObject.optString("msgId"));
            data.setUrl(jsonObject.optString("msg"));
            return data;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }


    private static String filterNull(String str) {
        if (!TextUtils.isEmpty(str)) {
            if (str.equals("null")) {
                return null;
            } else {
                String msgHint = str.replace("\n", "<br/>");
                if (msgHint.startsWith("<br/>")) {
                    msgHint = msgHint.substring(5, msgHint.length());
                }

                if (msgHint.endsWith("<br/>")) {
                    msgHint = msgHint.substring(0, msgHint.length() - 5);
                }
                return msgHint;
            }
        } else {
            return null;
        }
    }

    private static String filterNullStr(String str) {
        if (!str.equalsIgnoreCase("null")) {
            return str;
        }
        return null;
    }

    public static String map2Json(Map<String, String> map) {
        if (map != null && map.size() > 0) {
            JSONObject a = new JSONObject(map);
            return a.toString();
        }
        return "";
    }

    public static String map2Str(Map<String, String> map) {
        if (map == null) {
            return "";
        }
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> entry = it.next();
                if ("items".equals(entry.getKey()) || "level".equals(entry.getKey())) {
                    sb.append("\"" + entry.getKey() + "\":" + entry.getValue() + ",");
                } else {
                    sb.append("\"" + entry.getKey() + "\":\"" + entry.getValue() + "\",");
                }
            }
            String tmpstr = sb.toString();
            return tmpstr.substring(0, tmpstr.lastIndexOf(",")) + "}";
        } catch (Exception e) {
            return "";
        }
    }


    public static <T> JSONArray praseList2Json(List<T> list) {
        JSONArray json = new JSONArray();
        try {
            for (T data : list) {
                JSONObject jo = new JSONObject();
                Field field[] = data.getClass().getDeclaredFields();
                for (Field f : field) {
                    f.setAccessible(true);
                    Method m = convertGetter(data.getClass(), f.getName());
                    if (m != null) {
                        String result = (String) m.invoke(data);
                        jo.put(f.getName(), result);
                    }
                }
                json.put(jo);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    public static Method convertGetter(Class cla, String field, Class<?>... parameterTypes) {
        String str1 = field.substring(0, 1);
        String str2 = field.substring(1);
        String method_set = "get" + str1.toUpperCase() + str2;
        Method method1 = null;
        try {
            method1 = cla.getMethod(method_set, parameterTypes);
        } catch (NoSuchMethodException e) {
            //e.printStackTrace();
        }
        return method1;
    }

    /**
     * 判断是否为空
     */
    public static boolean isEmpty(Object str) {
        return (str == null || "".equals(str) || "null".equals(str));
    }


}