package com.cooleshow.base.widgets.poplist;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cooleshow.base.R;
import com.cooleshow.base.utils.PopupUtil;

import java.util.List;

/**
 * @author dengqw
 * @time 2022/6/28 10:24
 * @describe：
 **/
public class PopupListWindow {

    private Context mContext;
    private View mAnchorView;
    private List<PopMenuBean> mPopupItemList;
    private PopupListListener mPopupListListener;
    private PopupWindow mPopupWindow;

    public PopupListWindow(Context context) {
        mContext = context;
    }

    public void showListPop(View anchorView, List<PopMenuBean> popupItemList, PopupListListener popupListListener) {
        this.mAnchorView = anchorView;
        this.mPopupItemList = popupItemList;
        this.mPopupListListener = popupListListener;
        this.mPopupWindow = null;
        showPopupListWindow();
    }

    private void showPopupListWindow() {
        if (mContext instanceof Activity && ((Activity) mContext).isFinishing()) {
            return;
        }
        if (mPopupWindow == null) {
            View popupContentView = LayoutInflater.from(mContext).inflate(R.layout.list_popu_layout, null);
            RecyclerView recyclerView = popupContentView.findViewById(R.id.recyclerView);
            View bg = popupContentView.findViewById(com.cooleshow.base.R.id.view);
            bg.setOnClickListener(v -> {
                if (mPopupWindow != null) {
                    mPopupWindow.dismiss();
                }
            });
            CourseStatusFilterAdapter listAdapter = new CourseStatusFilterAdapter();
            listAdapter.setOnItemClickListener((adapter, view, position) -> {
                PopMenuBean bean = listAdapter.getData().get(position);
                if (listAdapter != null) {
                    listAdapter.setSelect(position);
                }
                if (mPopupListListener != null) {
                    mPopupListListener.onPopupListClick(position);
                }
                mPopupWindow.dismiss();
            });
            recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            recyclerView.setAdapter(listAdapter);
            listAdapter.setNewInstance(mPopupItemList);
            mPopupWindow = PopupUtil.createNoBackPopupWindow(popupContentView, mContext, ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT, true);
        }
        if (!mPopupWindow.isShowing()) {
            mPopupWindow.showAsDropDown(mAnchorView);
        }
    }

    public interface PopupListListener {
        void onPopupListClick(int position);
    }
}
