package com.tagmae.tsgame_erwang;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tagmae.tsgame_erwang.utils.Base64ImageUtil;
import com.tsgame.tsgame_niuniu.simcpux.bean.sharetypeBean;
import com.tsgame.tsgame_niuniu.util.DouYinIntentShareUtil;
import com.tsgame.tsgame_niuniu.util.FileProviderUtil;

import java.io.File;
import java.io.FileOutputStream;

/**
 * 抖音分享测试辅助类
 */
public class DouYinIntentShareHelper {

    /**
     * 测试抖音分享
     *
     * @param context  上下文
     * @param jsonData 分享数据JSON字符串
     */
    public static void doDouYinShare(Context context, String jsonData) {
        try {
            // 解析JSON数据
            Gson gson = new Gson();
            sharetypeBean bean = gson.fromJson(jsonData, sharetypeBean.class);

            // 初始化抖音分享工具
            DouYinIntentShareUtil douYinIntentShareUtil = DouYinIntentShareUtil.getInstance(context);

            // 检查抖音是否已安装 - HarmonyOS兼容性修改：移除强制检查
            // if (!douYinIntentShareUtil.isDouyinInstalled()) {
            //    Toast.makeText(context, "抖音未安装，无法进行抖音分享测试", Toast.LENGTH_SHORT).show();
            //    return;
            // }

            // 设置分享回调
            douYinIntentShareUtil.setShareCallback(new DouYinIntentShareUtil.DouYinShareCallback() {
                @Override
                public void onSuccess() {
                    ((Activity) context).runOnUiThread(() ->
                            Toast.makeText(context, "抖音分享成功", Toast.LENGTH_SHORT).show()
                    );
                }

                @Override
                public void onError(int errorCode, String errorMsg) {
                    ((Activity) context).runOnUiThread(() ->
                            Toast.makeText(context, "抖音分享失败: " + errorMsg, Toast.LENGTH_SHORT).show()
                    );
                }

                @Override
                public void onCancel() {
                    ((Activity) context).runOnUiThread(() ->
                            Toast.makeText(context, "抖音分享被取消", Toast.LENGTH_SHORT).show()
                    );
                }
            });

            // 获取分享类型和图片路径
            String type = bean.getType();
            String imagePath = bean.getDescription(); // 使用WebpageUrl作为图片/视频路径
            String hashTag = "#抖音分享"; // 默认话题标签

            // 为标题添加至话题标签中
            if (bean.getTitle() != null && !bean.getTitle().isEmpty()) {
                hashTag = "#" + bean.getTitle();
            }

            // 显示测试开始提示
            Toast.makeText(context, "正在分享到抖音", Toast.LENGTH_SHORT).show();

            // 获取分享目标类型：主页(默认)、私信或群聊
            String shareTarget = "private_message";
//            if (shareTarget == null || shareTarget.isEmpty()) {
//                shareTarget = "feed"; // 默认分享到主页
//            }

            // 根据分享目标类型执行不同的分享操作
            if ("private_message".equals(shareTarget)) {
                // 分享到私信
                shareToPrivateMessage(context, douYinIntentShareUtil, type, bean, imagePath);
            } else if ("group_chat".equals(shareTarget)) {
                // 分享到群聊
                shareToGroupChat(context, douYinIntentShareUtil, type, bean, imagePath);
            } else {
                // 默认分享到主页
//                shareToFeed(context, douYinIntentShareUtil, type, bean, imagePath);
            }

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context, "抖音分享出错: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 分享到抖音私信
     */
    private static void shareToPrivateMessage(Context context, DouYinIntentShareUtil douYinIntentShareUtil, String type, sharetypeBean bean, String imagePath) {
        StringBuilder content = new StringBuilder();

        // 构建要分享的文本内容
        if (bean.getTitle() != null && !bean.getTitle().isEmpty()) {
            content.append(bean.getTitle()).append("\n\n");
        }

        if (bean.getDescription() != null && !bean.getDescription().isEmpty()) {
            content.append(bean.getDescription());
        }


        String textContent = content.toString();

        // 根据类型执行不同的分享操作
        if (type != null && type.equals("3") && imagePath != null) {
            // 准备图片
            try {

            } catch (Exception e) {
                e.printStackTrace();
                // 如果图片准备失败，至少分享文本
                //douYinIntentShareUtil.shareToPrivateMessage((Activity) context, textContent, null, null);
            }
        } else if (type != null && type.equals("4") && imagePath != null) {
            // 准备视频URI
            try {
                File videoFile = new File(imagePath);
                if (videoFile.exists()) {
                    Uri videoUri = FileProviderUtil.getUriForFile(context, videoFile);
                    if (videoUri != null) {
                        // 分享视频到私信
                        douYinIntentShareUtil.shareToPrivateMessage((Activity) context, textContent, videoUri, "video");
                    } else {
                        // URI为空，退回到纯文本分享
                        douYinIntentShareUtil.shareToPrivateMessage((Activity) context, textContent, null, null);
                    }
                } else {
                    // 文件不存在，退回到纯文本分享
                    douYinIntentShareUtil.shareToPrivateMessage((Activity) context, textContent, null, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
                // 如果视频准备失败，至少分享文本
                douYinIntentShareUtil.shareToPrivateMessage((Activity) context, textContent, null, null);
            }
        } else if (type != null && type.equals("2")) {
            // 处理Base64图片分享
//            String description = bean.getDescription();
//
//            if (!TextUtils.isEmpty(description)) {
//                Bitmap bitmap = Base64ImageUtil.base64ToBitmap(description);
//                if (bitmap != null) {
//                    try {
//                        douYinIntentShareUtil.shareBitmapToDouyin((Activity) context,bitmap);
//                        bitmap.recycle();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            }            // 图片分享 - 使用Canvas截图，直接分享到私信
            GlobalWebViewHelper.getCanvasBase64(new WebViewScreenshotUtil.CanvasToBase64Callback() {
                @Override
                public void onSuccess(String canvasBase64) {
                    // 使用Canvas截图的base64数据，直接分享到私信
                    Bitmap bitmap = Base64ImageUtil.base64ToBitmap(canvasBase64);
                    if (bitmap != null) {
                        try {
                            // 直接分享到私信，不弹出选择器
                            shareImageDirectToPrivateMessage((Activity) context, bitmap);
                            bitmap.recycle();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onError(String error) {
                    // Canvas截图失败，提示用户
                    ((Activity) context).runOnUiThread(() ->
                        Toast.makeText(context, "截图失败: " + error, Toast.LENGTH_SHORT).show()
                    );
                }            });

            // 如果处理失败，退回到纯文本分享
            //douYinIntentShareUtil.shareToPrivateMessage((Activity) context, textContent, null, null);
        } else {
            // 只分享文本 - 直接使用Intent分享而不是复制粘贴方式
            shareWebPageDirectToDouYin((Activity) context, bean.getTitle(), bean.getDescription(), "");
        }
    }

    /**
     * 分享到抖音群聊
     */
    private static void shareToGroupChat(Context context, DouYinIntentShareUtil douYinIntentShareUtil, String type, sharetypeBean bean, String imagePath) {
        StringBuilder content = new StringBuilder();

        // 构建要分享的文本内容
        if (bean.getTitle() != null && !bean.getTitle().isEmpty()) {
            content.append(bean.getTitle()).append("\n\n");
        }

        if (bean.getDescription() != null && !bean.getDescription().isEmpty()) {
            content.append(bean.getDescription());
        }


        String textContent = content.toString();

        // 根据类型执行不同的分享操作
        if (type != null && type.equals("3") && imagePath != null) {
            // 准备图片URI
            try {
                File imageFile = new File(imagePath);
                if (imageFile.exists()) {
                    Uri imageUri = FileProviderUtil.getUriForFile(context, imageFile);
                    if (imageUri != null) {
                        // 分享图片到群聊
                        douYinIntentShareUtil.shareToGroupChat((Activity) context, textContent, imageUri, "image");
                    } else {
                        // URI为空，退回到纯文本分享
                        douYinIntentShareUtil.shareToGroupChat((Activity) context, textContent, null, null);
                    }
                } else {
                    // 文件不存在，退回到纯文本分享
                    douYinIntentShareUtil.shareToGroupChat((Activity) context, textContent, null, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
                // 如果图片准备失败，至少分享文本
                douYinIntentShareUtil.shareToGroupChat((Activity) context, textContent, null, null);
            }
        } else if (type != null && type.equals("4") && imagePath != null) {
            // 准备视频URI
            try {
                File videoFile = new File(imagePath);
                if (videoFile.exists()) {
                    Uri videoUri = FileProviderUtil.getUriForFile(context, videoFile);
                    if (videoUri != null) {
                        // 分享视频到群聊
                        douYinIntentShareUtil.shareToGroupChat((Activity) context, textContent, videoUri, "video");
                    } else {
                        // URI为空，退回到纯文本分享
                        douYinIntentShareUtil.shareToGroupChat((Activity) context, textContent, null, null);
                    }
                } else {
                    // 文件不存在，退回到纯文本分享
                    douYinIntentShareUtil.shareToGroupChat((Activity) context, textContent, null, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
                // 如果视频准备失败，至少分享文本
                douYinIntentShareUtil.shareToGroupChat((Activity) context, textContent, null, null);
            }
        } else if (type != null && type.equals("2")) {
            // 处理Base64图片分享
            String description = bean.getDescription();
            if (!TextUtils.isEmpty(description)) {
                Bitmap bitmap = Base64ImageUtil.base64ToBitmap(description);
                if (bitmap != null) {
                    try {
                        // 创建文件保存路径
                        File imageFolder = new File(((Activity) context).getExternalCacheDir(), "douyin_share");
                        if (!imageFolder.exists()) {
                            imageFolder.mkdirs();
                        }

                        // 生成唯一的文件名
                        String fileName = "douyin_base64_" + System.currentTimeMillis() + ".jpg";
                        File imageFile = new File(imageFolder, fileName);

                        // 保存图片到文件
                        FileOutputStream fos = new FileOutputStream(imageFile);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
                        fos.flush();
                        fos.close();

                        // 回收Bitmap释放内存
                        bitmap.recycle();

                        Uri imageUri = FileProviderUtil.getUriForFile(context, imageFile);
                        if (imageUri != null) {
                            // 分享图片到群聊
                            douYinIntentShareUtil.shareToGroupChat((Activity) context, textContent, imageUri, "image");
                            return;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            // 如果处理失败，退回到纯文本分享
            douYinIntentShareUtil.shareToGroupChat((Activity) context, textContent, null, null);
        } else {
            // 只分享文本
            douYinIntentShareUtil.shareToGroupChat((Activity) context, textContent, null, null);
        }
    }

    /**
     * 分享纯文本到抖音
     *
     * @param context 上下文
     * @param text    要分享的文本内容
     */
    public static void shareTextToDouYin(Context context, String text) {
        try {
            // 初始化抖音分享工具
            DouYinIntentShareUtil douYinIntentShareUtil = DouYinIntentShareUtil.getInstance(context);

            // 检查抖音是否已安装 - HarmonyOS兼容性修改：移除强制检查
            // if (!douYinIntentShareUtil.isDouyinInstalled()) {
            //    Toast.makeText(context, "抖音未安装，无法分享", Toast.LENGTH_SHORT).show();
            //    return;
            // }

            // 设置分享回调
            douYinIntentShareUtil.setShareCallback(new DouYinIntentShareUtil.DouYinShareCallback() {
                @Override
                public void onSuccess() {
                    ((Activity) context).runOnUiThread(() ->
                            Toast.makeText(context, "抖音分享成功", Toast.LENGTH_SHORT).show()
                    );
                }

                @Override
                public void onError(int errorCode, String errorMsg) {
                    ((Activity) context).runOnUiThread(() ->
                            Toast.makeText(context, "抖音分享失败: " + errorMsg, Toast.LENGTH_SHORT).show()
                    );
                }

                @Override
                public void onCancel() {
                    ((Activity) context).runOnUiThread(() ->
                            Toast.makeText(context, "抖音分享被取消", Toast.LENGTH_SHORT).show()
                    );
                }
            });

            // 显示分享提示
            Toast.makeText(context, "正在分享到抖音", Toast.LENGTH_SHORT).show();            // 修改：直接调用Intent分享方法，而不是复制粘贴方式
            shareTextDirectToDouYin((Activity) context, text);

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context, "分享到抖音出错: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 分享网页到抖音私信
     *
     * @param activity 当前活动
     * @param title 网页标题
     * @param description 网页描述
     * @param webUrl 网页URL
     * @param previewImageBase64 网页预览图(Base64编码，可为null)
     */
    public static void shareWebPageToDouYinPrivate(Activity activity, String title, String description,
                                           String webUrl, String previewImageBase64) {
        try {
            // 初始化抖音分享工具
            DouYinIntentShareUtil douYinIntentShareUtil = DouYinIntentShareUtil.getInstance(activity);

            // 检查抖音是否已安装 - HarmonyOS兼容性修改：移除强制检查
            // if (!douYinIntentShareUtil.isDouyinInstalled()) {
            //    Toast.makeText(activity, "抖音未安装，无法分享", Toast.LENGTH_SHORT).show();
            //    return;
            // }

            // 设置分享回调
            douYinIntentShareUtil.setShareCallback(new DouYinIntentShareUtil.DouYinShareCallback() {
                @Override
                public void onSuccess() {
                    activity.runOnUiThread(() ->
                        Toast.makeText(activity, "网页分享成功", Toast.LENGTH_SHORT).show()
                    );
                }

                @Override
                public void onError(int errorCode, String errorMsg) {
                    activity.runOnUiThread(() ->
                        Toast.makeText(activity, "网页分享失败: " + errorMsg, Toast.LENGTH_SHORT).show()
                    );
                }

                @Override
                public void onCancel() {
                    activity.runOnUiThread(() ->
                        Toast.makeText(activity, "网页分享被取消", Toast.LENGTH_SHORT).show()
                    );
                }
            });

            // 构建要分享的文本内容
            StringBuilder content = new StringBuilder();
            if (!TextUtils.isEmpty(title)) {
                content.append(title).append("\n\n");
            }
            if (!TextUtils.isEmpty(description)) {
                content.append(description).append("\n\n");
            }
            if (!TextUtils.isEmpty(webUrl)) {
                content.append(webUrl);
            }            String textContent = content.toString();
            try {
                Context mContext = activity.getApplicationContext();
                // 设置缩略图 - 使用应用的启动图标 logo6 而不是 ic_launcher
                Bitmap thumbBmp = BitmapFactory.decodeResource(mContext.getResources(),
                        mContext.getResources().getIdentifier("logo6", "drawable", mContext.getPackageName()));
                Uri imagePath = Base64ImageUtil.saveBitmapToFile(activity, thumbBmp, null);
                
                // 方式1：尝试分享图文到私信（图片+文本）
                if (imagePath != null) {
                    shareImageWithTextDirectToDouYin(activity, textContent, imagePath);
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            // 方式2：如果图片处理失败，使用纯文本直接分享
            shareTextDirectToDouYin(activity, textContent);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(activity, "网页分享出错: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 分享网页到抖音群聊
     *
     * @param activity 当前活动
     * @param title 网页标题
     * @param description 网页描述
     * @param webUrl 网页URL
     * @param previewImageBase64 网页预览图(Base64编码，可为null)
     */
    public static void shareWebPageToDouYinGroup(Activity activity, String title, String description,
                                         String webUrl, String previewImageBase64) {
        try {
            // 初始化抖音分享工具
            DouYinIntentShareUtil douYinIntentShareUtil = DouYinIntentShareUtil.getInstance(activity);

            // 检查抖音是否已安装 - HarmonyOS兼容性修改：移除强制检查
            // if (!douYinIntentShareUtil.isDouyinInstalled()) {
            //    Toast.makeText(activity, "抖音未安装，无法分享", Toast.LENGTH_SHORT).show();
            //    return;
            // }

            // 设置分享回调
            douYinIntentShareUtil.setShareCallback(new DouYinIntentShareUtil.DouYinShareCallback() {
                @Override
                public void onSuccess() {
                    activity.runOnUiThread(() ->
                        Toast.makeText(activity, "网页分享成功", Toast.LENGTH_SHORT).show()
                    );
                }

                @Override
                public void onError(int errorCode, String errorMsg) {
                    activity.runOnUiThread(() ->
                        Toast.makeText(activity, "网页分享失败: " + errorMsg, Toast.LENGTH_SHORT).show()
                    );
                }

                @Override
                public void onCancel() {
                    activity.runOnUiThread(() ->
                        Toast.makeText(activity, "网页分享被取消", Toast.LENGTH_SHORT).show()
                    );
                }
            });

            // 构建要分享的文本内容
            StringBuilder content = new StringBuilder();
            if (!TextUtils.isEmpty(title)) {
                content.append(title).append("\n\n");
            }
            if (!TextUtils.isEmpty(description)) {
                content.append(description).append("\n\n");
            }
            if (!TextUtils.isEmpty(webUrl)) {
                content.append(webUrl);
            }

            String textContent = content.toString();

            // 如果提供了预览图，先处理图片再分享
            if (!TextUtils.isEmpty(previewImageBase64)) {
                Bitmap bitmap = Base64ImageUtil.base64ToBitmap(previewImageBase64);
                if (bitmap != null) {
                    try {
                        // 创建文件保存路径
                        File imageFolder = new File(activity.getExternalCacheDir(), "douyin_web_share");
                        if (!imageFolder.exists()) {
                            imageFolder.mkdirs();
                        }

                        // 生成唯一的文件名
                        String fileName = "douyin_webpage_" + System.currentTimeMillis() + ".jpg";
                        File imageFile = new File(imageFolder, fileName);

                        // 保存图片到文件
                        FileOutputStream fos = new FileOutputStream(imageFile);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
                        fos.flush();
                        fos.close();

                        // 回收Bitmap释放内存
                        bitmap.recycle();

                        // 获取图片URI
                        Uri imageUri = FileProviderUtil.getUriForFile(activity, imageFile);
                        if (imageUri != null) {
                            // 分享图文到群聊
                            douYinIntentShareUtil.shareToGroupChat(activity, textContent, imageUri, "image");
                            return;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            // 如果没有预览图或处理失败，退回到纯文本分享
            douYinIntentShareUtil.shareToGroupChat(activity, textContent, null, null);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(activity, "网页分享出错: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 从JSON数据分享网页到抖音(自动选择私信或群聊)
     *
     * @param context 上下文
     * @param jsonData 分享数据JSON字符串
     */
    public static void shareWebPageToDouYin(Context context, String jsonData) {
        try {
            // 解析JSON数据
            Gson gson = new Gson();
            sharetypeBean bean = gson.fromJson(jsonData, sharetypeBean.class);

            // 获取分享参数
            String title = bean.getTitle();
            String description = bean.getDescription();
            String webUrl = bean.getWebpageUrl();
            String imageBase64 = null;

            // 如果描述字段包含Base64图片，则提取出来作为预览图
            if (!TextUtils.isEmpty(description) &&
                (description.startsWith("data:image") ||
                description.startsWith("/9j/") ||
                description.startsWith("iVBOR"))) {
                imageBase64 = description;
                // 清空描述以避免重复使用
                description = null;
            }

            // 获取分享目标类型：私信(默认)或群聊
            String shareTarget = "private_message"; // 默认私信

            // 根据分享目标执行不同的分享操作
            if ("group_chat".equals(shareTarget)) {
                // 分享到群聊
                shareWebPageToDouYinGroup((Activity) context, title, description, webUrl, imageBase64);
            } else {
                // 分享到私信(默认)
                shareWebPageToDouYinPrivate((Activity) context, title, description, webUrl, imageBase64);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context, "抖音网页分享出错: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 截取当前屏幕并分享到抖音私信
     *
     * @param activity 当前活动
     */    /**
     * 分享截图到抖音私信（不弹出选择器）
     * @param activity 活动上下文
     */
    public static void shareScreenshotToDouYin(Activity activity) {
        try {
            // 获取当前窗口的根视图
            View rootView = activity.getWindow().getDecorView().getRootView();
            // 创建一个与窗口大小相同的位图
            Bitmap bitmap = Bitmap.createBitmap(rootView.getWidth(), rootView.getHeight(), Bitmap.Config.ARGB_8888);
            // 创建画布并将位图绑定到画布上
            Canvas canvas = new Canvas(bitmap);
            // 将根视图绘制到画布上
            rootView.draw(canvas);

            // 显示分享提示
            Toast.makeText(activity, "正在分享截图到抖音私信", Toast.LENGTH_SHORT).show();

            // 直接分享到私信，不弹出选择器
            shareImageDirectToPrivateMessage(activity, bitmap);

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(activity, "分享截屏到抖音出错: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 直接分享图片到抖音私信，不弹出选择器
     * @param activity 活动上下文
     * @param bitmap 要分享的图片
     */
    public static void shareImageDirectToPrivateMessage(Activity activity, Bitmap bitmap) {
        try {
            // 检查抖音是否已安装 - HarmonyOS兼容性修改：移除强制检查
            // if (!isAppInstalled(activity, "com.ss.android.ugc.aweme")) {
            //    Toast.makeText(activity, "抖音未安装，无法分享", Toast.LENGTH_SHORT).show();
            //    return;
            // }

            // 保存bitmap到文件
            File cacheDir = activity.getExternalCacheDir();
            if (cacheDir == null) {
                cacheDir = activity.getCacheDir();
            }

            File imageFile = new File(cacheDir, "douyin_private_share_" + System.currentTimeMillis() + ".jpg");
            FileOutputStream fos = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            fos.flush();
            fos.close();

            // 获取图片URI
            Uri imageUri = FileProviderUtil.getUriForFile(activity, imageFile);
            if (imageUri != null) {
                // 创建专门用于私信分享的Intent
                shareImageToPrivateMessageIntent(activity, imageUri);
            } else {
                Toast.makeText(activity, "获取图片文件失败", Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(activity, "分享出错: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 使用Intent直接分享图片到抖音私信
     * @param activity 活动上下文
     * @param imageUri 图片Uri
     */
    /**
     * 使用剪贴板 + 弹窗引导的方式进行图片分享
     * 不再使用系统分享Intent，因为在鸿蒙/卓易通上兼容性问题较多
     */
    private static void shareImageToPrivateMessageIntent(Activity activity, Uri imageUri) {
        try {
            // 1. 复制图片到剪贴板
            boolean success = copyImageToClipboard(activity, imageUri);
            
            if (success) {
                // 2. 显示引导弹窗
                showDouYinGuideDialog(activity);
            } else {
                 Toast.makeText(activity, "复制图片失败，请检查文件权限", Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(activity, "启动分享失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 复制图片Uri到剪贴板
     * 为了确保抖音能读取（粘贴）图片，尝试将图片保存到系统公共图库
     */
    private static boolean copyImageToClipboard(Context context, Uri uri) {
        Uri contentUri = uri; // 默认为传入的URI

        // 尝试1：将图片插入系统相册获取公共Content URI (解决FileProvider权限无法跨应用粘贴的问题)
        try {
            android.content.ContentValues values = new android.content.ContentValues();
            values.put(android.provider.MediaStore.Images.Media.DISPLAY_NAME, "share_douyin_" + System.currentTimeMillis());
            values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            
            // 插入Media
            Uri publicUri = context.getContentResolver().insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            
            if (publicUri != null) {
                // 复制文件内容到新URI
                try (java.io.OutputStream os = context.getContentResolver().openOutputStream(publicUri);
                     java.io.InputStream is = context.getContentResolver().openInputStream(uri)) {
                    if (os != null && is != null) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = is.read(buffer)) != -1) {
                            os.write(buffer, 0, bytesRead);
                        }
                        // 成功复制内容，使用新的公共URI
                        contentUri = publicUri;
                    }
                }
            }
        } catch (Exception e) {
            Log.e("DouYinShare", "保存图片到相册失败: " + e.getMessage());
            // 失败时不阻断，继续尝试直接使用原始URI
        }

        // 尝试2：设置剪贴板
        try {
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            android.content.ClipData clip = android.content.ClipData.newUri(context.getContentResolver(), "Image", contentUri);
            clipboard.setPrimaryClip(clip);
            return true;
        } catch (Exception e) {
            Log.e("DouYinShare", "复制图片到剪贴板失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 显示抖音分享引导弹窗
     */
    private static void showDouYinGuideDialog(final Activity activity) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(activity);
        builder.setTitle("抖音分享准备完成");

        // 构建自定义视图
        android.widget.LinearLayout layout = new android.widget.LinearLayout(activity);
        layout.setOrientation(android.widget.LinearLayout.VERTICAL);
        int padding = dp2px(activity, 20);
        layout.setPadding(padding, padding, padding, padding);
        layout.setGravity(android.view.Gravity.CENTER_HORIZONTAL);

        // 状态提示
        android.widget.TextView statusTv = new android.widget.TextView(activity);
        statusTv.setText("✅ 图片已复制到剪贴板，并保存到相册");
        statusTv.setTextColor(android.graphics.Color.parseColor("#4CAF50"));
        statusTv.setTextSize(16);
        statusTv.setTypeface(null, android.graphics.Typeface.BOLD);
        statusTv.setGravity(android.view.Gravity.CENTER);
        layout.addView(statusTv);

        // 间隔
        android.view.View space = new android.view.View(activity);
        layout.addView(space, new android.widget.LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, dp2px(activity, 15)));

        // 步骤文本
        android.widget.TextView stepTv = new android.widget.TextView(activity);
        stepTv.setText("分享到好友或群聊步骤：\n\n" +
                "1. 点击下方按钮打开抖音\n" +
                "2. 找到好友或群聊进入聊天界面\n" +
                "3. 点击输入框旁的「+」号 ->「相册」\n" + 
                "4. 选择第一张图片发送即可\n" + 
                "(也可以尝试在输入框长按粘贴)");
        stepTv.setTextColor(android.graphics.Color.DKGRAY);
        stepTv.setTextSize(14);
        // 行间距
        stepTv.setLineSpacing(dp2px(activity, 4), 1.0f);
        layout.addView(stepTv);

        builder.setView(layout);
        
        // 按钮
        builder.setPositiveButton("立即打开抖音", new android.content.DialogInterface.OnClickListener() {
            @Override
            public void onClick(android.content.DialogInterface dialog, int which) {
                tryLaunchDouyinMain(activity);
            }
        });
        
        builder.setNegativeButton("稍后分享", null);
        
        builder.show();
    }

    /**
     * 启动抖音主界面
     */
    private static void tryLaunchDouyinMain(Activity activity) {
        try {
            Intent launchIntent = null;
            
            // 方法1: 尝试获取官方启动Intent
            try {
                launchIntent = activity.getPackageManager().getLaunchIntentForPackage("com.ss.android.ugc.aweme");
            } catch (Exception e) {
                // 忽略包可见性异常
            }

            // 方法2: 如果获取不到（HarmonyOS/Android 11+ 可见性限制），尝试构造Intent盲拉
            if (launchIntent == null) {
                launchIntent = new Intent(Intent.ACTION_MAIN);
                launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
                launchIntent.setPackage("com.ss.android.ugc.aweme");
            }
            
            launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            activity.startActivity(launchIntent);
            
        } catch (Exception e) {
            // 方法3: 最后的救命稻草 - URL Scheme
            try {
                Uri uri = Uri.parse("snssdk1128://");
                Intent schemeIntent = new Intent(Intent.ACTION_VIEW, uri);
                schemeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivity(schemeIntent);
            } catch (Exception ex) {
                Toast.makeText(activity, "启动抖音失败，请手动打开", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private static int dp2px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    /**
     * 检查应用是否已安装
     * @param context 上下文
     * @param packageName 包名
     * @return 是否已安装
     */
    private static boolean isAppInstalled(Context context, String packageName) {
        try {
            context.getPackageManager().getPackageInfo(packageName, 0);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 直接分享网页到抖音（使用Intent方式，不是复制粘贴）
     *
     * @param activity 当前活动
     * @param title 网页标题
     * @param description 网页描述
     * @param webUrl 网页URL
     */
    public static void shareWebPageDirectToDouYin(Activity activity, String title, String description, String webUrl) {
        try {
            // 检查抖音是否已安装 - HarmonyOS兼容性修改：移除强制检查
            // if (!isAppInstalled(activity, "com.ss.android.ugc.aweme")) {
            //    Toast.makeText(activity, "抖音未安装，无法分享", Toast.LENGTH_SHORT).show();
            //    return;
            // }

            // 构建要分享的文本内容
            StringBuilder content = new StringBuilder();
            if (!TextUtils.isEmpty(title)) {
                content.append(title).append("\n\n");
            }
            if (!TextUtils.isEmpty(description)) {
                content.append(description).append("\n\n");
            }            if (!TextUtils.isEmpty(webUrl)) {
                content.append(webUrl);
            }

            String textContent = content.toString();

            // 方法1：先尝试直接启动抖音App
            if (tryLaunchDouyinDirectly(activity, textContent)) {
                return;
            }

            // 方法2：尝试使用多种MIME类型的分享Intent
            if (tryMultipleShareIntents(activity, textContent)) {
                return;
            }

            // 方法3：最后的备选方案 - 复制到剪贴板并引导用户
            fallbackCopyAndLaunch(activity, textContent);

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(activity, "网页分享出错: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }    /**
     * 直接分享图片和文本到抖音（使用Intent方式）
     */
    private static void shareImageWithTextDirectToDouYin(Activity activity, String text, Uri imageUri) {
        try {
            // 图片分享通常有更好的支持，先尝试图片分享
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("image/*");
            shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
            shareIntent.putExtra(Intent.EXTRA_TEXT, text);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            
            // 检查抖音是否可以处理图片分享
            if (isIntentSafe(activity, shareIntent, "com.ss.android.ugc.aweme")) {
                shareIntent.setPackage("com.ss.android.ugc.aweme");
                // 添加额外参数尝试指定分享类型为私信
                shareIntent.putExtra("share_type", "private_message");
                shareIntent.putExtra("type", "private");
                
                activity.startActivity(shareIntent);
                Toast.makeText(activity, "正在打开抖音图文分享...", Toast.LENGTH_SHORT).show();
                return;
            }

            // 如果直接分享失败，使用系统选择器
            Intent chooser = Intent.createChooser(shareIntent.setPackage(null), "分享图文");
            activity.startActivity(chooser);
            
            new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(() -> {
                Toast.makeText(activity, "请选择抖音进行分享", Toast.LENGTH_LONG).show();
            }, 1000);
            
        } catch (Exception e) {
            e.printStackTrace();
            // 如果图片分享失败，降级为纯文本分享
            Toast.makeText(activity, "图片分享失败，尝试文本分享", Toast.LENGTH_SHORT).show();
            shareTextDirectToDouYin(activity, text);
        }
    }/**
     * 直接分享纯文本到抖音（使用Intent方式）
     */
    private static void shareTextDirectToDouYin(Activity activity, String text) {
        try {
            // 方法1：先尝试直接启动抖音App
            if (tryLaunchDouyinDirectly(activity, text)) {
                return;
            }

            // 方法2：尝试使用多种MIME类型的分享Intent
            if (tryMultipleShareIntents(activity, text)) {
                return;
            }

            // 方法3：最后的备选方案 - 复制到剪贴板并引导用户
            fallbackCopyAndLaunch(activity, text);
            
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(activity, "文本分享失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 方法1：尝试直接启动抖音App并复制内容到剪贴板
     */
    private static boolean tryLaunchDouyinDirectly(Activity activity, String content) {
        try {
            // 复制内容到剪贴板
            copyTextToClipboard(activity, content);
            
            // 尝试直接启动抖音主页
            Intent launchIntent = activity.getPackageManager().getLaunchIntentForPackage("com.ss.android.ugc.aweme");
            if (launchIntent != null) {
                launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivity(launchIntent);
                
                // 提示用户操作
                Toast.makeText(activity, "内容已复制到剪贴板，请在抖音中点击\"消息\"→选择联系人→粘贴发送", Toast.LENGTH_LONG).show();
                return true;
            }
        } catch (Exception e) {
            Log.e("DouYinShare", "直接启动抖音失败: " + e.getMessage());
        }
        return false;
    }

    /**
     * 方法2：尝试使用多种MIME类型创建分享Intent
     */
    private static boolean tryMultipleShareIntents(Activity activity, String content) {
        // 尝试的MIME类型列表
        String[] mimeTypes = {
            "text/plain",
            "*/*",
            "application/octet-stream"
        };
        
        for (String mimeType : mimeTypes) {
            try {
                Intent shareIntent = new Intent(Intent.ACTION_SEND);
                shareIntent.setType(mimeType);
                shareIntent.putExtra(Intent.EXTRA_TEXT, content);
                shareIntent.putExtra(Intent.EXTRA_SUBJECT, "网页分享");
                
                // 检查是否有抖音可以处理这种Intent
                if (isIntentSafe(activity, shareIntent, "com.ss.android.ugc.aweme")) {
                    shareIntent.setPackage("com.ss.android.ugc.aweme");
                    activity.startActivity(shareIntent);
                    Toast.makeText(activity, "正在打开抖音分享...", Toast.LENGTH_SHORT).show();
                    return true;
                }
            } catch (Exception e) {
                Log.e("DouYinShare", "MIME类型 " + mimeType + " 分享失败: " + e.getMessage());
            }
        }
        
        // 如果直接分享失败，尝试使用系统分享选择器
        try {
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, content);
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, "网页分享");
            
            Intent chooser = Intent.createChooser(shareIntent, "选择分享方式");
            activity.startActivity(chooser);
            
            // 提示用户如果看不到抖音选项的解决方案
            new android.os.Handler(android.os.Looper.getMainLooper()).postDelayed(() -> {
                Toast.makeText(activity, "如果没有抖音选项，请选择\"复制\"然后手动打开抖音粘贴", Toast.LENGTH_LONG).show();
            }, 1000);
            return true;
            
        } catch (Exception e) {
            Log.e("DouYinShare", "系统分享选择器失败: " + e.getMessage());
        }
        
        return false;
    }

    /**
     * 方法3：备选方案 - 复制到剪贴板并引导用户手动操作
     */
    private static void fallbackCopyAndLaunch(Activity activity, String content) {
        try {
            // 复制到剪贴板
            copyTextToClipboard(activity, content);
            
            // 尝试启动抖音
            try {
                Intent launchIntent = activity.getPackageManager().getLaunchIntentForPackage("com.ss.android.ugc.aweme");
                if (launchIntent != null) {
                    launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    activity.startActivity(launchIntent);
                }
            } catch (Exception e) {
                Log.e("DouYinShare", "启动抖音失败: " + e.getMessage());
            }
            
            // 详细的操作指导
            Toast.makeText(activity, "内容已复制！请在抖音中：消息→选择好友→长按输入框→粘贴→发送", Toast.LENGTH_LONG).show();
            
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(activity, "分享失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 检查指定应用是否可以处理某个Intent
     */
    private static boolean isIntentSafe(Activity activity, Intent intent, String packageName) {
        try {
            intent.setPackage(packageName);
            return activity.getPackageManager().resolveActivity(intent, 0) != null;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 复制文本到剪贴板（兼容不同Android版本）
     */
    private static void copyTextToClipboard(Activity activity, String text) {
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
                android.content.ClipboardManager clipboard = (android.content.ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
                android.content.ClipData clip = android.content.ClipData.newPlainText("网页分享", text);
                clipboard.setPrimaryClip(clip);
            } else {
                @SuppressWarnings("deprecation")
                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setText(text);
            }
        } catch (Exception e) {
            Log.e("DouYinShare", "复制到剪贴板失败: " + e.getMessage());
        }
    }
}
