package com.zztrapp.zztrapp.download;

import android.text.TextUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * 项目名称：
 * 类描述：请求参数处理工具类
 * @Author: Bby
 * @CreateDate: 2021/11/20
 * 修改备注：
 */
public class THttpParameterUtils {

    /**
     * 仅仅用于登录/获取用户信息接口
     * 方法用途: 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序），并且生成url参数串<br>
     * 实现步骤: <br>
     *
     * @param paraMap    要排序的Map对象
     * @param urlEncode  是否需要urlencode
     * @param keyToLower 是否需要将Key转换为全小写 true:key转化成小写，false:不转化
     * @return 返回url参数串 可用于get请求生成参数串
     */
    public static String formatUrlMapGetLoginParameter(Map<String, String> paraMap, boolean urlEncode, boolean keyToLower) {

        String buff = "";
        Map<String, String> tmpMap = paraMap;
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(
                    tmpMap.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds,
                    new Comparator<Map.Entry<String, String>>() {

                        @Override
                        public int compare(Map.Entry<String, String> o1,
                                           Map.Entry<String, String> o2) {
                            return (o1.getKey()).toString().compareTo(
                                    o2.getKey());
                        }
                    });
            // 构造URL 键值对的格式
            StringBuilder buf = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (!TextUtils.isEmpty(item.getKey())) {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (urlEncode) {
                        val = URLEncoder.encode(val, "utf-8");
                    }
                    if (keyToLower) {
                        buf.append(key.toLowerCase() + "=" + val);
                    } else {
                        buf.append(key + "=" + val);
                    }
                    buf.append("&");
                }

            }
            buff = buf.toString();
            if (!buff.isEmpty()) {
                buff = buff.substring(0, buff.length() - 1);
            }
        } catch (Exception e) {
//            TLogUtils.e("formatUrlMapGetLoginParameter 请求参数格式化异常: " + e.toString());
            return null;
        }

        return buff;
    }

    /**
     * 获取6位随机数
     *
     * @return
     */
    public static String getRand() {
        int num = (int) ((Math.random() * 9 + 1) * 100000);
        String nonce = String.valueOf(num);
        return nonce;
    }

    /**
     * 利用java原生的摘要实现SHA256加密
     *
     * @param str 加密后的报文
     * @return
     */
    public static String getSHA256StrJava(String str) {
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            encodeStr = byte2Hex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }

    /**
     * 将byte转为16进制
     *
     * @param bytes
     * @return
     */
    private static String byte2Hex(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        String temp = null;
        for (int i = 0; i < bytes.length; i++) {
            temp = Integer.toHexString(bytes[i] & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                stringBuffer.append("0");
            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

    /**
     * 添加公共签名参数
     *
     * @param requestParameters
     * @return
     */
    public static Map<String, String> generatorSignature(Map<String, String> requestParameters) {

//        long timestamp = Calendar.getInstance().getTimeInMillis() / 1000;
//        requestParameters.put("appId", connectOption.getAppId());
//        requestParameters.put("userId", connectOption.getUserId());
//        requestParameters.put("deviceId", TGetDeviceId.getDeviceId(TIMBaseManager.getInstance().getContext()));
//
//        requestParameters.put("timestamp", String.valueOf(timestamp));
//        requestParameters.put("nonce", nonce);
//        String signature = TStringUtils.getSHA256StrJava(connectOption.getAppId() + connectOption.getUserId() + timestamp + nonce + TStringUtils.getSHA256StrJava(connectOption.getAccessToken()));
//        requestParameters.put("signature", signature);
//
//        return requestParameters;
        return null;
    }

    /**
     * 添加公共签名参数
     * <p>
     * 未登录时使用
     */
    public static Map<String, String> generatorSignatureWithoutConnect(String appId, String userId, String accessToken, Map<String, String> requestParameters) {

//        long timestamp = Calendar.getInstance().getTimeInMillis() / 1000;
//        String nonce = TCommonUtils.getRand();
//
//        requestParameters.put("appId", appId);
//        requestParameters.put("userId", userId);
//        requestParameters.put("deviceId", TGetDeviceId.getDeviceId(TIMBaseManager.getInstance().getContext()));
//
//        requestParameters.put("timestamp", String.valueOf(timestamp));
//        requestParameters.put("nonce", nonce);
//        String signature = TStringUtils.getSHA256StrJava(appId + userId + timestamp + nonce + TStringUtils.getSHA256StrJava(accessToken));
//        requestParameters.put("signature", signature);
//
//        return requestParameters;
        return null;
    }

    /**
     * 拼接文件下载url
     *
     * @param fileId
     * @return
     */
    public static String getDownLoadFileUrlById(String fileId) {

//        Map<String, String> paramsMap = new HashMap<>();
//        paramsMap.put("fileId", fileId);
//
//        THttpParameterUtils.generatorSignature(paramsMap);
//
//        String requestUrlParameters = THttpParameterUtils.formatUrlMapGetLoginParameter(paramsMap, false, false);
//        String url = TIMBaseManager.getInstance().getInitOption().getApiUrl() + TUrlConstants.FILE_DOWNLOAD;
//
//        return url + "?" + requestUrlParameters;
        return null;
    }

}
