package org.leanflutter.plugins.flutter_qiyu;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.Gravity;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.ComponentActivity;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.qiyukf.unicorn.api.event.EventCallback;
import com.qiyukf.unicorn.api.event.UnicornEventBase;
import com.qiyukf.unicorn.api.event.entry.RequestPermissionEventEntry;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import android.content.pm.PackageManager;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback;

import android.app.Activity;

public class DemoRequestPermissionEvent implements UnicornEventBase<RequestPermissionEventEntry> {
    private final FlutterQiyuPlugin plugin;
    private final Context context;
    private Map<String, String> h5MessageHandlerMap = new HashMap<>();
    private View tipView;
    private WindowManager windowManager;
    private boolean isTipVisible = false;
    private static final int REQUEST_CODE = 100;

    public DemoRequestPermissionEvent(Context context, FlutterQiyuPlugin plugin) {
        this.context = context;
        this.plugin = plugin;

        // 初始化权限映射
        h5MessageHandlerMap.put("android.permission.RECORD_AUDIO", "麦克风");
        h5MessageHandlerMap.put("android.permission.CAMERA", "相机");
        h5MessageHandlerMap.put("android.permission.READ_EXTERNAL_STORAGE", "存储");
        h5MessageHandlerMap.put("android.permission.WRITE_EXTERNAL_STORAGE", "存储");
        h5MessageHandlerMap.put("android.permission.READ_MEDIA_AUDIO", "多媒体文件");
        h5MessageHandlerMap.put("android.permission.READ_MEDIA_IMAGES", "多媒体文件");
        h5MessageHandlerMap.put("android.permission.READ_MEDIA_VIDEO", "多媒体文件");
        h5MessageHandlerMap.put("android.permission.POST_NOTIFICATIONS", "通知栏权限");
    }

    private String transToPermissionStr(List<String> permissionList) {
        if (permissionList == null || permissionList.size() == 0) {
            return "";
        }
        HashSet<String> set = new HashSet<>();
        for (int i = 0; i < permissionList.size(); i++) {
            if (!TextUtils.isEmpty(h5MessageHandlerMap.get(permissionList.get(i)))) {
                set.add(h5MessageHandlerMap.get(permissionList.get(i)));
            }
        }
        if (set.isEmpty()) {
            return "";
        }
        StringBuilder str = new StringBuilder();
        for (String temp : set) {
            str.append(temp);
            str.append("、");
        }
        if (str.length() > 0) {
            str.deleteCharAt(str.length() - 1);
        }
        return str.toString();
    }

