package com.sheep.gamegroup.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;

import java.util.List;
import java.util.Locale;

/**
 * Created by realicing on 2018/11/8.
 * realicing@sina.com
 */
public class QQUtil {

    public static void skip1(Activity activity, String qq) {
        String url = String.format(Locale.CHINA, "mqqwpa://im/chat?chat_type=wpa&;uin=%s&;site=qq&;menu=yes", qq);
        activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    }

    public static void skip2(Activity activity, String qq) {
        String url = String.format(Locale.CHINA, "http://wpa.qq.com/msgrd?v=3&;uin=%s&;site=qq&;menu=yes", qq);
        activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    }

    public static void skip3(Activity activity, String qq) {
        if (isQQClientAvailable(activity)) {
            // 跳转到客服的QQ
            String url = String.format(Locale.CHINA, "mqqwpa://im/chat?chat_type=wpa&uin=%s", qq);
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            // 跳转前先判断Uri是否存在，如果打开一个不存在的Uri，App可能会崩溃
            if (isValidIntent(activity, intent)) {
                activity.startActivity(intent);
            }
        }
    }/**
     * 判断 用户是否安装QQ客户端
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equalsIgnoreCase("com.tencent.qqlite") || pn.equalsIgnoreCase("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * 判断 Uri是否有效
     */
    public static boolean isValidIntent(Context context, Intent intent) {
        PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
        return !activities.isEmpty();
    }
}
