package com.police.policedatasystem.fragment;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
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.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.police.policedatasystem.R;
import com.police.policedatasystem.data.adapter.KeyPersonAdapter;
import com.police.policedatasystem.data.adapter.PoliceEmergencyAdapter;
import com.police.policedatasystem.databinding.FragmentDataBinding;
import com.police.policedatasystem.indexActivity;
import com.police.policedatasystem.model.KeyPerson;
import com.police.policedatasystem.model.PoliceEmergency;
import com.police.policedatasystem.viewmodel.DataViewModel;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;

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

public class DataFragment extends Fragment {
    public FragmentDataBinding binding;
    private DataViewModel viewModel;
    private PopupWindow popupWindow;
    private PopupWindow popupWindow2;
    private PopupWindow popupWindow3;
    public final List<KeyPerson> personList = new ArrayList<>();
    public final List<PoliceEmergency> policeList = new ArrayList<>();
    public BaseQuickAdapter adapter;
    private int currentTabBar = 1;
    private int currentTab = 1;
    public int filterType = 0;
    indexActivity act;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentDataBinding.inflate(inflater);
        initView();
        Activity activity = getActivity();
        if (activity instanceof indexActivity) {
            act = (indexActivity) activity;
        }
        viewModel = new DataViewModel(this, act);
        initListener();
        return binding.getRoot();
    }

    private void initView() {
        binding.refreshLayout.setRefreshHeader(new ClassicsHeader(getContext()));
        binding.refreshLayout.setRefreshFooter(new ClassicsFooter(getContext()));
        binding.rvGroup.setLayoutManager(new LinearLayoutManager(getContext()));
        keyPersonInitAdapter();
        setPopupWindow();
        setPopupWindow2();
        setPopupWindow3();
    }

    public void initData() {
        viewModel.keyPersonInit();
        viewModel.getKeyPersonMessageCount();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!act.findAddress) {
            act.requestClient.init();
        } else {
            initData();
        }
    }

    private void initListener() {
        //重点人，案情，案件，点击事件
        binding.llKeyPerson.setOnClickListener(view -> tabBarOnClick(1));
        binding.llPoliceEmergency.setOnClickListener(view -> tabBarOnClick(2));
        binding.llCaseDetails.setOnClickListener(view -> tabBarOnClick(3));
        //搜索按钮添加点击事件
        binding.tvSearchBtn.setOnClickListener(view -> {
            if (!act.findAddress) return;
            if (currentTabBar == 1) {
                if (currentTab == 1) {
                    viewModel.keyPersonInit();
                } else {
                    viewModel.orgKeyPersonInit();
                }
            } else if (currentTabBar == 2) {
                viewModel.policeEmergencyInit();
            }
        });
        //我的重点人与区域重点人tab点击切换事件
        binding.llMyKeyPerson.setOnClickListener(view -> tabOnClick(1));
        binding.llAreaKeyPerson.setOnClickListener(view -> tabOnClick(2));
        //loading视图设置空的点击事件
        binding.rlLoading.setOnClickListener(view -> {
        });
        //筛选文字下拉菜单按钮点击事件
        binding.typeGroup.setOnClickListener(view -> {
            if (!act.findAddress) return;
            if (currentTabBar == 1) {
                popupWindow.showAsDropDown(binding.typeGroup);
            } else if (currentTabBar == 2) {
                popupWindow2.showAsDropDown(binding.typeGroup);
            } else {
                popupWindow3.showAsDropDown(binding.typeGroup);
            }

        });
        //重点人列表条目点击事件
        adapter.setOnItemClickListener((adapter1, view, position) -> viewModel.keyPersonDetail(personList.get(position).getSfzh()));
        //刷新列表
        binding.refreshLayout.setOnRefreshListener(refreshlayout -> {
            if (currentTabBar == 1) {
                if (currentTab == 1) {
                    viewModel.keyPersonRefresh();
                } else {
                    viewModel.orgKeyPersonRefresh();
                }
                return;
            }
            if (currentTabBar == 2) {
                viewModel.policeEmergencyRefresh();
                return;
            }
            if (currentTabBar == 3) {
                if (currentTab == 1) {
                    viewModel.keyPersonRefresh();
                } else {
                    viewModel.orgKeyPersonRefresh();
                }
            }
        });
        //加载更多
        binding.refreshLayout.setOnLoadMoreListener(refreshlayout -> {
            if (currentTabBar == 1) {
                if (currentTab == 1) {
                    viewModel.keyPersonLoadMore();
                } else {
                    viewModel.orgKeyPersonLoadMore();
                }
                return;
            }
            if (currentTabBar == 2) {
                viewModel.policeEmergencyLoadMore();
            }
        });
    }

    private void keyPersonInitAdapter() {
        adapter = new KeyPersonAdapter();
        adapter.setNewInstance(personList);
        binding.rvGroup.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter1, view, position) -> viewModel.keyPersonDetail(personList.get(position).getSfzh()));
    }

    private void policeEmergencyInitAdapter() {
        adapter = new PoliceEmergencyAdapter();
        adapter.setNewInstance(policeList);
        binding.rvGroup.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter1, view, position) -> viewModel.policeEmergencyDetail(policeList.get(position).getJcjbh()));
    }

    /**
     * tab按钮点击切换
     *
     * @param i
     */
    private void tabOnClick(int i) {
        //如果点击tab与当前的一致，当前点击事件无效.
        if (currentTab == i) return;
        currentTab = i;
        //清空搜索框内容
        binding.etInput.setText("");
        //切换效果设置
        binding.tvAreaKeyPerson.setTextColor(getResources().getColor(R.color.color_666));
        binding.selectAreaKeyPerson.setBackgroundColor(getResources().getColor(R.color.transparent_color));
        binding.tvMyKeyPerson.setTextColor(getResources().getColor(R.color.color_666));
        binding.selectMyKeyPerson.setBackgroundColor(getResources().getColor(R.color.transparent_color));
        if (i == 1) {
            binding.tvMyKeyPerson.setTextColor(getResources().getColor(R.color.selected_color));
            binding.selectMyKeyPerson.setBackgroundColor(getResources().getColor(R.color.selected_color));
        } else {
            binding.tvAreaKeyPerson.setTextColor(getResources().getColor(R.color.selected_color));
            binding.selectAreaKeyPerson.setBackgroundColor(getResources().getColor(R.color.selected_color));
        }
        if (currentTabBar == 1) {
            if (currentTab == 1) {
                //加载我的重点人
                viewModel.keyPersonInit();
            } else {
                viewModel.orgKeyPersonInit();
            }
        }
    }

    /**
     * 顶部tabBar切换
     *
     * @param i
     */
    private void tabBarOnClick(int i) {
        if (currentTabBar == i) return;
        currentTabBar = i;
        binding.etInput.setText("");
        binding.iconKeyPerson.setBackgroundResource(R.drawable.mine_icon);
        binding.tvKeyPerson.setTextColor(getResources().getColor(R.color.black));
        binding.selectKeyPerson.setBackgroundColor(getResources().getColor(R.color.white));
        binding.iconPoliceEmergency.setBackgroundResource(R.drawable.huizhang_icon);
        binding.tvPoliceEmergency.setTextColor(getResources().getColor(R.color.black));
        binding.selectPoliceEmergency.setBackgroundColor(getResources().getColor(R.color.white));
        binding.iconCaseDetails.setBackgroundResource(R.drawable.wenjianjia_icon);
        binding.tvCaseDetails.setTextColor(getResources().getColor(R.color.black));
        binding.selectCaseDetails.setBackgroundColor(getResources().getColor(R.color.white));
        filterType = 0;
        switch (i) {
            case 1:
                binding.iconKeyPerson.setBackgroundResource(R.drawable.mine_normal);
                binding.tvKeyPerson.setTextColor(getResources().getColor(R.color.selected_color));
                binding.selectKeyPerson.setBackgroundColor(getResources().getColor(R.color.selected_color));
                binding.tvSearchTitle.setText("姓名");
                keyPersonInitAdapter();
                if (currentTab == 1) {
                    viewModel.keyPersonInit();
                } else {
                    viewModel.orgKeyPersonInit();
                }
                binding.tvMyKeyPerson.setText("我的重点人");
                binding.tvAreaKeyPerson.setText("辖区(警种)重点人");
                binding.tabGroup.setVisibility(View.VISIBLE);
                break;
            case 2:
                binding.iconPoliceEmergency.setBackgroundResource(R.drawable.huizhang);
                binding.tvPoliceEmergency.setTextColor(getResources().getColor(R.color.selected_color));
                binding.selectPoliceEmergency.setBackgroundColor(getResources().getColor(R.color.selected_color));
                binding.tvSearchTitle.setText("警情编号");
                policeEmergencyInitAdapter();
                viewModel.policeEmergencyInit();
                binding.tabGroup.setVisibility(View.GONE);
                break;
            default:
                binding.iconCaseDetails.setBackgroundResource(R.drawable.wenjianjia);
                binding.tvCaseDetails.setTextColor(getResources().getColor(R.color.selected_color));
                binding.selectCaseDetails.setBackgroundColor(getResources().getColor(R.color.selected_color));
                binding.tvSearchTitle.setText("案件编号");
                binding.tvMyKeyPerson.setText("在办案件");
                binding.tvAreaKeyPerson.setText("历史案件");
                binding.tabGroup.setVisibility(View.GONE);
                loadCase(new ArrayList<>());
        }

    }

    /**
     * 加载案情布局
     */
    public void loadCase(List<KeyPerson> data) {
        KeyPersonAdapter adapter = new KeyPersonAdapter();
        adapter.setNewInstance(data);
        binding.rvGroup.setLayoutManager(new LinearLayoutManager(getContext()));
        binding.rvGroup.setAdapter(adapter);
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            viewModel.keyPersonDetail(data.get(position).getSfzh());
        });
    }

    public void loadingShow() {
        getActivity().runOnUiThread(() -> binding.rlLoading.setVisibility(View.VISIBLE));

    }

    public void loadingNone() {
        getActivity().runOnUiThread(() -> binding.rlLoading.setVisibility(View.GONE));
    }

    private void setPopupWindow() {
        // 初始化 PopupWindow
        popupWindow = new PopupWindow(getContext());
        // 加载自定义布局
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(R.layout.dropdown_layout, null);
        // 设置 PopupWindow 的宽高
        popupWindow.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        // 设置 PopupWindow 的背景
        popupWindow.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        // 设置 PopupWindow 显示的位置（相对于按钮）
        popupWindow.showAtLocation(binding.typeGroup, Gravity.NO_GRAVITY, 0, 0);
        // 为每个菜单项设置点击事件
        TextView textView1 = contentView.findViewById(R.id.textView1); // 假设这是菜单项1的ID
        TextView textView2 = contentView.findViewById(R.id.textView2); // 假设这是菜单项2的ID
        textView1.setOnClickListener(v -> {
            // 处理菜单项 1 的点击事件
            binding.tvSearchTitle.setText("姓名");
            filterType = 0;
            popupWindow.dismiss(); // 关闭 PopupWindow
        });
        textView2.setOnClickListener(v -> {
            // 处理菜单项 2 的点击事件
            binding.tvSearchTitle.setText("身份证号");
            filterType = 1;
            popupWindow.dismiss(); // 关闭 PopupWindow
        });
        // 将自定义布局设置为 PopupWindow 的内容视图
        popupWindow.setContentView(contentView);
        // 设置 PopupWindow 的焦点
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true); // 设置点击 PopupWindow 外部区域使其消失
    }

    private void setPopupWindow2() {
        // 初始化 PopupWindow
        popupWindow2 = new PopupWindow(getContext());
        // 加载自定义布局
        LayoutInflater inflater2 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView2 = inflater2.inflate(R.layout.dropdown_layout2, null);
        // 设置 PopupWindow 的宽高
        popupWindow2.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow2.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        // 设置 PopupWindow 的背景
        popupWindow2.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        // 设置 PopupWindow 显示的位置（相对于按钮）
        popupWindow2.showAtLocation(binding.typeGroup, Gravity.NO_GRAVITY, 0, 0);
        // 为每个菜单项设置点击事件
        TextView textView3 = contentView2.findViewById(R.id.textView3); // 假设这是菜单项1的ID
        TextView textView4 = contentView2.findViewById(R.id.textView4); // 假设这是菜单项2的ID
        TextView textView5 = contentView2.findViewById(R.id.textView5); // 假设这是菜单项2的ID
        textView3.setOnClickListener(v -> {
            // 处理菜单项 1 的点击事件
            binding.tvSearchTitle.setText("警情编号");
            filterType = 0;
            popupWindow2.dismiss(); // 关闭 PopupWindow
        });
        textView4.setOnClickListener(v -> {
            // 处理菜单项 2 的点击事件
            binding.tvSearchTitle.setText("报警内容");
            filterType = 1;
            popupWindow2.dismiss(); // 关闭 PopupWindow
        });
        textView5.setOnClickListener(v -> {
            // 处理菜单项 2 的点击事件
            binding.tvSearchTitle.setText("报警电话");
            filterType = 2;
            popupWindow2.dismiss(); // 关闭 PopupWindow
        });
        // 将自定义布局设置为 PopupWindow 的内容视图
        popupWindow2.setContentView(contentView2);
        // 设置 PopupWindow 的焦点
        popupWindow2.setFocusable(true);
        popupWindow2.setOutsideTouchable(true); // 设置点击 PopupWindow 外部区域使其消失
    }

    private void setPopupWindow3() {
        // 初始化 PopupWindow
        popupWindow3 = new PopupWindow(getContext());
        // 加载自定义布局
        LayoutInflater inflater2 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView2 = inflater2.inflate(R.layout.dropdown_layout3, null);
        // 设置 PopupWindow 的宽高
        popupWindow3.setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow3.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        // 设置 PopupWindow 的背景
        popupWindow3.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        // 设置 PopupWindow 显示的位置（相对于按钮）
        popupWindow3.showAtLocation(binding.typeGroup, Gravity.NO_GRAVITY, 0, 0);
        // 为每个菜单项设置点击事件
        TextView textView6 = contentView2.findViewById(R.id.textView6); // 假设这是菜单项1的ID
        TextView textView7 = contentView2.findViewById(R.id.textView7); // 假设这是菜单项2的ID
        TextView textView8 = contentView2.findViewById(R.id.textView8); // 假设这是菜单项2的ID
        TextView textView9 = contentView2.findViewById(R.id.textView9); // 假设这是菜单项2的ID
        textView6.setOnClickListener(v -> {
            // 处理菜单项 1 的点击事件
            binding.tvSearchTitle.setText("案件编号");
            filterType = 0;
            popupWindow3.dismiss(); // 关闭 PopupWindow
        });
        textView7.setOnClickListener(v -> {
            // 处理菜单项 2 的点击事件
            binding.tvSearchTitle.setText("案件名称");
            filterType = 1;
            popupWindow3.dismiss(); // 关闭 PopupWindow
        });
        textView8.setOnClickListener(v -> {
            // 处理菜单项 2 的点击事件
            binding.tvSearchTitle.setText("嫌疑人姓名");
            filterType = 3;
            popupWindow3.dismiss(); // 关闭 PopupWindow
        });
        textView9.setOnClickListener(v -> {
            // 处理菜单项 2 的点击事件
            binding.tvSearchTitle.setText("受害人姓名");
            filterType = 4;
            popupWindow3.dismiss(); // 关闭 PopupWindow
        });
        // 将自定义布局设置为 PopupWindow 的内容视图
        popupWindow3.setContentView(contentView2);
        // 设置 PopupWindow 的焦点
        popupWindow3.setFocusable(true);
        popupWindow3.setOutsideTouchable(true); // 设置点击 PopupWindow 外部区域使其消失
    }
}
