package com.tsgame.tsgame_niuniu.util;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * QQ分享工具类 - 无需SDK，使用Intent实现
 */
public class QQIntentShareUtil {

    private static final String TAG = "QQIntentShareUtil";

    // QQ可能的包名列表
    private static final String QQ_PACKAGE_NAME = "com.tencent.mobileqq";
    private static final String TIM_PACKAGE_NAME = "com.tencent.tim";
    private static final String QQ_LITE_PACKAGE_NAME = "com.tencent.qqlite";
    private static final String QQ_INTERNATIONAL_PACKAGE_NAME = "com.tencent.mobileqqi";

    // 可能的QQ包名列表
    private static final List<String> QQ_PACKAGES = Arrays.asList(
            QQ_PACKAGE_NAME,           // 标准QQ
            TIM_PACKAGE_NAME,          // TIM
            QQ_LITE_PACKAGE_NAME,      // QQ轻聊版
            QQ_INTERNATIONAL_PACKAGE_NAME  // 国际版QQ
    );

    // QQ分享的Activity组件名称
    private static final String QQ_SHARE_COMPONENT = "com.tencent.mobileqq.activity.JumpActivity";
    private static final String QQ_TIM_SHARE_COMPONENT = "com.tencent.tim.activity.JumpActivity";

    // QQ聊天的Activity组件名称
    private static final String QQ_CHAT_COMPONENT = "com.tencent.mobileqq.activity.ChatActivity";
    private static final String TIM_CHAT_COMPONENT = "com.tencent.tim.activity.ChatActivity";

    // QQ临时会话的Activity组件名称
    private static final String QQ_TEMP_CHAT_COMPONENT = "com.tencent.mobileqq.activity.TempSessionActivity";
    private static final String TIM_TEMP_CHAT_COMPONENT = "com.tencent.tim.activity.TempSessionActivity";

    // QQ空间分享的Activity组件名称
    private static final String QZONE_COMPONENT = "com.tencent.mobileqq.activity.QzonePublishMoodActivity";
    private static final String TIM_QZONE_COMPONENT = "com.tencent.tim.activity.QzonePublishMoodActivity";

    /**
     * 动态获取分享组件（适配鸿蒙等定制系统）
     */
    private ComponentName resolveShareComponent(Activity activity, Intent intent, String packageName) {
        try {
            List<android.content.pm.ResolveInfo> resolveInfoList =
                activity.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            if (resolveInfoList != null && !resolveInfoList.isEmpty()) {
                for (android.content.pm.ResolveInfo resolveInfo : resolveInfoList) {
                    if (packageName.equals(resolveInfo.activityInfo.packageName)) {
                        return new ComponentName(packageName, resolveInfo.activityInfo.name);
                    }
                }
            }
        } catch (Exception e) {}
        return null;
    }

    private static QQIntentShareUtil instance;
    private final Context mContext;
    private QQShareCallback mCallback;

    // 缓存已安装的QQ包名
    private String installedQQPackage = null;

    private QQIntentShareUtil(Context context) {
        this.mContext = context.getApplicationContext();
    }

    public static QQIntentShareUtil getInstance(Context context) {
        if (instance == null && context != null) {
            instance = new QQIntentShareUtil(context);
        }
        return instance;
    }

    /**
     * 设置分享回调
     * @param callback 分享回调
     */
    public void setShareCallback(QQShareCallback callback) {
        this.mCallback = callback;
    }

    /**
     * 检查QQ是否已安装
     * @return 是否安装
     */
    public boolean isQQInstalled() {
        // 如果之前已找到包名，直接返回true
        if (installedQQPackage != null) {
            return true;
        }

        // 检查所有可能的QQ包名
        PackageManager pm = mContext.getPackageManager();
        for (String packageName : QQ_PACKAGES) {
            boolean installed = false;
            try {
                // 1. 尝试获取包信息
                pm.getPackageInfo(packageName, 0);
                installed = true;
            } catch (PackageManager.NameNotFoundException e) {
                // 忽略
            }

            // 2. 如果getPackageInfo失败，尝试获取启动Intent
            if (!installed) {
                try {
                    if (pm.getLaunchIntentForPackage(packageName) != null) {
                        installed = true;
                    }
                } catch (Exception e) {
                    // 忽略
                }
            }
            
            // 3. 尝试查询是否支持分享Intent (针对部分机型/系统的兜底策略)
            if (!installed) {
                try {
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("text/plain");
                    intent.setPackage(packageName);
                    List<?> list = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                    if (list != null && list.size() > 0) {
                        installed = true;
                    }
                } catch (Exception e) {
                    // 忽略
                }
            }

            if (installed) {
                // 找到已安装的QQ，缓存包名
                installedQQPackage = packageName;
                Log.d(TAG, "找到已安装的QQ: " + packageName);
                return true;
            }
        }

        Log.d(TAG, "未找到已安装的QQ应用");
        return false;
    }

