package com.police.policedatasystem.apply.fragment;

import static android.app.Activity.RESULT_OK;

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 android.widget.Toast;

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.activity.SuccessActivity;
import com.police.policedatasystem.apply.model.ApplyDept;
import com.police.policedatasystem.apply.model.ApplyPerson;
import com.police.policedatasystem.apply.model.ApplyType;
import com.police.policedatasystem.apply.viewmodel.ApplyViewModel;
import com.police.policedatasystem.databinding.DialogDeptSelectorBinding;
import com.police.policedatasystem.databinding.DialogSelectorBinding;
import com.police.policedatasystem.databinding.DropdownLayout4Binding;
import com.police.policedatasystem.databinding.FragmentApplyBinding;
import com.police.policedatasystem.indexActivity;
import com.police.policedatasystem.util.UiUtils;

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

public class ApplyFragment extends Fragment {
    private FragmentApplyBinding binding;
    private ApplyViewModel viewModel;
    public List<ApplyType> applyTypes;
    public List<ApplyDept> applyDept;
    public List<ApplyPerson> applyPeople;
    public List<ApplyType> applyXXLY;
    public List<ApplyType> applyJWLX;
    private String dictValue;

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

    private void initView() {
        viewModel = new ApplyViewModel(this, (indexActivity) this.getActivity());
        binding.includeApply.tvCommitBtn.setOnClickListener(view -> addApply());
        binding.rlLoading.setOnClickListener(view -> {
        });
        viewModel.getApplyType();
        viewModel.getApplyDept();
        viewModel.getApplyXXLY();
        viewModel.getApplyJWLX();
        binding.includeApply.tvQueryOrg.setOnClickListener(view -> showDept(applyDept));
//        binding.includeApply.tvQueryName2.setOnClickListener(view -> {
//            //打开相册选择一张图片
//            openAlbum();
//        });
    }

