package com.tagmae.tsgame_erwang;

import android.annotation.TargetApi;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.os.Build;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import com.tencent.smtt.sdk.ValueCallback;

import com.tagmae.jsbridge.BridgeWebView;

import java.io.ByteArrayOutputStream;

/**
 * WebView截图工具类，专门用于截取WebView内容
 */
public class WebViewScreenshotUtil {
    private static final String TAG = "WebViewScreenshotUtil";

    /**
     * Canvas转base64回调接口
     */
    public interface CanvasToBase64Callback {
        void onSuccess(String base64Data);
        void onError(String error);
    }

    static {
        // 在静态初始化块中启用整个文档绘制模式（for Android 5.0+）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                WebView.enableSlowWholeDocumentDraw();
                Log.d(TAG, "启用了WebView慢速整页绘制模式");
            } catch (Exception e) {
                Log.e(TAG, "启用WebView慢速绘制模式失败: " + e.getMessage());
            }
        }
    }

    /**
     * 截取BridgeWebView的内容（简单直接的方法）
     *
     * @param webView 要截图的BridgeWebView
     * @return 截图Bitmap，失败返回null
     */
    public static Bitmap captureWebView(BridgeWebView webView) {
        if (webView == null) {
            Log.e(TAG, "WebView is null");
            return null;
        }

        if (webView.getWidth() == 0 || webView.getHeight() == 0) {
            Log.e(TAG, "WebView dimensions are zero");
            return null;
        }

        try {
            // 创建与WebView相同大小的位图
            Bitmap bitmap = Bitmap.createBitmap(webView.getWidth(), webView.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);

            // 绘制WebView内容
            webView.draw(canvas);

            // 检查是否为空白或黑屏
            if (isBitmapEmpty(bitmap)) {
                Log.d(TAG, "Simple capture resulted in empty bitmap, trying other methods");
                return captureBridgeWebView(webView);
            }

            return bitmap;
        } catch (Exception e) {
            Log.e(TAG, "Error in captureWebView: " + e.getMessage());
            return captureBridgeWebView(webView);
        }
    }

    /**
     * 截取BridgeWebView的内容
     * 尝试多种方法，确保能够获取到有效的截图
     *
     * @param webView 要截图的BridgeWebView
     * @return 截图Bitmap，失败返回null
     */
    public static Bitmap captureBridgeWebView(BridgeWebView webView) {
        if (webView == null) {
            Log.e(TAG, "WebView is null");
            return null;
        }

        // 首先使用直接绘制的方式（适用于大多数情况）
        Bitmap bitmap = captureWebViewDirectly(webView);
        if (bitmap != null && !isBitmapEmpty(bitmap)) {
            Log.d(TAG, "Direct capture succeeded");
            return bitmap;
        }

        // 如果直接绘制方式失败，尝试禁用硬件加速后再截图
        Log.d(TAG, "Direct capture failed or empty, trying with hardware acceleration disabled");
        bitmap = captureWebViewWithHardwareAccelerationDisabled(webView);
        if (bitmap != null && !isBitmapEmpty(bitmap)) {
            Log.d(TAG, "Capture with hardware acceleration disabled succeeded");
            return bitmap;
        }

        // 如果前两种方法都失败，尝试使用Picture方式
        Log.d(TAG, "Previous methods failed, trying with Picture method");
        bitmap = captureWebViewUsingPicture(webView);
        if (bitmap != null && !isBitmapEmpty(bitmap)) {
            Log.d(TAG, "Picture method succeeded");
            return bitmap;
        }

        Log.e(TAG, "All screenshot methods failed");
        return null;
    }

    /**
     * 判断Bitmap是否为空（全黑或透明）
     */
    private static boolean isBitmapEmpty(Bitmap bitmap) {
        if (bitmap == null || bitmap.getWidth() == 0 || bitmap.getHeight() == 0) {
            return true;
        }

        // 采样检查bitmap是否全黑或全透明
        int[] pixels = new int[10]; // 只采样几个点
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        // 获取中心区域的几个像素点
        bitmap.getPixels(pixels, 0, 1, width/2, height/2, 1, 1);
        bitmap.getPixels(pixels, 1, 1, width/3, height/3, 1, 1);
        bitmap.getPixels(pixels, 2, 1, width*2/3, height*2/3, 1, 1);

        // 检查这些像素点是否全是黑色或全透明
        boolean allBlackOrTransparent = true;
        for (int i = 0; i < 3; i++) {
            int pixel = pixels[i];
            int alpha = (pixel >> 24) & 0xff;
            int red = (pixel >> 16) & 0xff;
            int green = (pixel >> 8) & 0xff;
            int blue = pixel & 0xff;

            // 如果不是黑色或透明，那么bitmap不是空的
            if (alpha > 20 && (red > 10 || green > 10 || blue > 10)) {
                allBlackOrTransparent = false;
                break;
            }
        }

        return allBlackOrTransparent;
    }

    /**
     * 直接绘制WebView到Bitmap
     */
    private static Bitmap captureWebViewDirectly(BridgeWebView webView) {
        try {
            if (webView.getWidth() == 0 || webView.getHeight() == 0) {
                Log.e(TAG, "WebView has not been laid out yet");
                return null;
            }

            Bitmap bitmap = Bitmap.createBitmap(webView.getWidth(), webView.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            webView.draw(canvas);

            return bitmap;
        } catch (Exception e) {
            Log.e(TAG, "Error in captureWebViewDirectly: " + e.getMessage());
            return null;
        }
    }

    /**
     * 暂时禁用硬件加速并绘制WebView
     */
    private static Bitmap captureWebViewWithHardwareAccelerationDisabled(BridgeWebView webView) {
        try {
            if (webView.getWidth() == 0 || webView.getHeight() == 0) {
                Log.e(TAG, "WebView has not been laid out yet");
                return null;
            }

            boolean wasHardwareAccelerated = false;

            // 只在Android 3.0(API 11)及以上版本调用isHardwareAccelerated方法
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                try {
                    wasHardwareAccelerated = webView.isHardwareAccelerated();
                } catch (Exception e) {
                    Log.e(TAG, "Error checking hardware acceleration: " + e.getMessage());
                }
            }

            // 临时禁用硬件加速
            if (wasHardwareAccelerated) {
                try {
                    webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
                } catch (Exception e) {
                    Log.e(TAG, "Error disabling hardware acceleration: " + e.getMessage());
                }
            }

            Bitmap bitmap = Bitmap.createBitmap(webView.getWidth(), webView.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);

            // 强制绘制
            webView.computeScroll();
            webView.draw(canvas);

            // 恢复硬件加速状态
            if (wasHardwareAccelerated) {
                try {
                    webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
                } catch (Exception e) {
                    Log.e(TAG, "Error restoring hardware acceleration: " + e.getMessage());
                }
            }

            return bitmap;
        } catch (Exception e) {
            Log.e(TAG, "Error in captureWebViewWithHardwareAccelerationDisabled: " + e.getMessage());
            return null;
        }
    }

    /**
     * 使用Picture方式截取WebView
     */
    private static Bitmap captureWebViewUsingPicture(BridgeWebView webView) {
        try {
            if (webView.getWidth() == 0 || webView.getHeight() == 0) {
                Log.e(TAG, "WebView has not been laid out yet");
                return null;
            }

            // 确保WebView已经加载完成
            webView.measure(View.MeasureSpec.makeMeasureSpec(webView.getWidth(), View.MeasureSpec.EXACTLY),
                    View.MeasureSpec.makeMeasureSpec(webView.getHeight(), View.MeasureSpec.EXACTLY));
            webView.layout(0, 0, webView.getWidth(), webView.getHeight());

            // 获取WebView内容
            Picture picture = webView.capturePicture();
            if (picture != null && picture.getWidth() > 0 && picture.getHeight() > 0) {
                Bitmap bitmap = Bitmap.createBitmap(picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(bitmap);
                picture.draw(canvas);
                return bitmap;
            }

            return null;
        } catch (Exception e) {
            Log.e(TAG, "Error in captureWebViewUsingPicture: " + e.getMessage());
            return null;
        }
    }

    /**
     * 从Activity中获取并截取BridgeWebView
     *
     * @param activity 包含BridgeWebView的Activity
     * @return 截图Bitmap，失败返回null
     */
    public static Bitmap captureWebViewFromActivity(Activity activity) {
        if (activity == null) {
            Log.e(TAG, "Activity is null");
            return null;
        }

        BridgeWebView webView = null;        // 对NewwebviewActivity特别处理 - 直接使用静态变量
        if (activity instanceof NewwebviewActivity) {
            webView = NewwebviewActivity.x5webview;
            if (webView != null) {
                Log.d(TAG, "Found WebView in NewwebviewActivity using static field");
            } else {
                Log.w(TAG, "Static x5webview is null in NewwebviewActivity");
            }
        }
        // 对webviewActivity特别处理
        else if (activity.getClass().getSimpleName().equals("webviewActivity")) {
            try {
                java.lang.reflect.Field field = activity.getClass().getDeclaredField("x5webview");
                field.setAccessible(true);
                webView = (BridgeWebView) field.get(activity);
                Log.d(TAG, "Found WebView in webviewActivity");
            } catch (Exception e) {
                Log.e(TAG, "Failed to get WebView from webviewActivity: " + e.getMessage());
            }
        }

        // 如果找到了WebView，进行截图
        if (webView != null) {
            Log.d(TAG, "Capturing WebView: width=" + webView.getWidth() + ", height=" + webView.getHeight());
            // 使用新的简化截图方法
            return captureWebView(webView);
        }

        Log.e(TAG, "No WebView found in activity");        return null;
    }

    /**
     * 将Bitmap转换为base64编码
     * 
     * @param bitmap 要转换的bitmap
     * @param quality 压缩质量(0-100)
     * @return base64编码字符串，失败返回null
     */
    public static String bitmapToBase64(Bitmap bitmap, int quality) {
        if (bitmap == null) {
            Log.e(TAG, "Bitmap is null");
            return null;
        }

        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, quality, outputStream);
            byte[] byteArray = outputStream.toByteArray();
            return Base64.encodeToString(byteArray, Base64.NO_WRAP);
        } catch (Exception e) {
            Log.e(TAG, "Error converting bitmap to base64: " + e.getMessage());
            return null;
        }
    }

    /**
     * 截取WebView并直接转换为base64编码
     * 
     * @param webView 要截图的BridgeWebView
     * @param quality 压缩质量(0-100)
     * @return base64编码字符串，失败返回null
     */
    public static String captureWebViewToBase64(BridgeWebView webView, int quality) {
        Bitmap bitmap = captureWebView(webView);
        if (bitmap != null) {
            String base64 = bitmapToBase64(bitmap, quality);
            bitmap.recycle(); // 释放bitmap内存
            return base64;
        }
        return null;
    }

    /**
     * 截取WebView并转换为base64编码（默认质量90）
     * 
     * @param webView 要截图的BridgeWebView
     * @return base64编码字符串，失败返回null
     */
    public static String captureWebViewToBase64(BridgeWebView webView) {
        return captureWebViewToBase64(webView, 90);
    }

    /**
     * 通过JavaScript获取WebView中的Canvas内容并转为base64
     * 这个方法专门用于获取HTML5 Canvas元素的内容
     * 
     * @param webView 包含Canvas的WebView
     * @param canvasId Canvas元素的ID，如果为null或空则获取第一个Canvas
     * @param callback 获取结果的回调
     */
    public static void getCanvasBase64FromWebView(BridgeWebView webView, String canvasId, CanvasToBase64Callback callback) {
        if (webView == null) {
            if (callback != null) {
                callback.onError("WebView is null");
            }
            return;
        }

        // 构建JavaScript代码
        String javascript;
        if (canvasId != null && !canvasId.trim().isEmpty()) {
            // 根据ID获取指定Canvas
            javascript = "(function() {" +
                    "try {" +
                    "var canvas = document.getElementById('" + canvasId + "');" +
                    "if (!canvas) return 'Canvas not found';" +
                    "if (canvas.tagName.toLowerCase() !== 'canvas') return 'Element is not a canvas';" +
                    "return canvas.toDataURL('image/png');" +
                    "} catch(e) {" +
                    "return 'Error: ' + e.message;" +
                    "}" +
                    "})();";
        } else {
            // 获取页面中第一个Canvas元素
            javascript = "(function() {" +
                    "try {" +
                    "var canvas1 = document.createElement('canvas');"+
                    "canvas1.width=720,canvas1.height=405;"+
                    "var g=canvas1.getContext('2d');"+
                    "g.drawImage(iui.canvas,0,0,720,405);"+
                    "return canvas1.toDataURL('image/jpeg',1);"+
                    "} catch(e) {" +
                    "return 'Error: ' + e.message;" +
                    "}" +
                    "})();";
        }

        // 执行JavaScript代码
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript(javascript, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    if (callback != null) {
                        if (value != null && value.startsWith("\"data:image/")) {
                            // 移除引号和data:image/png;base64,前缀
                            String base64 = value.substring(1, value.length() - 1); // 移除引号
                            if (base64.startsWith("data:image/png;base64,")) {
                                base64 = base64.substring("data:image/png;base64,".length());
                            }
                            callback.onSuccess(base64);
                        } else {
                            String error = value != null ? value.replace("\"", "") : "Unknown error";
                            callback.onError(error);
                        }
                    }
                }
            });
        } else {
            if (callback != null) {
                callback.onError("Android version too low (requires API 19+)");
            }
        }
    }

    /**
     * 获取WebView中所有Canvas元素的内容
     * 
     * @param webView 包含Canvas的WebView
     * @param callback 获取结果的回调
     */
    public static void getAllCanvasBase64FromWebView(BridgeWebView webView, CanvasToBase64Callback callback) {
        if (webView == null) {
            if (callback != null) {
                callback.onError("WebView is null");
            }
            return;
        }

        String javascript = "(function() {" +
                "try {" +
                "var canvases = document.getElementsByTagName('canvas');" +
                "if (canvases.length === 0) return 'No canvas found';" +
                "var results = [];" +
                "for (var i = 0; i < canvases.length; i++) {" +
                "try {" +
                "var canvas = canvases[i];" +
                "var dataUrl = canvas.toDataURL('image/png');" +
                "results.push({" +
                "index: i," +
                "id: canvas.id || 'canvas_' + i," +
                "width: canvas.width," +
                "height: canvas.height," +
                "dataUrl: dataUrl" +
                "});" +
                "} catch(e) {" +
                "results.push({" +
                "index: i," +
                "error: e.message" +
                "});" +
                "}" +
                "}" +
                "return JSON.stringify(results);" +
                "} catch(e) {" +
                "return 'Error: ' + e.message;" +
                "}" +
                "})();";


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript(javascript, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    if (callback != null) {
                        if (value != null && value.startsWith("\"[")) {
                            // 移除引号
                            String jsonResult = value.substring(1, value.length() - 1)
                                    .replace("\\\"", "\"")
                                    .replace("\\\\", "\\");
                            callback.onSuccess(jsonResult);
                        } else {
                            String error = value != null ? value.replace("\"", "") : "Unknown error";
                            callback.onError(error);
                        }
                    }
                }
            });
        } else {
            if (callback != null) {
                callback.onError("Android version too low (requires API 19+)");
            }
        }
    }

    /**
     * 高级Canvas截图方法 - 组合使用多种技术
     * 1. 首先尝试JavaScript获取Canvas内容
     * 2. 如果失败，则回退到传统截图方法
     * 
     * @param webView 包含Canvas的WebView
     * @param canvasId Canvas元素ID，可以为null
     * @param callback 获取结果的回调
     */
    public static void captureCanvasAdvanced(BridgeWebView webView, String canvasId, CanvasToBase64Callback callback) {
        // 首先尝试JavaScript方法
        getCanvasBase64FromWebView(webView, canvasId, new CanvasToBase64Callback() {
            @Override
            public void onSuccess(String base64Data) {
                Log.d(TAG, "Successfully captured canvas using JavaScript method");
                if (callback != null) {
                    callback.onSuccess(base64Data);
                }
            }

            @Override
            public void onError(String error) {
                Log.d(TAG, "JavaScript method failed: " + error + ", trying fallback method");
                // JavaScript方法失败，使用传统截图方法作为后备
                String fallbackBase64 = captureWebViewToBase64(webView);
                if (fallbackBase64 != null) {
                    Log.d(TAG, "Fallback method succeeded");
                    if (callback != null) {
                        callback.onSuccess(fallbackBase64);
                    }
                } else {
                    Log.e(TAG, "All methods failed");
                    if (callback != null) {
                        callback.onError("All capture methods failed: " + error);
                    }
                }
            }
        });
    }

    /**
     * 便捷方法：直接从全局WebView获取Canvas base64数据
     * 
     * @param canvasId Canvas元素的ID，如果为null则获取第一个Canvas
     * @param callback 获取结果的回调
     */
    public static void getCanvasBase64FromGlobalWebView(String canvasId, CanvasToBase64Callback callback) {
        BridgeWebView webView = NewwebviewActivity.getWebView();
        if (webView == null) {
            if (callback != null) {
                callback.onError("Global WebView is not available");
            }
            return;
        }
        getCanvasBase64FromWebView(webView, canvasId, callback);
    }

    /**
     * 便捷方法：直接从全局WebView获取Canvas base64数据（使用默认Canvas）
     * 
     * @param callback 获取结果的回调
     */
    public static void getCanvasBase64FromGlobalWebView(CanvasToBase64Callback callback) {
        getCanvasBase64FromGlobalWebView(null, callback);
    }
}
