package com.fujica.abk.utils;

import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.ProgressBar;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.colors.RgbColor;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.Rect;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

/**
 * Loading对话框工具类
 * 全屏遮罩，中间显示loading，不可点击，不可取消
 */
public class LoadingDialog {
    private static CommonDialog currentDialog = null;
    private static int showCount = 0; // 显示计数，用于处理多个请求同时显示loading的情况

    /**
     * 在主线程显示Loading
     */
    private static void showOnMainThread(Context context) {
        if (context == null) {
            return;
        }
        
        // 获取主线程的 EventRunner
        EventRunner mainRunner = EventRunner.getMainEventRunner();
        if (mainRunner == null) {
            // 如果获取不到主线程，直接在当前线程显示（可能已经是主线程）
            showDialog(context);
            return;
        }
        
        // 创建主线程的 EventHandler
        EventHandler mainHandler = new EventHandler(mainRunner);
        mainHandler.postTask(() -> {
            showDialog(context);
        });
    }

    /**
     * 在主线程隐藏Loading
     */
    private static void hideOnMainThread() {
        // 获取主线程的 EventRunner
        EventRunner mainRunner = EventRunner.getMainEventRunner();
        if (mainRunner == null) {
            // 如果获取不到主线程，直接在当前线程隐藏（可能已经是主线程）
            hideDialog();
            return;
        }
        
        // 创建主线程的 EventHandler
        EventHandler mainHandler = new EventHandler(mainRunner);
        mainHandler.postTask(() -> {
            hideDialog();
        });
    }

    /**
     * 显示Loading对话框
     */
    private static void showDialog(Context context) {
        if (currentDialog != null && currentDialog.isShowing()) {
            // 如果已经显示，增加计数
            showCount++;
            return;
        }

        try {
            // 创建固定大小的布局（不再全屏）
            DirectionalLayout rootLayout = new DirectionalLayout(context);
            // 设置固定大小，根据内容自适应
            DirectionalLayout.LayoutConfig rootConfig = new DirectionalLayout.LayoutConfig(
                DirectionalLayout.LayoutConfig.MATCH_CONTENT,
                DirectionalLayout.LayoutConfig.MATCH_CONTENT
            );
            rootLayout.setLayoutConfig(rootConfig);
            rootLayout.setAlignment(LayoutAlignment.CENTER);
            // 不设置背景，保持全透明
            
            // 创建内容容器（白色圆角卡片）
            DirectionalLayout contentLayout = new DirectionalLayout(context);
            DirectionalLayout.LayoutConfig contentConfig = new DirectionalLayout.LayoutConfig(
                DirectionalLayout.LayoutConfig.MATCH_CONTENT,
                DirectionalLayout.LayoutConfig.MATCH_CONTENT
            );
            contentLayout.setLayoutConfig(contentConfig);
            contentLayout.setOrientation(DirectionalLayout.VERTICAL);
            contentLayout.setAlignment(LayoutAlignment.CENTER);
            contentLayout.setPadding(40, 40, 40, 40);
            
            // 设置白色圆角背景
            ShapeElement contentBackground = new ShapeElement();
            contentBackground.setShape(ShapeElement.RECTANGLE);
            contentBackground.setRgbColor(new RgbColor(255, 255, 255, 255));
            contentBackground.setCornerRadius(16);
            contentLayout.setBackground(contentBackground);
            
            // 创建ProgressBar
            ProgressBar progressBar = new ProgressBar(context);
            DirectionalLayout.LayoutConfig progressConfig = new DirectionalLayout.LayoutConfig(
                80, 80
            );
            progressBar.setLayoutConfig(progressConfig);
            progressBar.setProgressColor(Color.BLUE);
            progressBar.setIndeterminate(true); // 设置为无限循环
            
            // 创建提示文字（可选）
            Text text = new Text(context);
            DirectionalLayout.LayoutConfig textConfig = new DirectionalLayout.LayoutConfig(
                DirectionalLayout.LayoutConfig.MATCH_CONTENT,
                DirectionalLayout.LayoutConfig.MATCH_CONTENT
            );
            text.setLayoutConfig(textConfig);
            text.setText("加载中...");
            text.setTextSize(14);
            text.setTextColor(new Color(Color.getIntColor("#FF666666")));
            text.setMarginTop(16);
            
            // 添加到内容容器
            contentLayout.addComponent(progressBar);
            contentLayout.addComponent(text);
            
            // 添加到根布局
            rootLayout.addComponent(contentLayout);
            // 创建对话框
            CommonDialog dialog = new CommonDialog(context);
            // 注意：CommonDialog 在 API 7 中可能无法完全移除外层全屏蒙层
            // 只能通过 setTransparent(true) 设置对话框背景透明
            dialog.setTransparent(true); // 设置对话框背景透明
            dialog.setContentCustomComponent(rootLayout);
            dialog.setAutoClosable(false); // 不可自动关闭
//            dialog.setCanceledOnTouchOutside(false); // 点击外部不可关闭
            
            // 显示对话框
            dialog.show();
            currentDialog = dialog;
            showCount = 1;
            
        } catch (Exception e) {
            Log.error("显示Loading失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 隐藏Loading对话框
     */
    private static void hideDialog() {
        if (currentDialog == null) {
            return;
        }

        try {
            // 减少计数
            showCount--;
            
            // 只有当计数为0时才真正关闭对话框
            if (showCount <= 0) {
                if (currentDialog.isShowing()) {
                    currentDialog.destroy();
                }
                currentDialog = null;
                showCount = 0;
            }
        } catch (Exception e) {
            Log.error("隐藏Loading失败: " + e.getMessage());
            e.printStackTrace();
            // 出错时强制重置
            currentDialog = null;
            showCount = 0;
        }
    }

    /**
     * 显示Loading
     */
    public static void show(Context context) {
        showOnMainThread(context);
    }

    /**
     * 隐藏Loading
     */
    public static void hide() {
        hideOnMainThread();
    }

    /**
     * 强制关闭所有Loading（用于异常情况）
     */
    public static void forceHide() {
        if (currentDialog != null) {
            try {
                if (currentDialog.isShowing()) {
                    currentDialog.destroy();
                }
            } catch (Exception e) {
                Log.error("强制关闭Loading失败: " + e.getMessage());
            }
            currentDialog = null;
            showCount = 0;
        }
    }
}