    private void showPermissionTip(Context context, String permission) {
        if (windowManager == null) {
            windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        }

        // 如果已经有提示在显示，先移除
        removeTipView();

        // 创建提示视图
        tipView = LayoutInflater.from(context).inflate(R.layout.permission_tip_view, null);
        
        // 从 tipView 中找到 TextView
        TextView tipText = tipView.findViewById(R.id.tip_text);

        // 设置提示文本
        tipText.setText(getTipText(permission));

        // 设置布局参数
        WindowManager.LayoutParams params = new WindowManager.LayoutParams();
        params.type = WindowManager.LayoutParams.TYPE_APPLICATION;
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params.format = PixelFormat.TRANSLUCENT;
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;

        // 设置 y 值为 50dp
        params.gravity = Gravity.TOP;
        params.y = (int) (50 * context.getResources().getDisplayMetrics().density); // 设置 y 值为 50dp

        // 显示提示
        try {
            windowManager.addView(tipView, params);
            isTipVisible = true; // 更新标志
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void removeTipView() {
        if (tipView != null && windowManager != null) {
            try {
                windowManager.removeView(tipView);
            } catch (Exception e) {
                e.printStackTrace();
            }
            tipView = null;
        }
    }

    private String getTipText(String permission) {
        if (permission.contains("CAMERA")) {
            return "使用该功能需要使用 \"开启相机权限\",开启相机权限后，授权后您可以使用拍摄照片发送图片与在线客服联系并协助您解答疑惑\"等功能";
        } else if (permission.contains("RECORD_AUDIO")) {
            return "使用该功能需要使用 \"麦克风权限\"，开启麦克风权限后，用于发送语音，录制有声视频，与在线客服联系并协助您解答疑惑";
        } else if (permission.contains("READ_EXTERNAL_STORAGE") || permission.contains("WRITE_EXTERNAL_STORAGE")) {
            return "使用该功能需要使用 \"存储权限\",开启存储权限后，用于保存文件。";
        } else if (permission.contains("READ_MEDIA_AUDIO") || permission.contains("READ_MEDIA_IMAGES") || permission.contains("READ_MEDIA_VIDEO")) {
            return "使用该功能需要使用 \"存储权限\",开启存储权限后，用于发送文件，与在线客服联系并协助您解答疑惑";
        } else if (permission.contains("POST_NOTIFICATIONS")) {
            return "使用该功能需要使用 \"通知权限\"，开启通知权限后，您可以及时收到客服消息提醒。";
        } else {
            return "开启权限后，您可以使用相关功能。";
        }
    }

    @Override
    public void onEvent(RequestPermissionEventEntry entry, Context context, EventCallback<RequestPermissionEventEntry> callback) {
        List<String> permissions = entry.getPermissionList();
        for (String permission : permissions) {
            showPermissionDialog(context, entry.getScenesType(), permission, entry, callback);
        }
    }

    private void showPermissionDialog(Context context, int type, String permissionName,
                                      RequestPermissionEventEntry entry, EventCallback<RequestPermissionEventEntry> callback) {
        Dialog dialog = new Dialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        View dialogView = LayoutInflater.from(context).inflate(R.layout.permission_dialog, null);
        dialog.setContentView(dialogView);

        // 设置消息
        TextView messageView = dialogView.findViewById(R.id.message);
        messageView.setText(getPermissionMessage(type, permissionName));

        // 设置关闭按钮
        ImageView closeButton = dialogView.findViewById(R.id.close_button);
        closeButton.setOnClickListener(v -> dialog.dismiss());

        // 设置确认按钮
        Button confirmButton = dialogView.findViewById(R.id.confirm_button);
        confirmButton.setOnClickListener(v -> {


            // 显示权限提示
            List<String> permissions = entry.getPermissionList();
            if (!permissions.isEmpty()) {
                showPermissionTip(context, permissions.get(0));

            }

            if (context instanceof ComponentActivity) {
                for (String permission : permissions) {
                    new ActivityForResultUtil<String, Boolean>().startActivityForResult((ComponentActivity) context, new ActivityResultContracts.RequestPermission(), permission, result -> {
                        Log.d("qqq", "result: " + result);
                        if (isTipVisible) {
                            removeTipView();
                            isTipVisible = false;
                        }
                        if (result) {
                            dialog.dismiss();
                            callback.onProcessEventSuccess(entry);
                        } else {
                            dialog.dismiss();
                        }
                    });
                }
            }
        });

        // 设置对话框宽度
        Window window = dialog.getWindow();
        if (window != null) {
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.WRAP_CONTENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(params);
        }


        dialog.show();
    }

    private String getPermissionMessage(int type, String permissionName) {
        switch (type) {
            case 4: // 视频
                return "使用该功能需要使用 \"存储权限\",启用该权限后，用于发送视频文件，与在线客服联系并协助您解答疑惑";
            case 2:
                return "使用该功能需要使用 \"存储权限\",开启存储权限后，用于保存文件。";
            case 0:
            case 5: // 存储
                return "使用该功能需要使用 \"存储权限\",开启存储权限后，用于发送文件，与在线客服联系并协助您解答疑惑";
            case 6: // 相册
                return "使用该功能需要使用 \"相册权限\"，用于发送图片文件，与在线客服联系并协助您解答疑惑";
            case 1: // 拍摄视频
                return "使用该功能需要使用 \"开启相机权限和录音权限\",开启该权限后，授权后您可以拍摄视频，用于发送视频与在线客服联系并协助您解答疑惑等功能";
            case 7: // 拍照
                return "使用该功能需要使用 \"开启相机权限\",开启相机权限后，授权后您可以使用拍摄照片用于发送图片与在线客服联系并协助您解答疑惑等功能";
            case 8: // 录音
                return "使用该功能需要使用 \"麦克风权限\"，开启麦克风权限后，用于发送语音，与在线客服联系并协助您解答疑惑";
            case 10: // 通知
                return "使用该功能需要使用 \"通知权限\"，开启通知权限后，您可以及时收到客服消息提醒。";
            default:
                return "使用该功能需要使用 \"" + permissionName + "\"，开启权限后才能正常使用该功能。";
        }
    }

    @Override
    public boolean onDenyEvent(Context context, RequestPermissionEventEntry entry) {
        if (isTipVisible) {
            removeTipView();
            isTipVisible = false;
        }
        String permissionName = transToPermissionStr(entry.getPermissionList());

        Dialog dialog = new Dialog(context);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

        View dialogView = LayoutInflater.from(context).inflate(R.layout.permission_dialog, null);
        dialog.setContentView(dialogView);

        // 设置消息
        TextView messageView = dialogView.findViewById(R.id.message);
        messageView.setText("您没有开启\"" + (TextUtils.isEmpty(permissionName) ? "相关" : permissionName)
                + "\"权限，是否前往设置开启？");

        // 设置关闭按钮
        ImageView closeButton = dialogView.findViewById(R.id.close_button);
        closeButton.setOnClickListener(v -> dialog.dismiss());

        // 设置确认按钮
        Button confirmButton = dialogView.findViewById(R.id.confirm_button);
        confirmButton.setText("去设置");
        confirmButton.setOnClickListener(v -> {
            List<String> permissions = entry.getPermissionList();
            for (String permission : permissions) {

            }
            dialog.dismiss();
        });

        // 设置对话框宽度
        Window window = dialog.getWindow();
        if (window != null) {
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.WRAP_CONTENT;
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            window.setAttributes(params);
        }

        dialog.setOnDismissListener(dialogInterface -> {
            // 当对话框关闭时，检查是否需要移除提示
            if (isTipVisible) {
                removeTipView();
                isTipVisible = false;
            }
        });

        dialog.show();
        return true;
    }

    // 在适当的时机（比如 Activity 销毁时）清理资源
    public boolean cleanUp() {
        try {
            removeTipView(); // 尝试移除提示视图
            Log.d("qqq", "cleanUp successful");
            return true; // 清理成功
        } catch (Exception e) {
            Log.e("qqq", "cleanUp failed", e);
            return false; // 清理失败
        }
    }
}