    /**
     * 获取已安装的QQ包名
     * @return QQ包名，如果未安装则返回默认包名
     */
    private String getInstalledQQPackage() {
        if (installedQQPackage != null) {
            return installedQQPackage;
        }

        // 如果没有缓存，重新检测
        isQQInstalled();
        return installedQQPackage != null ? installedQQPackage : QQ_PACKAGE_NAME;
    }

    /**
     * 获取QQ分享的组件名称
     */
    private String getQQShareComponent() {
        String packageName = getInstalledQQPackage();
        if (TIM_PACKAGE_NAME.equals(packageName)) {
            return QQ_TIM_SHARE_COMPONENT;
        }
        return QQ_SHARE_COMPONENT;
    }

    /**
     * 获取QQ聊天的组件名称
     */
    private String getQQChatComponent() {
        String packageName = getInstalledQQPackage();
        if (TIM_PACKAGE_NAME.equals(packageName)) {
            return TIM_CHAT_COMPONENT;
        }
        return QQ_CHAT_COMPONENT;
    }

    /**
     * 获取QQ临时会话的组件名称
     */
    private String getQQTempChatComponent() {
        String packageName = getInstalledQQPackage();
        if (TIM_PACKAGE_NAME.equals(packageName)) {
            return TIM_TEMP_CHAT_COMPONENT;
        }
        return QQ_TEMP_CHAT_COMPONENT;
    }

    /**
     * 获取QQ空间分享的组件名称
     */
    private String getQZoneShareComponent() {
        String packageName = getInstalledQQPackage();
        if (TIM_PACKAGE_NAME.equals(packageName)) {
            return TIM_QZONE_COMPONENT;
        }
        return QZONE_COMPONENT;
    }

