package com.police.policedatasystem.apply.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
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.ApplyDept;
import com.police.policedatasystem.apply.model.ApplyPerson;
import com.police.policedatasystem.apply.viewmodel.ApplyPostViewModel;
import com.police.policedatasystem.databinding.ActivityApplyBinding;
import com.police.policedatasystem.databinding.DialogDeptSelectorBinding;
import com.police.policedatasystem.databinding.DialogSelectorBinding;
import com.police.policedatasystem.http.RequestClient;
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 ApplyActivity extends AppCompatActivity {

    private ApplyPostViewModel viewModel;
    public List<ApplyDept> applyDept;
    public List<ApplyPerson> applyPeople;
    public RequestClient requestClient;

    private com.police.policedatasystem.databinding.ActivityApplyBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityApplyBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        requestClient = RequestClient.instance();
        binding.ivBack.setOnClickListener(view -> finish());
        initView();
    }

    private void initView() {
        viewModel = new ApplyPostViewModel(this);
        binding.includeApply.tvCommitBtn.setOnClickListener(view -> addApply());
        binding.rlLoading.setOnClickListener(view -> {
        });
        binding.includeApply.tvQueryOrg.setOnClickListener(view -> showDeptDialog((TextView) view, "选择部门", applyDept));
        binding.includeApply.tvQueryName.setOnClickListener(view -> showPerson(applyPeople));
        viewModel.getApplyDept();
        binding.includeApply.tvQueryOrg.setOnClickListener(view -> showDept(applyDept));
        binding.includeApply.etSearchTitle.setText(getIntent().getStringExtra("jqbh"));
//        binding.includeApply.tvQueryName2.setOnClickListener(view -> {
//            //打开相册选择一张图片
//            openAlbum();
//        });
    }


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

    @Override
    protected 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, data.getData());
//            binding.includeApply.tvQueryName2.setText(data.getData().toString());
        }
    }

    private String nrFj = "";

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

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

    public void showDialog(TextView textView, String title, List<String> items) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        DialogSelectorBinding selectorBinding = DialogSelectorBinding.inflate(getLayoutInflater());
        View dialogView = selectorBinding.getRoot();
        selectorBinding.tvDialogTitle.setText(title);
        RecyclerView recyclerView = selectorBinding.rcv;
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        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) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.TransparentAlertDialog);
        DialogDeptSelectorBinding selectorBinding = DialogDeptSelectorBinding.inflate(getLayoutInflater());
        View dialogView = selectorBinding.getRoot();
        selectorBinding.tvDialogTitle.setText(title);
        RecyclerView recyclerView = selectorBinding.rcv;
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        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(this, "请选择一个归属部门", 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));
            }
        }
    }

    /**
     * 发送成功，跳转到成功页面
     */
    public void sendSuccess() {
        Toast.makeText(this, "提交成功！", Toast.LENGTH_SHORT).show();
        finish();
    }

    /**
     * 取消勾选
     */
    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);
    }

    /**
     * 提交
     */
    private void addApply() {
        HashMap<String, String> params = new HashMap<>();
        params.put("jqbh", binding.includeApply.etSearchTitle.getText().toString());
        params.put("sy", "7");
        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);
    }

    public void loadingShow() {
        binding.rlLoading.setVisibility(View.VISIBLE);
    }

    public void loadingNone() {
        binding.rlLoading.setVisibility(View.GONE);
    }
}