    /**
     * 设置申请事由下拉框
     *
     * @param applyTypes 申请事由集合
     */
    public void setPopupWindow(List<ApplyType> applyTypes) {//布局，include，自定义view，service服务，启动方式
        if (applyTypes.isEmpty()) {
            Toast.makeText(this.getContext(), "用户未在大数据实战赋能系统登记，无法进行赋能", Toast.LENGTH_SHORT).show();
            return;
        }
        // 初始化 PopupWindow
        PopupWindow popupWindow = new PopupWindow(getContext());
        // 加载自定义布局
        DropdownLayout4Binding contentViewBinding = DropdownLayout4Binding.inflate(getLayoutInflater());
        View contentView = contentViewBinding.getRoot();
        // 设置 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.showAtLocation(binding.typeGroup, Gravity.NO_GRAVITY, 0, 0);
        this.applyTypes = applyTypes;
        binding.tvApplySearchTitle.setText(applyTypes.get(0).getDictLabel());
        this.dictValue = applyTypes.get(0).getDictValue();
        for (ApplyType item : applyTypes) {
            TextView textView = new TextView(getContext());
            textView.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            textView.setHeight(UiUtils.dp2Px(40));
            textView.setGravity(Gravity.CENTER_VERTICAL);
            textView.setTextSize(16);
            textView.setBackgroundResource(R.color.white);
            textView.setText(item.getDictLabel());
            contentViewBinding.llApplyTypeGroup.addView(textView);
            textView.setOnClickListener(view -> {
                // 处理菜单项 1 的点击事件
                binding.tvApplySearchTitle.setText(item.getDictLabel());
                changeView(item.getDictValue());
                popupWindow.dismiss(); // 关闭 PopupWindow
            });
        }
        // 将自定义布局设置为 PopupWindow 的内容视图
        popupWindow.setContentView(contentView);
        // 设置 PopupWindow 的焦点
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true); // 设置点击 PopupWindow 外部区域使其消失
        binding.typeGroup.setOnClickListener(view -> {
            popupWindow.setWidth(binding.typeGroup.getWidth());
            popupWindow.showAsDropDown(binding.typeGroup);
        });
        binding.includeApply.tvQueryOrg.setOnClickListener(view -> showDeptDialog((TextView) view, "选择部门", applyDept));
        binding.includeApply.tvQueryName.setOnClickListener(view -> showPerson(applyPeople));
        binding.includeApply.tvSearchTitle.setOnClickListener(view -> {
            if ("2".equals(dictValue)) {
                showXXLY(applyXXLY);
            }
            if ("3".equals(dictValue)) {
                showJWLX(applyJWLX);
            }
        });
    }

    /**
     * 根据申请事由，改变输入选项title
     *
     * @param dictValue 申请事由类型
     */
    private void changeView(String dictValue) {
        this.dictValue = dictValue;
        binding.includeApply.etSearchTitle.setText("");
        binding.includeApply.tvSearchTitle.setText("");
        switch (dictValue) {
            case "0":
                binding.includeApply.etSearchTitle.setVisibility(View.VISIBLE);
                binding.includeApply.tvSearchTitle.setVisibility(View.INVISIBLE);
                binding.includeApply.tvMyKeyPerson.setText("警情编号:");
                break;
            case "1":
            case "6":
                binding.includeApply.etSearchTitle.setVisibility(View.VISIBLE);
                binding.includeApply.tvSearchTitle.setVisibility(View.INVISIBLE);
                binding.includeApply.tvMyKeyPerson.setText("身份证号码:");
                break;
            case "2":
                binding.includeApply.etSearchTitle.setVisibility(View.INVISIBLE);
                binding.includeApply.tvSearchTitle.setVisibility(View.VISIBLE);
                binding.includeApply.tvMyKeyPerson.setText("线索来源:");
                break;
            case "3":
                binding.includeApply.etSearchTitle.setVisibility(View.INVISIBLE);
                binding.includeApply.tvSearchTitle.setVisibility(View.VISIBLE);
                binding.includeApply.tvMyKeyPerson.setText("警务类型:");
                break;
            case "5":
                binding.includeApply.etSearchTitle.setVisibility(View.VISIBLE);
                binding.includeApply.tvSearchTitle.setVisibility(View.INVISIBLE);
                binding.includeApply.tvMyKeyPerson.setText("事由详情:");
                break;
            case "7":
                binding.includeApply.etSearchTitle.setVisibility(View.VISIBLE);
                binding.includeApply.tvSearchTitle.setVisibility(View.INVISIBLE);
                binding.includeApply.tvMyKeyPerson.setText("案件编号:");
                break;
            default:
        }
    }

    public void showDept(List<ApplyDept> applyDept) {
        if (applyDept == null || applyDept.isEmpty()) return;
        showDeptDialog(binding.includeApply.tvQueryOrg, "选择归属部门", applyDept);
    }

    public void showPerson(List<ApplyPerson> applyPeople) {
        if (applyPeople == null || applyPeople.isEmpty()) {
            return;
        }
        List<String> names = applyPeople.stream().map(ApplyPerson::getUserName).collect(Collectors.toList());
        showDialog(binding.includeApply.tvQueryName, "选择审批人", names);
    }

    public void showXXLY(List<ApplyType> applyPeople) {
        if (applyPeople == null || applyPeople.isEmpty()) return;
        List<String> names = applyPeople.stream().map(ApplyType::getDictLabel).collect(Collectors.toList());
        showDialog(binding.includeApply.tvSearchTitle, "选择消息来源", names);
    }

    public void showJWLX(List<ApplyType> applyPeople) {
        if (applyPeople == null || applyPeople.isEmpty()) return;
        List<String> names = applyPeople.stream().map(ApplyType::getDictLabel).collect(Collectors.toList());
        showDialog(binding.includeApply.tvSearchTitle, "选择警务类型", names);
    }

    /**
     * 提交
     */
    private void addApply() {
        if (applyTypes == null) {
            Toast.makeText(this.getContext(), "用户未在大数据实战赋能系统登记，无法进行赋能", Toast.LENGTH_SHORT).show();
            return;
        }
        HashMap<String, String> params = new HashMap<>();
        for (ApplyType item : applyTypes) {
            if (item.getDictLabel().equals(binding.tvApplySearchTitle.getText().toString())) {
                dictValue = item.getDictValue();
                break;
            }
        }
        if (dictValue == null) {
            return;
        }
        switch (dictValue) {
            case "0":
            case "1":
            case "5":
            case "7":
                params.put("jqbh", binding.includeApply.etSearchTitle.getText().toString());
                break;
            case "2":
                params.put("xsly", binding.includeApply.tvSearchTitle.getText().toString());
                break;
            case "3":
                params.put("jwlx", binding.includeApply.tvSearchTitle.getText().toString());
                break;
            case "6":
                params.put("syBz", binding.includeApply.etSearchTitle.getText().toString());
                break;
            default:
                return;
        }
        params.put("sy", dictValue);
        params.put("sqnr", binding.includeApply.etQueryBody.getText().toString());
//        params.put("nrFj", nrFj);
        params.put("shrName", binding.includeApply.tvQueryName.getText().toString());
        for (ApplyPerson item : applyPeople) {
            if (item.getUserName().equals(binding.includeApply.tvQueryName.getText().toString())) {
                params.put("shrSfhm", item.getLoginName());
                break;
            }
        }
        viewModel.addApply(params);
    }

