package com.bocloud.ims.service.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

public class ClassHelper {

    public static Object merger(Object target, Object source) throws Exception {
        Class<?> otherClass = source.getClass();
        Field[] otherFields = otherClass.getDeclaredFields();
        Map<String, Object> map = new HashMap<String, Object>();
        for (Field field : otherFields) {
            String fieldName = field.getName();
            String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            Method getMethod = otherClass.getMethod(methodName);
            map.put(fieldName, getMethod.invoke(source));
        }

        Class<?> objectClass = target.getClass();
        Field[] fields = objectClass.getDeclaredFields();
        for (Field field : fields) {
            String fieldName = field.getName();
            if (null == map.get(fieldName)) {
                continue;
            }
            String methodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            Method setMethod = objectClass.getMethod(methodName, field.getType());
            if (null != map.get(fieldName)) {
                setMethod.invoke(target, map.get(fieldName));
            }
        }
        return target;
    }

    public static JSONObject getJson(String result) {
        JSONObject json = new JSONObject();
        String[] data = result.split("\n");
        for (String str : data) {
            int index = str.indexOf(":");
            if (index < 0) {
                continue;
            }
            String key = str.substring(0, index);
            String value = str.substring(index + 1);
            json.put(key.trim(), value.trim());
        }
        return json;
    }

    public static JSONObject getJson(String result, String identify) {
        JSONObject json = new JSONObject();
        String[] data = result.split("\n");
        for (String str : data) {
            int index = str.indexOf(identify);
            if (index < 0) {
                continue;
            }
            String key = str.substring(0, index);
            String value = str.substring(index + 1);
            json.put(key.trim(), value.trim());
        }
        return json;
    }
}
