package com.police.policedatasystem.mine.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.police.policedatasystem.R;
import com.police.policedatasystem.apply.model.ApplyType;
import com.police.policedatasystem.databinding.DialogSelectorBinding;
import com.police.policedatasystem.databinding.FragmentMineBinding;
import com.police.policedatasystem.indexActivity;
import com.police.policedatasystem.mine.activity.ApplyDetailActivity;
import com.police.policedatasystem.mine.adapter.MineApplyListAdapter;
import com.police.policedatasystem.mine.model.Apply;
import com.police.policedatasystem.mine.viewmodel.MineViewModel;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class MineFragment extends Fragment {
    private FragmentMineBinding binding;
    private PopupWindow popupWindow;
    private MineApplyListAdapter adapter;
    private List<Apply> applyList;
    private List<ApplyType> applyTypes;
    private List<ApplyType> applyXXLY;
    private List<ApplyType> applyBLZT;
    private final MineViewModel viewModel = new MineViewModel(this, (indexActivity) getActivity());

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentMineBinding.inflate(inflater);
        initView();
        return binding.getRoot();
    }

    private void initView() {
        setPopupWindow();
        binding.mineTypeGroup.setOnClickListener(view -> {
            popupWindow.setWidth(binding.mineTypeGroup.getWidth());
            popupWindow.showAsDropDown(binding.mineTypeGroup);
        });
//        binding.refreshLayout.setRefreshHeader(new ClassicsHeader(getContext()));
//        binding.refreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        binding.mineRvGroup.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new MineApplyListAdapter();
        binding.mineRvGroup.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter1, view, position) -> applyDetail(applyList.get(position).getBh()));
        binding.mineTvInput.setOnClickListener(view -> {
            switch (searchType) {
                case "sy":
                    showDialog((TextView) view, "选择申请事由", applyTypes.stream()
                            .map(ApplyType::getDictLabel)
                            .collect(Collectors.toList()));
                    break;
                case "ly":
                    showDialog((TextView) view, "选择信息来源", applyXXLY.stream()
                            .map(ApplyType::getDictLabel)
                            .collect(Collectors.toList()));
                    break;
                case "spzt":
                    showDialog((TextView) view, "选择办理状态", applyBLZT.stream()
                            .map(ApplyType::getDictLabel)
                            .collect(Collectors.toList()));
                    break;
                default:
            }

        });
        binding.tvMineSearchBtn.setOnClickListener(view -> searchData());
        searchData();
    }

    private void searchData() {
        String value = "";
        switch (searchType) {
            case "sy":
                for (ApplyType item : applyTypes) {
                    String str = binding.mineTvInput.getText().toString();
                    if (item.getDictLabel().equals(str)) {
                        value = item.getDictValue();
                        break;
                    }
                }
                break;
            case "ly":
                for (ApplyType item : applyXXLY) {
                    if (item.getDictLabel().equals(binding.mineTvInput.getText().toString())) {
                        value = item.getDictValue();
                        break;
                    }
                }
                break;
            case "spzt":
                for (ApplyType item : applyBLZT) {
                    if (item.getDictLabel().equals(binding.mineTvInput.getText().toString())) {
                        value = item.getDictValue();
                        break;
                    }
                }
                break;
            default:
                value = binding.mineEtInput.getText().toString();
        }
        HashMap<String, String> map = new HashMap<>();
        map.put(searchType, value);
        viewModel.getApplyList(map);
    }

    private String searchType = "fnbh";

    private void setPopupWindow() {
        // 初始化 PopupWindow
        popupWindow = new PopupWindow(getContext());
        // 加载自定义布局
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(R.layout.dropdown_layout5, null);
        // 设置 PopupWindow 的宽高
        popupWindow.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.all_7_fff_bg));
        popupWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        // 设置 PopupWindow 的背景