//    private String nrFj = "";

    /**
     * 发送成功，跳转到成功页面
     */
    public void sendSuccess() {
        if (getActivity() == null) return;
        getActivity().startActivity(new Intent(getActivity(), SuccessActivity.class));
    }

    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, 250);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //相册
        if (requestCode == 250 && resultCode == RESULT_OK && data != null) {
//            nrFj = UiUtils.uriToBase64(this.getContext(), data.getData());
//            binding.includeApply.tvQueryName2.setText(data.getData().toString());
        }
    }

    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 showDeptDialog(TextView textView, String title, List<ApplyDept> items) {
        if (getContext() == null) return;
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.TransparentAlertDialog);
        DialogDeptSelectorBinding selectorBinding = DialogDeptSelectorBinding.inflate(getLayoutInflater());
        View dialogView = selectorBinding.getRoot();
        selectorBinding.tvDialogTitle.setText(title);
        RecyclerView recyclerView = selectorBinding.rcv;
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        List<ApplyDept> data = new ArrayList<>();
        for (ApplyDept item : items) {
            if ("0".equals(item.getpId())) {
                data.add(item);
                break;
            }
        }
        BaseQuickAdapter<ApplyDept, BaseViewHolder> adapter = new BaseQuickAdapter<ApplyDept, BaseViewHolder>(R.layout.item_select_dept, data) {
            @Override
            protected void convert(@NonNull BaseViewHolder baseViewHolder, ApplyDept s) {
                baseViewHolder.setText(R.id.tv_title, s.getName());
                boolean hasChild = false;
                for (ApplyDept item : items) {
                    if (s.getId().equals(item.getpId())) {
                        hasChild = true;
                        break;
                    }
                }
                baseViewHolder.setVisible(R.id.iv_sanjiao, hasChild);
                if (s.isOpen()) {
                    baseViewHolder.setImageResource(R.id.iv_sanjiao, R.mipmap.icon_down_sanjiao);
                    baseViewHolder.setImageResource(R.id.iv_box, R.mipmap.icon_selected);
                    baseViewHolder.setTextColor(R.id.tv_title, getResources().getColor(R.color.main_color));
                    baseViewHolder.setBackgroundColor(R.id.tv_title, getResources().getColor(R.color.selected_bg_color));
                } else {
                    baseViewHolder.setImageResource(R.id.iv_sanjiao, R.mipmap.icon_right_sanjiao);
                    baseViewHolder.setImageResource(R.id.iv_box, R.mipmap.icon_unselected);
                    baseViewHolder.setTextColor(R.id.tv_title, getResources().getColor(R.color.color_666));
                    baseViewHolder.setBackgroundColor(R.id.tv_title, getResources().getColor(R.color.white));
                }
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < s.getLevel(); i++) {
                    sb.append("   ");
                }
                baseViewHolder.setText(R.id.v_level, sb);
            }
        };
        recyclerView.setAdapter(adapter);
        builder.setView(dialogView);
        AlertDialog dialog = builder.create();
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            ApplyDept dept = data.get(position);
            boolean open = dept.isOpen();
            int addCount = 1;
            for (ApplyDept item : items) {
                if (item.getpId().equals(dept.getId())) {
                    if (open) {
                        removeItem(data, item);
                    } else {
                        item.setLevel(dept.getLevel() + 1);
                        data.add(position + addCount, item);
                        addCount += 1;
                    }
                }
            }
            if (open) {
                cancelSelected(dept);
            } else {
                enterSelected(data, dept);
            }
            adapter.setList(data);
            selectorBinding.tvEnter.setOnClickListener(view1 -> {
                long selectId = -1;
                ApplyDept selectDept = null;
                for (ApplyDept item : applyDept) {
                    if (item.isOpen()) {
                        item.setOpen(false);
                        if (selectId < Long.parseLong(item.getId())) {
                            selectId = Long.parseLong(item.getId());
                            selectDept = item;
                        }
                    }
                }
                if (selectId >= 0) {
                    textView.setText(selectDept.getTitle());
                    viewModel.getApplyPerson(selectId + "");
                    dialog.dismiss();
                } else {
                    Toast.makeText(getContext(), "请选择一个归属部门", Toast.LENGTH_SHORT).show();
                }

            });
        });
        dialog.show();
    }

    private void removeItem(List<ApplyDept> data, ApplyDept dept) {
        data.remove(dept);
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getpId().equals(dept.getId())) {
                removeItem(data, data.get(i));
            }
        }
    }

    /**
     * 取消勾选
     */
    private void cancelSelected(ApplyDept dept) {
        dept.setOpen(false);
        for (ApplyDept item : applyDept) {
            if (item.getpId().equals(dept.getId())) {
                cancelSelected(item);
            }
        }
    }

    /**
     * 选择勾选
     */
    private void enterSelected(List<ApplyDept> data, ApplyDept dept) {
        for (ApplyDept item : applyDept) {
            if (item.getpId().equals(dept.getpId()) && !item.equals(dept)) {
                cancelSelected(item);
                for (ApplyDept i : applyDept) {
                    if (i.getpId().equals(item.getId())) {
                        removeItem(data, i);
                    }
                }
            }
        }
        dept.setOpen(true);
    }

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

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