package com.rdiot.yx485.widget;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.king.zxing.util.LogUtils;
import com.rdiot.yx485.R;
import com.rdiot.yx485.databinding.ItemPopupMenuBinding;
import com.rdiot.yx485.databinding.PopupMenuCommonBinding;
import com.zcolin.frame.util.DisplayUtil;

import java.util.ArrayList;
import java.util.List;

public class CommonPopupWindow extends PopupWindow {
    private final Activity context;
    private final PopupMenuCommonBinding binding;
    private final MenuAdapter adapter;
    private final List<MenuItem> menuItems = new ArrayList<>();
    private final boolean mIsMatchParent;
    private View backgroundView;

    public CommonPopupWindow(Activity context) {
        this(context, false);
    }

    public CommonPopupWindow(Activity context, boolean isMatchParent) {
        super(context);
        this.context = context;
        mIsMatchParent = isMatchParent;
        binding = PopupMenuCommonBinding.inflate(LayoutInflater.from(context));
        adapter = new MenuAdapter();
        initView();
    }

    private void initView() {
        if (mIsMatchParent) {// 2. 获取屏幕宽度
            DisplayMetrics displayMetrics = new DisplayMetrics();
            context.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int margin = DisplayUtil.dip2px(context, 16);
            int screenWidth = displayMetrics.widthPixels - margin * 4;
            LogUtils.d(String.format("displayMetrics.widthPixels:%s,margin:%s,screenWidth:%s", displayMetrics.widthPixels, margin, screenWidth));
            binding.recyclerView.setMinimumWidth(screenWidth);
        }
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(context));
        binding.recyclerView.setAdapter(adapter);

        // 设置背景
        setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        // 设置弹出窗体可点击
        setFocusable(true);
        setOutsideTouchable(true);

        // 设置弹出窗体的宽和高
        setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        // 设置弹出窗体显示时的动画，从底部向上弹出
        setAnimationStyle(R.style.PopupWindowAnimation);

        // 设置弹出窗体的内容
        setContentView(binding.getRoot());

        // 设置背景变暗
        setOnDismissListener(() -> {
            if (backgroundView != null) {
                backgroundView.setBackgroundColor(Color.TRANSPARENT);
            }
        });
    }

    public void addMenuItem(String title, @DrawableRes int iconRes, View.OnClickListener listener) {
        menuItems.add(new MenuItem(title, iconRes, listener));
        adapter.notifyItemInserted(menuItems.size() - 1);
    }

    public void addMenuItem(String title, View.OnClickListener listener) {
        addMenuItem(title, 0, listener);
    }

    public void show(View anchorView, int offsetX, int offsetY) {
        // 创建背景变暗的View
        if (backgroundView == null) {
            backgroundView = new View(context);
            backgroundView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
        }

        // 将背景View添加到Window中
        View rootView = anchorView.getRootView();
        if (rootView instanceof ViewGroup) {
            ((ViewGroup) rootView).addView(backgroundView);
            backgroundView.setBackgroundColor(Color.argb(100, 0, 0, 0));
        }

        showAsDropDown(anchorView, offsetX, offsetY);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (backgroundView != null && backgroundView.getParent() != null) {
            ((ViewGroup) backgroundView.getParent()).removeView(backgroundView);
        }
    }

    private static class MenuItem {
        String title;
        int iconRes;
        View.OnClickListener listener;

        MenuItem(String title, int iconRes, View.OnClickListener listener) {
            this.title = title;
            this.iconRes = iconRes;
            this.listener = listener;
        }
    }

    private class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.ViewHolder> {
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            ItemPopupMenuBinding itemBinding = ItemPopupMenuBinding.inflate(
                    LayoutInflater.from(parent.getContext()), parent, false);
            return new ViewHolder(itemBinding);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            MenuItem item = menuItems.get(position);
            holder.binding.tvTitle.setText(item.title);

            if (item.iconRes != 0) {
                holder.binding.ivIcon.setVisibility(View.VISIBLE);
                holder.binding.ivIcon.setImageResource(item.iconRes);
            } else {
                holder.binding.ivIcon.setVisibility(View.GONE);
            }

            holder.itemView.setOnClickListener(v -> {
                if (item.listener != null) {
                    item.listener.onClick(v);
                }
                dismiss();
            });
        }

        @Override
        public int getItemCount() {
            return menuItems.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            ItemPopupMenuBinding binding;

            ViewHolder(ItemPopupMenuBinding binding) {
                super(binding.getRoot());
                this.binding = binding;
            }
        }
    }
} 