package com.joe.base.utils.request;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.joe.base.utils.constans.UserConstans;
import com.joe.base.utils.encryption.MD5;
import com.joe.base.utils.mobile.DeviceUuidFactory;
import com.joe.base.utils.mobile.Installation;
import com.joe.base.utils.other.SPUtils;
import com.qmuiteam.qmui.util.QMUIDeviceHelper;

import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

/**
 * autour: ELEGANT_BIN
 * date: 2018/4/9 18:56
 * update: 2018/4/9 18:56
 * description:
 */

public class RequestUtils {


    /**
     * @param dataMap
     * @param times
     * @return
     * @Title: getSign
     * @Description: TODO(获取签名)
     */
    public static String getSign(Context context, Map<String, Object> dataMap, long times) {
        String sign = "";
        String token = getLoginToken(context);
        if (!TextUtils.isEmpty(token)) {
            MD5 md5 = new MD5();
            Set<String> set = new TreeSet<>();
            Set<String> keys = dataMap.keySet();
            set.addAll(keys);
            StringBuffer buffer = new StringBuffer();
            for (String key : set) {
                buffer.append(key);
                buffer.append("=");
                buffer.append(dataMap.get(key) + "");
            }
            buffer.append("token=" + token + "");
            buffer.append("times=" + times + "");
            sign = md5.GetMD5Code(buffer.toString());
            Log.e("joe", "bufferStr=====> " + buffer.toString());
        }
        return sign;
    }

    //获取登陆token
    public static String getLoginToken(Context context) {
        return (String) SPUtils.get(context, UserConstans.token, "");
    }


    public static String getMobileToken(Context context) {
        if (QMUIDeviceHelper.isTablet(context)) {
            //平板端登錄做下設備区分(pad_用户_机器名_592A9789-43D2-43D1-B184-82235206C3FF)
            boolean flatbedloginStatus = (int) SPUtils.get(context, UserConstans.FLATBED_LOGIN_STATUS, -1) != -1;
            if (flatbedloginStatus) {
                int userId = (int) SPUtils.get(context, UserConstans.memberId, 0);
                String deviceModel = android.os.Build.MODEL;
                return "pad_" + userId + "_" + deviceModel + "_" + getuUid(context);
            }
        }
        return getuUid(context);
    }

    private static String getuUid(Context context) {
        DeviceUuidFactory deviceUuidFactory = new DeviceUuidFactory(context);
        UUID deviceUuid = deviceUuidFactory.getDeviceUuid();
        if (deviceUuid != null) {
            return deviceUuid.toString();
        } else {
            return Installation.id(context);
        }
    }


}
