package com.dahe.pass.net;

import android.util.Log;

import com.dahe.mylibrary.net.JsonUtils;
import com.dahe.mylibrary.utils.MD5Utils;
import com.dahe.mylibrary.utils.StringUtils;
import com.dahe.mylibrary.utils.TimeUtil;
import com.google.gson.Gson;

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

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by Administrator on 2017/4/15 0015.
 */

public class CreateJsonUtils {
    public static CreateJsonUtils utils = null;
    private static final String TAG = "GetJsonUtils";

    public static CreateJsonUtils getInstance() {
        if (null == utils) {
            synchronized (CreateJsonUtils.class) {
                if (null == utils) {
                    utils = new CreateJsonUtils();
                }
            }
        }
        return utils;
    }

    /**
     * 得到请求体的json数据
     *
     * @param key   jsonObject的key
     * @param value jsonObject的value  如果要请求jsonObject里面嵌套jsonObject的value只需要传map 否就传简单的数据类型
     * @return
     */
    public String getRequest(String[] key, Object[] value) {
        Map<String, Object> map = new HashMap<>();
        for (int i = 0; i < key.length; i++) {
            if (value[i] instanceof Map) {
                Map<Object, Object> sonMap = new HashMap<>();
                Map<Object, Object> sonDateMap = (Map<Object, Object>) value[i];
                List<String> keyList = getMapKey(sonDateMap);
                for (int j = 0; j < keyList.size(); j++) {
                    sonMap.put(keyList.get(j), sonDateMap.get(keyList.get(j)));
                }
                map.put(key[i], sonMap);
            } else if (value[i] instanceof List) {
                map.put(key[i], value[i]);
            } else if (value[i] instanceof String) {
                map.put(key[i], value[i].toString());
            } else {
                map.put(key[i], value[i]);
            }
        }
        map.put("api_key", "xccdb-power-bank");
        map.put("sign", MD5Utils.md5(JsonUtils.getInstance().getGson().toJson(map)));
        map.put("time", TimeUtil.getNowMills());
        Log.i(TAG, new Gson().toJson(map));
        return new Gson().toJson(map);
    }

    /**
     * 获取map里面的所有值
     *
     * @param hashmp
     * @return
     */
    public List<String> getMapKey(Map hashmp) {
        List<String> list = new ArrayList<>();
        Set set = hashmp.keySet();
        Iterator iter = set.iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            list.add(key);
        }
        return list;
    }

    public Map<String, Integer> getPagerMap(int page, int count) {
        Map<String, Integer> map = new HashMap<>();
        map.put("page", page);
        map.put("count", count);
        return map;
    }

    /**
     * 无参数的请求
     *
     * @return
     */
    public Map<String, RequestBody> createRequestBody() {
        return createRequestBody(new String[]{}, new String[]{});
    }

    /**
     * 生成请求的body
     *
     * @param key
     * @param value
     * @return
     */
    public Map<String, RequestBody> createRequestBody(String[] key, Object[] value) {
        Map<String, RequestBody> requestBodyMap = new HashMap<>();
        Map<String, Object> requestDataMap = new HashMap<>();
        String signStr = "";
        for (int i = 0; i < key.length; i++) {
            requestDataMap.put(key[i], value[i]);
        }
        try {
            signStr = (sign1(requestDataMap) + "&api_key=xccdb-power-bank").replaceFirst("&", "");
            Log.i(TAG, "createRequestBody: " + sign1(requestDataMap));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.i(TAG, "createRequestBody: " + signStr);
        for (String keySet : requestDataMap.keySet()) {
            requestBodyMap.put(keySet, RequestBody.create(MediaType.parse("multipart/form-data"), requestDataMap.get(keySet) + ""));
        }
        Log.i(TAG, "createRequestBody: " + MD5Utils.md5((signStr)));
        requestBodyMap.put("sign", RequestBody.create(MediaType.parse("multipart/form-data"),
                MD5Utils.md5((signStr))));
        requestBodyMap.put("time", RequestBody.create(MediaType.parse("multipart/form-data"), TimeUtil.getNowMills() / 1000 + ""));
        return requestBodyMap;
    }

    public String sign1(Map params) throws JSONException {
        JSONObject header = new JSONObject(JsonUtils.getInstance().getGson().toJson(params));
//获取header元素集合
        Iterator headerIt = header.keys();
        List<String> list = new ArrayList<String>();
//把header元素集合迭代 出 "param=value"形式字符串放入list集合中
        while (headerIt.hasNext()) {
            String param = headerIt.next().toString();
            String value = StringUtils.encode(header.getString(param));
            list.add(param + "=" + value);
        }
        Collections.sort(list);
        String paramStr = "";
//迭代list拼装签名sign
        for (int i = 0; i < list.size(); i++) {
            paramStr += "&" + list.get(i);
        }
        String signStr = paramStr;
        return signStr;
    }
}