//        popupWindow.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        // 设置 PopupWindow 显示的位置（相对于按钮）
        popupWindow.showAtLocation(binding.mineTypeGroup, Gravity.NO_GRAVITY, 0, 0);
        // 为每个菜单项设置点击事件
        TextView textView1 = contentView.findViewById(R.id.textView1); // 假设这是菜单项1的ID
        TextView textView2 = contentView.findViewById(R.id.textView2); // 假设这是菜单项2的ID
        TextView textView3 = contentView.findViewById(R.id.textView3); // 假设这是菜单项2的ID
        TextView textView4 = contentView.findViewById(R.id.textView4); // 假设这是菜单项2的ID
        TextView textView5 = contentView.findViewById(R.id.textView5); // 假设这是菜单项2的ID
        textView1.setOnClickListener(v -> {
            // 处理菜单项 1 的点击事件
            binding.tvMineSearchTitle.setText("赋能编号");
            searchType = "fnbh";
            binding.mineTvInput.setVisibility(View.INVISIBLE);
            binding.mineEtInput.setText("");
            binding.mineEtInput.setVisibility(View.VISIBLE);
            popupWindow.dismiss(); // 关闭 PopupWindow
        });
        textView2.setOnClickListener(v -> {
            // 处理菜单项 2 的点击事件
            binding.tvMineSearchTitle.setText("申请事由");
            searchType = "sy";
            binding.mineTvInput.setVisibility(View.VISIBLE);
            binding.mineTvInput.setText("");
            binding.mineEtInput.setVisibility(View.INVISIBLE);
            if (applyTypes == null) {
                viewModel.getApplyType();
            }
            popupWindow.dismiss(); // 关闭 PopupWindow
        });
        textView3.setOnClickListener(v -> {
            // 处理菜单项 2 的点击事件
            binding.tvMineSearchTitle.setText("申请时间");
            searchType = "sqsj";
            binding.mineTvInput.setVisibility(View.INVISIBLE);
            binding.mineEtInput.setText("");
            binding.mineEtInput.setVisibility(View.VISIBLE);
            popupWindow.dismiss(); // 关闭 PopupWindow
        });
        textView4.setOnClickListener(v -> {
            // 处理菜单项 2 的点击事件
            binding.tvMineSearchTitle.setText("信息来源");
            searchType = "ly";
            binding.mineTvInput.setVisibility(View.VISIBLE);
            binding.mineTvInput.setText("");
            binding.mineEtInput.setVisibility(View.INVISIBLE);
            if (applyXXLY == null) {
                viewModel.getMineXXLY();
            }
            popupWindow.dismiss(); // 关闭 PopupWindow
        });
        textView5.setOnClickListener(v -> {
            // 处理菜单项 2 的点击事件
            binding.tvMineSearchTitle.setText("办理状态");
            searchType = "spzt";
            binding.mineTvInput.setVisibility(View.VISIBLE);
            binding.mineTvInput.setText("");
            binding.mineEtInput.setVisibility(View.INVISIBLE);
            if (applyBLZT == null) {
                viewModel.getMineBLZT();
            }
            popupWindow.dismiss(); // 关闭 PopupWindow
        });
        // 将自定义布局设置为 PopupWindow 的内容视图
        popupWindow.setContentView(contentView);
        // 设置 PopupWindow 的焦点
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true); // 设置点击 PopupWindow 外部区域使其消失
    }

    public void applyType(List<ApplyType> list) {
        applyTypes = list;
    }

    public void applyBLZT(List<ApplyType> list) {
        applyBLZT = list;
    }

    public void applyXXLY(List<ApplyType> list) {
        applyXXLY = list;
    }

    public void showDialog(TextView textView, String title, List<String> items) {
        if (getContext() == null) return;
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        DialogSelectorBinding selectorBinding = DialogSelectorBinding.inflate(getLayoutInflater());
        View dialogView = selectorBinding.getRoot();
        selectorBinding.tvDialogTitle.setText(title);
        RecyclerView recyclerView = selectorBinding.rcv;
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        BaseQuickAdapter<String, BaseViewHolder> adapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_dialog_selector, items) {
            @Override
            protected void convert(@NonNull BaseViewHolder baseViewHolder, String s) {
                baseViewHolder.setText(R.id.tv_item_text, s);
            }
        };
        recyclerView.setAdapter(adapter);
        builder.setView(dialogView);
        AlertDialog dialog = builder.create();
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            textView.setText(items.get(position));
            dialog.dismiss();
        });
        dialog.show();
    }

    public void applyList(List<Apply> list) {
        applyList = list;
        adapter.setList(list);
    }

    public void applyDetail(String applyDetail) {
        Intent intent = new Intent(this.getActivity(), ApplyDetailActivity.class);
        intent.putExtra("applyDetail", applyDetail);
        startActivity(intent);
    }

    public void loadingShow() {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> binding.mineRlLoading.setVisibility(View.VISIBLE));
        }
    }

    public void loadingNone() {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> binding.mineRlLoading.setVisibility(View.GONE));
        }
    }
}
