package com.jx.jyhd.simcpux.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.Toast;

import com.jx.jyhd.simcpux.Constants;
import com.jx.jyhd.simcpux.Util;
import com.jx.jyhd.wxapi.WXEntryActivity;
import com.tagmae.tsgame_erwang.utils.Base64ImageUtil;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.File;

/**
 * 微信分享工具类
 */
public class WeChatShareUtil {

    private static final int THUMB_SIZE = 150;
    private static WeChatShareUtil instance;
    private final Context mContext;
    private final IWXAPI mWxApi;
    private WeChatShareCallback mCallback;

    private WeChatShareUtil(Context context) {
        this.mContext = context.getApplicationContext();
        // 初始化微信API
        mWxApi = WXAPIFactory.createWXAPI(mContext, Constants.APP_ID, true);
        mWxApi.registerApp(Constants.APP_ID);
    }

    /**
     * 获取实例
     * @param context 上下文
     * @return WeChatShareUtil实例
     */
    public static WeChatShareUtil getInstance(Context context) {
        if (instance == null && context != null) {
            instance = new WeChatShareUtil(context);
        }
        return instance;
    }

    /**
     * 检查微信是否已安装
     * @return 是否安装
     */
    public boolean isWeChatInstalled() {
        try {
            return mWxApi.isWXAppInstalled();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

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

    /**
     * 获取分享回调
     * @return 分享回调
     */
    public WeChatShareCallback getShareCallback() {
        return mCallback;
    }

    /**
     * 分享网页到微信
     * @param activity 活动
     * @param webpageUrl 网页链接
     * @param title 标题
     * @param description 描述
     * @param scene 分享场景(0:好友, 1:朋友圈)
     */
    public void shareWebPage(Activity activity, String webpageUrl, String title, String description, int scene) {
        if (!isWeChatInstalled()) {
            Toast.makeText(activity, "请先安装微信客户端", Toast.LENGTH_SHORT).show();
            if (mCallback != null) {
                mCallback.onError(-1, "未安装微信客户端");
            }
            return;
        }

        try {
            // 设置分享回调处理
            // 创建Handler来接收微信分享结果
            final Handler shareHandler = new Handler(Looper.getMainLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    // 处理微信分享回调
                    if (mCallback != null) {
                        if (msg.what == 0) { // 成功
                            mCallback.onSuccess();
                        } else if (msg.what == -2) { // 取消
                            mCallback.onCancel();
                        } else { // 错误
                            mCallback.onError(msg.what, "微信分享失败，错误码：" + msg.what);
                        }
                    }
                }
            };

            // 设置分享回调
            WXEntryActivity.setshareHandler(shareHandler);

            // 创建网页消息对象
            WXWebpageObject webpage = new WXWebpageObject();
            String timestampUrl = webpageUrl + (webpageUrl.contains("?") ? "&" : "?") + "t=" + System.currentTimeMillis();
            webpage.webpageUrl = timestampUrl;

            // 创建多媒体消息
            WXMediaMessage msg = new WXMediaMessage(webpage);
            msg.title = title;
            msg.description = description;

            // 设置缩略图 - 使用应用的启动图标 logo6 而不是 ic_launcher
            Bitmap thumbBmp = BitmapFactory.decodeResource(mContext.getResources(),
                    com.jx.jyhd.R.drawable.logo6);

            // 如果找不到logo6，则退回到使用ic_launcher
            if (thumbBmp == null) {
                thumbBmp = BitmapFactory.decodeResource(mContext.getResources(),
                    com.jx.jyhd.R.mipmap.ic_launcher);
            }

            if (thumbBmp != null) {
                Bitmap thumbBitmap = Bitmap.createScaledBitmap(thumbBmp, THUMB_SIZE, THUMB_SIZE, true);
                thumbBmp.recycle();
                msg.thumbData = Util.bmpToByteArray(thumbBitmap, true);
            }

            // 构建发送请求
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction("webpage");
            req.message = msg;
            req.scene = scene == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;

            // 发送请求
            boolean result = mWxApi.sendReq(req);

            if (!result) {
                Toast.makeText(activity, "微信分享请求发送失败", Toast.LENGTH_SHORT).show();
                if (mCallback != null) {
                    mCallback.onError(-2, "微信分享请求发送失败");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(activity, "微信分享失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            if (mCallback != null) {
                mCallback.onError(-3, "微信分享失败: " + e.getMessage());
            }
        }
    }

    /**
     * 分享图片到微信
     * @param activity 活动
     * @param imagePath 图片路径
     * @param scene 分享场景(0:好友, 1:朋友圈)
     */
    public void shareImage(Activity activity, String imagePath, int scene) {
        if (!isWeChatInstalled()) {
            Toast.makeText(activity, "请先安装微信客户端", Toast.LENGTH_SHORT).show();
            if (mCallback != null) {
                mCallback.onError(-1, "未安装微信客户端");
            }
            return;
        }

        // 使用新的图片处理工具类检查图片是否存在，不存在时可以尝试使用其他备用方案
        Uri imageFile = Base64ImageUtil.base64ToImageFile(activity,imagePath,null);
        //Uri imageFile = Uri.parse(imagePath);

        if (imageFile == null) {
            //Toast.makeText(activity, "分享图片不存在，尝试创建临时图片", Toast.LENGTH_SHORT).show();

            // 如果是Bitmap对象，可以使用ImageProcessUtils保存
            if (imagePath.startsWith("data:image/") || imagePath.startsWith("base64,")) {
                // 对于Base64编码的图片，使用ImageProcessUtils保存
                com.tagmae.tsgame_erwang.utils.ImageProcessUtils.saveBase64ImageToCache(
                        activity,
                        imagePath,
                        new com.tagmae.tsgame_erwang.utils.ImageProcessUtils.ImageSaveCallback() {
                            @Override
                            public void onSuccess(String savedImagePath) {
                                // 保存成功，使用新路径进行分享
                                shareImageInternal(activity, savedImagePath, scene);
                            }

                            @Override
                            public void onError(String errorMsg) {
                                Toast.makeText(activity, errorMsg, Toast.LENGTH_SHORT).show();
                                if (mCallback != null) {
                                    mCallback.onError(-2, errorMsg);
                                }
                            }
                        }
                );
                return;
            } else {
                // 图片不存在且不能处理
                if (mCallback != null) {
                    mCallback.onError(-2, "图片文件不存在");
                }
                return;
            }
        }

        // 直接使用现有图片路径分享
        shareImageInternal(activity, imageFile.getPath(), scene);
    }

    /**
     * 内部图片分享实现
     */
    private void shareImageInternal(Activity activity, String imagePath, int scene) {
        try {
            // 设置分享回调处理
            // 创建Handler来接收微信分享结果
            final Handler shareHandler = new Handler(Looper.getMainLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    // 处理微信分享回调
                    if (mCallback != null) {
                        if (msg.what == 0) { // 成功
                            mCallback.onSuccess();
                        } else if (msg.what == -2) { // 取消
                            mCallback.onCancel();
                        } else { // 错误
                            mCallback.onError(msg.what, "微信分享失败，错误码：" + msg.what);
                        }
                    }
                }
            };

            // 设置分享回调
            WXEntryActivity.setshareHandler(shareHandler);

            // 加载要分享的图片
            Bitmap bmp = BitmapFactory.decodeFile(imagePath);
            if (bmp == null) {
                Toast.makeText(activity, "图片加载失败", Toast.LENGTH_SHORT).show();
                if (mCallback != null) {
                    mCallback.onError(-3, "图片加载失败");
                }
                return;
            }

            // 创建图片对象
            WXImageObject imgObj = new WXImageObject(bmp);

            // 创建多媒体消息
            WXMediaMessage msg = new WXMediaMessage();
            msg.mediaObject = imgObj;

            // 设置缩略图
            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
            bmp.recycle();
            msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

            // 构建发送请求
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction("img");
            req.message = msg;
            req.scene = scene == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;

            // 发送请求
            boolean result = mWxApi.sendReq(req);

            if (!result) {
                Toast.makeText(activity, "微信分享请求发送失败", Toast.LENGTH_SHORT).show();
                if (mCallback != null) {
                    mCallback.onError(-4, "微信分享请求发送失败");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(activity, "微信分享失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            if (mCallback != null) {
                mCallback.onError(-5, "微信分享失败: " + e.getMessage());
            }
        }
    }

    /**
     * 分享Bitmap到微信
     * @param activity 活动
     * @param bitmap 位图对象
     * @param scene 分享场景(0:好友, 1:朋友圈)
     */
    public void shareBitmap(Activity activity, Bitmap bitmap, int scene) {
        if (bitmap == null) {
            Toast.makeText(activity, "分享图片为空", Toast.LENGTH_SHORT).show();
            if (mCallback != null) {
                mCallback.onError(-1, "分享图片为空");
            }
            return;
        }

        // 使用ImageProcessUtils保存Bitmap
        com.tagmae.tsgame_erwang.utils.ImageProcessUtils.saveBitmapToCache(
                activity,
                bitmap,
                new com.tagmae.tsgame_erwang.utils.ImageProcessUtils.ImageSaveCallback() {
                    @Override
                    public void onSuccess(String imagePath) {
                        // 保存成功，使用生成的图片路径分享
                        shareImageInternal(activity, imagePath, scene);
                    }

                    @Override
                    public void onError(String errorMsg) {
                        Toast.makeText(activity, errorMsg, Toast.LENGTH_SHORT).show();
                        if (mCallback != null) {
                            mCallback.onError(-2, errorMsg);
                        }
                    }
                }
        );
    }

    /**
     * 构建交易ID
     */
    private String buildTransaction(String type) {
        return type + System.currentTimeMillis();
    }

    /**
     * 微信分享回调接口
     */
    public interface WeChatShareCallback {
        void onSuccess();
        void onError(int code, String message);
        void onCancel();
    }
}
