package com.ttstd.dialer.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.hjq.toast.Toaster;
import com.ttstd.dialer.R;

import java.util.List;

public class ApkUtils {
    private static final String TAG = "ApkUtils";

    public static boolean isInstalled(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) return false;
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES);
            return packageInfo != null;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean openPackage(Context context, String packageName) {
        Context pkgContext = getPackageContext(context, packageName);
        Intent intent = getAppOpenIntentByPackageName(context, packageName);
        if (pkgContext != null && intent != null) {
            pkgContext.startActivity(intent);
            return true;
        }
        Log.e(TAG, "openPackage:  can not open " + packageName);
        Toaster.show("打开失败");
        return false;
    }

    public static Context getPackageContext(Context context, String packageName) {
        Context pkgContext = null;
        if (context.getPackageName().equals(packageName)) {
            pkgContext = context;
        } else {
            // 创建第三方应用的上下文环境
            try {
                pkgContext = context.createPackageContext(packageName,
                        Context.CONTEXT_IGNORE_SECURITY
                                | Context.CONTEXT_INCLUDE_CODE);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return pkgContext;
    }


    public static Intent getAppOpenIntentByPackageName(Context context, String packageName) {
        //Activity完整名
        String mainAct = null;
        //根据包名寻找
        PackageManager pkgMag = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);

        List<ResolveInfo> list = pkgMag.queryIntentActivities(intent,
                PackageManager.GET_ACTIVITIES);
        for (int i = 0; i < list.size(); i++) {
            ResolveInfo info = list.get(i);
            if (info.activityInfo.packageName.equals(packageName)) {
                mainAct = info.activityInfo.name;
                break;
            }
        }
        if (TextUtils.isEmpty(mainAct)) {
            return null;
        }
        intent.setComponent(new ComponentName(packageName, mainAct));
        return intent;
    }

    public static boolean openApp(Context context, ComponentName componentName) {
        Intent intent = new Intent()
                .setComponent(componentName)
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            context.startActivity(intent);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "openApp: " + e.getMessage());
        }
        return false;
    }

    public static Drawable getDrawableFromComponentName(Context context, ComponentName componentName) {
        try {
            PackageManager packageManager = context.getPackageManager();
            ActivityInfo activityInfo = packageManager.getActivityInfo(componentName, 0);
            ApplicationInfo applicationInfo = activityInfo.applicationInfo;
            Drawable activityIcon = applicationInfo.loadIcon(packageManager);
            return activityIcon;

        } catch (PackageManager.NameNotFoundException e) {
            // 处理未找到组件的情况
            e.printStackTrace();
            // 可以根据需要设置一个默认图标或提示用户
        }
        return context.getDrawable(R.mipmap.ic_launcher);
    }

    public static String getAppName(Context context, ComponentName componentName) {
        try {
            PackageManager packageManager = context.getPackageManager();
            ActivityInfo activityInfo = packageManager.getActivityInfo(componentName, 0);
            ApplicationInfo applicationInfo = activityInfo.applicationInfo;
            String name = applicationInfo.loadLabel(packageManager).toString();
            return name;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "未知";
    }

    public static List<ResolveInfo> getAllLauncherResolveInfo(Context context) {
        PackageManager packageManager = context.getPackageManager();
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        // 查询所有包含CATEGORY_LAUNCHER的Activity
        List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL);
        return resolveInfoList;
    }

    public static List<ResolveInfo> getResolveInfoByPackageName(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager(); // 在Activity中使用

        // 构建查询Intent
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setPackage(packageName); // 设置包名过滤

        // 查询匹配的Activity列表
        List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, 0);
        return resolveInfoList;
    }

    /**
     * 判断是否为系统应用
     *
     * @param context 上下文
     * @param pkgName 包名
     * @return
     */
    public static boolean isSystemApp(Context context, String pkgName) {
        boolean isSystemApp = false;
        PackageInfo pi = null;
        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(pkgName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("isSystemApp: ", "NameNotFoundException:" + e.getMessage());
        }
        // 是系统中已安装的应用
        if (pi != null) {
            boolean isSysApp = (pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 1;
            boolean isSysUpd = (pi.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1;
            isSystemApp = isSysApp || isSysUpd;
        }
        return isSystemApp;
    }


    public static void openAppStore(Context context, String pkg) {
        Uri uri = Uri.parse("market://details?id=" + pkg);
        Intent storeIntent = new Intent(Intent.ACTION_VIEW, uri);
        storeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            context.startActivity(storeIntent);
        } catch (Exception e1) {
            Log.e(TAG, "openWeixin storeIntent: " + e1.getMessage());
        }
    }
}
