package com.tagmae.tsgame_erwang;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tsgame.tsgame_niuniu.simcpux.bean.sharetypeBean;
import com.tsgame.tsgame_niuniu.util.DouYinIntentShareUtil;
import com.tsgame.tsgame_niuniu.util.QQIntentShareUtil;

import org.json.JSONObject;

/**
 * 处理QQ分享和抖音分享的JavaScript接口
 */
public class ShareJavascriptInterface {

    private Context mContext;
    private boolean isShareInProgress = false;

    public ShareJavascriptInterface(Context context) {
        this.mContext = context;
    }

    /**
     * QQ分享
     * @param data JSON格式数据
     *            {
     *                "type": "1",           // 1-普通分享, 2-截图分享, 3-图片分享
     *                "webpageUrl": "链接",  // 网页链接或图片路径
     *                "title": "标题",       // 分享标题
     *                "description": "描述", // 分享描述
     *                "sharefriend": "1"     // 1-QQ好友, 2-QQ空间
     *            }
     */
    @JavascriptInterface
    public void shareToQQ(String data) {
        try {
            if (isShareInProgress) {
                return;
            }

            isShareInProgress = true;

            // 使用主线程执行UI操作
            ((Activity)mContext).runOnUiThread(() -> {
                try {
                    Gson gson = new Gson();
                    sharetypeBean bean = gson.fromJson(data, sharetypeBean.class);

                    if (bean.getType() == null) {
                        bean.setType("");
                    }
                    if (bean.getSharefriend() == null) {
                        bean.setSharefriend("");
                    }

                    // 图片分享
                    if ("3".equals(bean.getType())) {
                        shareQQImage(bean.getSharefriend(), bean.getWebpageUrl());
                    } else {
                        // 普通分享
                        shareQQWebpage(bean.getSharefriend(), bean.getWebpageUrl(), bean.getTitle(), bean.getDescription());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(mContext, "QQ分享数据解析错误", Toast.LENGTH_SHORT).show();
                }

                // 3秒后重置分享状态
                new android.os.Handler().postDelayed(() -> {
                    isShareInProgress = false;
                }, 3000);
            });
        } catch (Exception e) {
            e.printStackTrace();
            isShareInProgress = false;
        }
    }

    /**
     * 抖音分享
     * @param data JSON格式数据
     *            {
     *                "type": "1",           // 1-图片分享, 2-视频分享
     *                "filePath": "路径",    // 图片或视频文件路径
     *                "hashTag": "话题"      // 话题标签(可选)
     *            }
     */
    @JavascriptInterface
    public void shareToDouYin(String data) {
        try {
            if (isShareInProgress) {
                return;
            }

            isShareInProgress = true;

            // 使用主线程执行UI操作
            ((Activity)mContext).runOnUiThread(() -> {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    String type = jsonObject.optString("type", "1");
                    String filePath = jsonObject.optString("filePath", "");
                    String hashTag = jsonObject.optString("hashTag", "");

                    // 分享到抖音
                    boolean isImage = "1".equals(type);
                    shareToDouYinInternal(filePath, hashTag, isImage);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(mContext, "抖音分享数据解析错误", Toast.LENGTH_SHORT).show();
                }

                // 3秒后重置分享状态
                new android.os.Handler().postDelayed(() -> {
                    isShareInProgress = false;
                }, 3000);
            });
        } catch (Exception e) {
            e.printStackTrace();
            isShareInProgress = false;
        }
    }

    // QQ分享网页链接
    private void shareQQWebpage(String shareType, String webpageUrl, String title, String description) {
        if (TextUtils.isEmpty(title)) {
            title = "分享";
        }
        if (TextUtils.isEmpty(description)) {
            description = "来自应用的分享";
        }

        QQIntentShareUtil qqShareUtil = QQIntentShareUtil.getInstance(mContext);
        if (!qqShareUtil.isQQInstalled()) {
            Toast.makeText(mContext, "请先安装QQ客户端", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            // 创建临时文件用于分享
            // 注：由于QQShareUtil仅支持图片分享，我们将网页信息添加到分享标题中
            // 实际项目中应考虑创建一个包含网页预览的图片
            String sharePath = ((Activity)mContext).getExternalFilesDir(null) + "/share_tmp.png";

            // 分享标题包含描述和链接
            String shareTitle = title;
            if (!TextUtils.isEmpty(description)) {
                shareTitle += "\n" + description;
            }
            if (!TextUtils.isEmpty(webpageUrl)) {
                shareTitle += "\n" + webpageUrl;
            }

            // 分享给QQ
            qqShareUtil.shareImageToQQ((Activity)mContext, sharePath);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(mContext, "分享失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    // QQ分享图片
    private void shareQQImage(String shareType, String imagePath) {
        QQIntentShareUtil qqShareUtil = QQIntentShareUtil.getInstance(mContext);
        if (!qqShareUtil.isQQInstalled()) {
            Toast.makeText(mContext, "请先安装QQ客户端", Toast.LENGTH_SHORT).show();
            return;
        }

        // 不管是QQ好友还是QQ空间，都使用同一个分享方法
        // QQShareUtil类中只有shareImageToQQ方法，没有专门的QQ空间分享方法
        // 实际上用户可以在QQ分享界面选择分享到QQ空间或好友
        qqShareUtil.shareImageToQQ((Activity)mContext, imagePath);
    }

    // 分享到抖音
    private void shareToDouYinInternal(String filePath, String hashTag, boolean isImage) {
        DouYinIntentShareUtil douYinIntentShareUtil = DouYinIntentShareUtil.getInstance(mContext);
        if (!douYinIntentShareUtil.isDouyinInstalled()) {
            Toast.makeText(mContext, "请先安装抖音客户端", Toast.LENGTH_SHORT).show();
            return;
        }

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

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

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

        if (isImage) {
            douYinIntentShareUtil.shareImageToDouyin((Activity)mContext, filePath);
        } else {
            douYinIntentShareUtil.shareVideoToDouyin((Activity)mContext, filePath);
        }
    }
}
