package com.ydl.utils;

import android.text.TextUtils;

import com.ydl.ydlcommon.base.BaseApp;
import com.ydl.ydlcommon.data.PlatformDataManager;
import com.ydl.ydlcommon.data.http.EncryptUtils;
import com.ydl.ydlcommon.modular.IPlatformUserModuleService;
import com.ydl.ydlcommon.modular.ModularServiceManager;
import com.ydl.ydlcommon.router.YdlUserInfo;
import com.yidianling.common.tools.RxAppTool;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2018/04/27
 *
 * 临时性的工具类，后续删除
 */

public class WebUrlParamsUtils {

    /**
     * h5添加认证url后缀
     *
     * @param url 原始url
     * @return 加签后的完整url
     */
    public static String getSuffix(String url,String appendSuffix) {

        String myUrl = url;

        //存储原url所带参数
        Map<String, String> map = getUrlParams(url);
        if(!TextUtils.isEmpty(appendSuffix)) {
            Map<String, String> appendMap = getUrlParams(appendSuffix);
            if(appendMap!=null && appendMap.size()!=0) {
                map.putAll(appendMap);
            }
        }

        String[] keys = new String[map.size()];
        String[] values = new String[map.size()];

        int i = 0;

        for (String key : map.keySet()) {
            keys[i] = key;
            values[i] = map.get(key);
            i++;
        }

        //去除原url所有参数
        if (myUrl.contains("?")) {
            myUrl = myUrl.substring(0, myUrl.indexOf("?"));
        }

        //重新组装url所有参数并加签名
        return myUrl + getSuffixNoButOther(keys, values);

    }

    /**
     * 传入完整url
     */
    public static Map<String, String> getUrlParams(String url) {
        Map<String, String> map = new HashMap<>();
        try {
            if (url != null && !url.trim().equals("")) {
                if (url.contains("?")||url.contains("&")) {
                    if (!url.endsWith("?")) {
                        //?号结尾表示没有参数
                        //有参数 取出所有参数加签
                        String urlQian = url.substring(url.lastIndexOf("?") + 1, url.length());
                        //原始键值对数组
                        String[] array = urlQian.split("&");
                        //解析后的集合
                        for (String str : array) {
                            String[] ys = str.split("=");
                            if (ys.length > 1){
                                map.put(ys[0], ys[1]);
                            }else {
                                map.put(ys[0], "");
                            }
                        }

                        return map;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    //签名里面还要加别的东西
    private static String getSuffixNoButOther(String[] keys, String[] values) {
        String time = System.currentTimeMillis() / 1000 + "";

        TreeMap<String, String> mTree = new TreeMap<>();

        if (keys != null) {
            for (int index = 0; index < keys.length; index++) {
                mTree.put(keys[index], values[index]);
            }
        }
        //移除sign参数，防止与后面拼接冲突
        mTree.remove("sign");
        mTree.remove("uid");
        mTree.remove("accessToken");
        mTree.remove("v");
        mTree.remove("isFromApp");
        mTree.remove("ffrom");
        mTree.remove("ts");
        IPlatformUserModuleService userService = ModularServiceManager.INSTANCE.getPlatformUserService();
        YdlUserInfo userInfo = null;
        if(userService!=null) {
         userInfo = ModularServiceManager.INSTANCE.getPlatformUserService().getUser();
        }
        //添加公用参数
        if (userInfo != null) {
            mTree.put("uid", userInfo.getUserId());
            mTree.put("accessToken", userInfo.getToken());
        }
        mTree.put("v", RxAppTool.getAppVersionName(BaseApp.Companion.getApp()));
        mTree.put("isFromApp", "1");//1表示用户版调用接口
        mTree.put("ffrom", PlatformDataManager.INSTANCE.getRam().getChannelName());
        mTree.put("ts", time);

        Set<String> keySet = mTree.descendingKeySet();
        StringBuilder subject = new StringBuilder();
        StringBuilder toSignature = new StringBuilder();
        for (String key : keySet) {
            subject.append(key).append("=").append(mTree.get(key)).append("&");
            toSignature.append(key).append("=").append(mTree.get(key)).append("&");
        }

        toSignature.deleteCharAt(toSignature.length() - 1);

        toSignature.append("dc59cf294f37d237c1f06240568ffe21");
        subject.append("sign=").append(EncryptUtils.encryptMD5ToString(toSignature.toString()));
        return "?" + subject.toString();
    }
}