    /**
     * 分享纯文本到QQ好友
     * @param activity 活动
     * @param text 要分享的文本
     */
    public void shareTextToQQ(Activity activity, String text) {
        // 在鸿蒙卓易通环境下，不完全依赖isQQInstalled，尝试强制拉起
        boolean isPackageDetected = isQQInstalled();
        
        try {
            // 尝试复制文本到剪贴板，作为兜底
            try {
                copyToClipboard(activity, text);
            } catch (Exception e) {
                // 忽略剪贴板异常
            }

            String packageName = getInstalledQQPackage();
            boolean launched = false;
            
            // 方法1: 采用调用系统分享
            try {
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, text);

                // 鸿蒙/卓易通关键适配Flags
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

                String targetPackage = (packageName != null && !packageName.isEmpty()) ? packageName : QQ_PACKAGE_NAME;
                // 通过设包名，系统分享面板中就只会出现QQ相关的组件，从而过滤掉抖音
                intent.setPackage(targetPackage);

                Intent chooser = Intent.createChooser(intent, "分享到QQ");
                chooser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivity(chooser);
                launched = true;

                Log.d(TAG, "成功启动分享");
                activity.runOnUiThread(() -> Toast.makeText(activity, "已将内容复制到剪贴板，请在QQ中粘贴并分享", Toast.LENGTH_LONG).show());
            } catch (Exception e) {
                Log.e(TAG, "启动分享失败: " + e.getMessage());
                final String msg = "启动分享失败: " + e.getMessage();
                activity.runOnUiThread(() -> Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show());
            }

            // 方法2: 如果上面的方法失败，回退到原有的特定Intent启动逻辑
            if (!launched) {
                // 原有的逻辑保留作为备选...
                
                // ... (原有代码可以保留在if (!launched)块中，或简化)
            }
            
            // 假设分享过程启动成功
            if (mCallback != null) {
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    mCallback.onSuccess();
                }, 1000);
            }
        } catch (Exception e) {
            Log.e(TAG, "分享文本到QQ失败: " + e.getMessage(), e);
            
            // 最终兜底：提示手动分享
            Toast.makeText(activity, "暂无法直接拉起QQ，已复制内容，请手动打开QQ粘贴分享", Toast.LENGTH_LONG).show();
            handleShareException(activity, e);
        }
    }

    /**
     * 分享纯文本到QQ空间
     * @param activity 活动
     * @param text 要分享的文本
     */
    public void shareTextToQZone(Activity activity, String text) {
        if (!isQQInstalled()) {
            handleNotInstalled(activity);
            return;
        }

        try {
            String packageName = getInstalledQQPackage();

            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, text);

            // 使用组件名称直接跳转到QQ空间分享界面
            ComponentName comp = new ComponentName(packageName, getQZoneShareComponent());
            intent.setComponent(comp);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            try {
                copyToClipboard(activity, text);
            } catch (Exception e) {
                // 忽略异常
            }

            activity.startActivity(intent);
            Toast.makeText(activity, "已将内容复制到剪贴板，请在QQ空间中粘贴并分享", Toast.LENGTH_LONG).show();

            // 假设分享成功
            if (mCallback != null) {
                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                    mCallback.onSuccess();
                }, 1000);
            }
        } catch (Exception e) {
            Log.e(TAG, "分享文本到QQ空间失败: " + e.getMessage(), e);

// 尝试使用通用系统分享
            try {
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_TEXT, text);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                String packageName = getInstalledQQPackage();
                String targetPackage = (packageName != null && !packageName.isEmpty()) ? packageName : QQ_PACKAGE_NAME;
                intent.setPackage(targetPackage);

                Intent chooser = Intent.createChooser(intent, "分享到QQ空间");
                chooser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivity(chooser);
                Toast.makeText(activity, "已将内容复制到剪贴板，请从打开的界面中粘贴分享", Toast.LENGTH_LONG).show();

                if (mCallback != null) {
                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        mCallback.onSuccess();
                    }, 1000);
                }
            } catch (Exception ex) {
                handleShareException(activity, ex);
            }
        }
    }

    /**
     * 分享图片到QQ
     * @param activity 活动
     * @param localImagePath 本地图片路径
     */
    public void shareImageToQQ(Activity activity, String localImagePath) {
        // 在鸿蒙卓易通环境下，避免过早报错，尝试强制分享
        boolean isPackageDetected = isQQInstalled();

        File imageFile = new File(localImagePath);
        if (!imageFile.exists()) {
            Toast.makeText(activity, "分享图片不存在", Toast.LENGTH_SHORT).show();
            if (mCallback != null) {
                mCallback.onError(-2, "图片文件不存在");
            }
            return;
        }

        try {
            String packageName = getInstalledQQPackage();

            // 创建分享Intent
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("image/*");

            // 根据Android版本使用不同的Uri方式
            Uri imageUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // Android 7.0及以上使用FileProvider
                imageUri = FileProviderUtil.getUriForFile(activity, imageFile);
                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                // Android 7.0以下直接使用文件Uri
                imageUri = Uri.fromFile(imageFile);
            }
            
            shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
            
            // 鸿蒙/卓易通关键适配Flags
            shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            shareIntent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 确保Flags也被设置在Intent上

            // 采用调用系统分享
            boolean launched = false;
            
            try {
                String targetPackage = (packageName != null && !packageName.isEmpty()) ? packageName : QQ_PACKAGE_NAME;
                shareIntent.setPackage(targetPackage); // 限制只能分享到QQ，防止出现抖音

                Intent chooserIntent = Intent.createChooser(shareIntent, "分享到QQ");
                chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                chooserIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 确保Chooser也有权限
                
                activity.startActivity(chooserIntent);
                launched = true;
                Log.d(TAG, "已发送分享图片Intent到QQ系统面板");
            } catch (Exception e) {
                Log.e(TAG, "启动分享图片到QQ系统面板失败: " + e.getMessage());
                final String failMsg = "分享失败: " + e.getMessage();
                activity.runOnUiThread(() -> Toast.makeText(activity, failMsg, Toast.LENGTH_SHORT).show());
            }

            if (launched) {
                if (mCallback != null) {
                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        mCallback.onSuccess();
                    }, 1000);
                }
            } else {
                 Toast.makeText(activity, "分享图片失败，请手动打开QQ分享", Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            Log.e(TAG, "分享图片到QQ失败: " + e.getMessage(), e);
            handleShareException(activity, e);
        }
    }

    /**
     * 分享图片到QQ空间
     * @param activity 活动
     * @param localImagePath 本地图片路径
     */
    public void shareImageToQZone(Activity activity, String localImagePath) {
        if (!isQQInstalled()) {
            handleNotInstalled(activity);
            return;
        }

        File imageFile = new File(localImagePath);
        if (!imageFile.exists()) {
            Toast.makeText(activity, "分享图片不存在", Toast.LENGTH_SHORT).show();
            if (mCallback != null) {
                mCallback.onError(-2, "图片文件不存在");
            }
            return;
        }

        try {
            String packageName = getInstalledQQPackage();

            // 创建分享Intent
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("image/*");

            // 设置组件名称
            ComponentName comp = new ComponentName(packageName, getQZoneShareComponent());
            shareIntent.setComponent(comp);

            // 根据Android版本使用不同的Uri方式
            Uri imageUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // Android 7.0及以上使用FileProvider
                imageUri = FileProviderUtil.getUriForFile(activity, imageFile);
                shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                // Android 7.0以下直接使用文件Uri
                imageUri = Uri.fromFile(imageFile);
            }

            shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
            shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            try {
                activity.startActivity(shareIntent);
                Log.d(TAG, "已发送分享图片Intent到QQ空间");

                // 延迟回调成功
                if (mCallback != null) {
                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        mCallback.onSuccess();
                    }, 1000);
                }
            } catch (android.content.ActivityNotFoundException e) {
                Log.e(TAG, "直接分享到QQ空间失败，尝试系统分享: " + e.getMessage());

                // 采用调用系统分享
                String targetPackage = (packageName != null && !packageName.isEmpty()) ? packageName : QQ_PACKAGE_NAME;
                shareIntent.setComponent(null);
                shareIntent.setPackage(targetPackage);

                Intent chooserIntent = Intent.createChooser(shareIntent, "分享到QQ空间");
                chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivity(chooserIntent);

                // 假设分享成功
                if (mCallback != null) {
                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        mCallback.onSuccess();
                    }, 1000);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "分享图片到QQ空间失败: " + e.getMessage(), e);
            handleShareException(activity, e);
        }
    }

    /**
     * 分享BitMap到QQ
     * @param activity 活动
     * @param bitmap 位图
     * @param isQzone 是否分享到QQ空间
     */
    public void shareBitmapToQQ(Activity activity, Bitmap bitmap, boolean isQzone) {
        if (bitmap == null) {
            Toast.makeText(activity, "分享图片为空", Toast.LENGTH_SHORT).show();
            if (mCallback != null) {
                mCallback.onError(-1, "分享图片为空");
            }
            return;
        }

        try {
            File cacheDir = activity.getExternalCacheDir();
            if (cacheDir == null) {
                cacheDir = activity.getCacheDir();
            }

            File imageFile = new File(cacheDir, "qq_share_" + UUID.randomUUID().toString() + ".jpg");
            FileOutputStream fos = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            fos.flush();
            fos.close();

            // 保存成功，分享图片
            if (isQzone) {
                shareImageToQZone(activity, imageFile.getAbsolutePath());
            } else {
                shareImageToQQ(activity, imageFile.getAbsolutePath());
            }
        } catch (Exception e) {
            Toast.makeText(activity, "保存图片失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            if (mCallback != null) {
                mCallback.onError(-2, "保存图片失败: " + e.getMessage());
            }
        }
    }

    /**
     * 分享多张图片到QQ（群发）
     * @param activity 活动
     * @param imagePaths 图片路径列表
     * @param isQzone 是否分享到QQ空间
     */
    public void shareImagesToQQ(Activity activity, ArrayList<String> imagePaths, boolean isQzone) {
        if (imagePaths == null || imagePaths.isEmpty()) {
            Toast.makeText(activity, "分享图片为空", Toast.LENGTH_SHORT).show();
            if (mCallback != null) {
                mCallback.onError(-1, "分享图片为空");
            }
            return;
        }

        try {
            ArrayList<Uri> imageUris = new ArrayList<>();
            for (String path : imagePaths) {
                File file = new File(path);
                if (file.exists()) {
                    // 根据Android版本使用不同的Uri方式
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        // Android 7.0及以上使用FileProvider
                        Uri fileUri = FileProviderUtil.getUriForFile(activity, file);
                        imageUris.add(fileUri);
                    } else {
                        // Android 7.0以下直接使用文件Uri
                        imageUris.add(Uri.fromFile(file));
                    }
                }
            }

            if (imageUris.isEmpty()) {
                Toast.makeText(activity, "没有有效图片可分享", Toast.LENGTH_SHORT).show();
                if (mCallback != null) {
                    mCallback.onError(-1, "没有有效图片可分享");
                }
                return;
            }

            Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
            // 获取已安装的QQ包名
            String packageName = getInstalledQQPackage();
            //intent.setPackage(packageName); // 不再强制依赖包名
            intent.setType("image/*");
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); // 鸿蒙卓易通适配

            boolean launched = false;

            try {
                String targetPackage = (packageName != null && !packageName.isEmpty()) ? packageName : QQ_PACKAGE_NAME;
                // 采用调用系统分享
                intent.setPackage(targetPackage);

                Intent chooser = Intent.createChooser(intent, isQzone ? "分享到QQ空间" : "分享到QQ");
                chooser.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                chooser.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                
                activity.startActivity(chooser);
                launched = true;
                Log.d(TAG, "已打开系统分享面板进行多图分享");
            } catch (Exception e) {
                Log.e(TAG, "开启系统多图分享到QQ失败: " + e.getMessage());
                if (mCallback != null) {
                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        mCallback.onSuccess();
                    }, 1000);
                }
            }

        } catch (Exception e) {
            handleShareException(activity, e);
        }
    }

    /**
     * 分享网页链接到QQ
     * @param activity 活动
     * @param title 标题
     * @param description 描述
     * @param webUrl 网页链接
     * @param imageUrl 图片链接(可选)
     * @param isQzone 是否分享到QQ空间
     */
    public void shareWebPageToQQ(Activity activity, String title, String description, String webUrl, String imageUrl, boolean isQzone) {
        if (!isQQInstalled()) {
            handleNotInstalled(activity);
            return;
        }

        try {
            // QQ支持直接分享网页链接，但实际上QQ会解析文本内容来查找URL
            StringBuilder sb = new StringBuilder();
            if (!TextUtils.isEmpty(title)) {
                sb.append(title).append("\n\n");
            }
            if (!TextUtils.isEmpty(description)) {
                sb.append(description).append("\n\n");
            }
            if (!TextUtils.isEmpty(webUrl)) {
                sb.append(webUrl);
            }

            String text = sb.toString().trim();

            copyToClipboard(activity, text);

            if (isQzone) {
                shareTextToQZone(activity, text);
            } else {
                shareTextToQQ(activity, text);
            }
        } catch (Exception e) {
            handleShareException(activity, e);
        }
    }

    /**
     * 处理未安装QQ的情况
     */
    private void handleNotInstalled(Activity activity) {
        Toast.makeText(activity, "请先安装QQ客户端", Toast.LENGTH_SHORT).show();
        if (mCallback != null) {
            mCallback.onError(-1, "未安装QQ客户端");
        }
    }

    /**
     * 处理分享异常
     */
    private void handleShareException(Activity activity, Exception e) {
        Toast.makeText(activity, "分享失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        if (mCallback != null) {
            mCallback.onError(-3, "分享失败: " + e.getMessage());
        }
    }

    /**
     * 兼容性复制文本到剪贴板
     * 支持API 9及以上版本
     * @param context 上下文
     * @param text 要复制的文本
     */
    private void copyToClipboard(Context context, String text) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                // API 11及以上使用ClipboardManager
                android.content.ClipboardManager clipboardManager =
                    (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                android.content.ClipData clipData =
                    android.content.ClipData.newPlainText("分享内容", text);
                clipboardManager.setPrimaryClip(clipData);
            } else {
                // API 11以下使用旧版的android.text.ClipboardManager
                android.text.ClipboardManager clipboardManager =
                    (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                clipboardManager.setText(text);
            }
        } catch (Exception e) {
            Log.e(TAG, "复制到剪贴板失败: " + e.getMessage(), e);
        }
    }

    /**
     * QQ分享回调接口
     */
    public interface QQShareCallback {
        /**
         * 分享成功
         */
        void onSuccess();

        /**
         * 分享失败
         * @param code 错误码
         * @param msg 错误信息
         */
        void onError(int code, String msg);

        /**
         * 分享取消
         */
        void onCancel();
    }
}

