package com.wisewoods.eduandroid.area;

import android.text.TextUtils;
import android.view.View;

import androidx.fragment.app.FragmentActivity;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.wisewoods.base.bean.AreaBean;
import com.wisewoods.base.net.JCallback;
import com.wisewoods.eduandroid.R;
import com.wisewoods.eduandroid.app.App;
import com.wisewoods.eduandroid.databinding.ViewAreaBinding;

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

import retrofit2.Response;

public class AreaView extends BottomSheetDialog implements TabLayout.OnTabSelectedListener {

    public static final String[] mAraes = new String[]{
            "省级", "市级", "区县级", "街道(镇)级","社区(村)级"
    };

    private ViewAreaBinding binding;
    private List<AreaBean> tabs = new ArrayList<>();
    private final VpAdapter adapter;
    private final TabLayoutMediator tabLayoutMediator;
    private String parentIds;

    @Override
    public void onTabSelected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    public interface ClickListener {
        void click(String code, String area);
    }

    private ClickListener listener;

    public void setListener(ClickListener listener) {
        this.listener = listener;
    }

    public void setData(String parentIds) {
        this.parentIds = parentIds;
        getTabData("", -1);
    }

    public AreaView(FragmentActivity activity) {
        super(activity, R.style.BottomSheetDialog2);
        binding = ViewAreaBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        adapter = new VpAdapter();
        adapter.setListener((layoutPosition, item) -> {
            handleClick(layoutPosition, item, false);
        });
        binding.tl.addOnTabSelectedListener(this);
        binding.vp.setAdapter(adapter);
        binding.vp.setUserInputEnabled(false);
        tabLayoutMediator = new TabLayoutMediator(binding.tl, binding.vp,
                true, (tab, position) -> {
            String title = this.tabs.get(position).msg;
            tab.setText(title);
        });
        tabLayoutMediator.attach();
        binding.tvOk.setOnClickListener(v -> {
            dismiss();
            StringBuffer sb = new StringBuffer();
            StringBuffer code = new StringBuffer();

            for (AreaBean tab : this.tabs) {
                if (!TextUtils.isEmpty(tab.codeStr)){
                    sb.append(tab.msg+'/');
                    code.append(tab.code);
                }
            }

            if (listener != null) {
                listener.click(code.length() > 0 ? sb.substring(0, sb.length() - 1) : "",
                        sb.length() > 0 ? sb.substring(0, sb.length() - 1) : "");
            }
        });
    }

    private void handleClick(int layoutPosition, AreaBean.DataBean item, boolean isCode) {
        if (!isCode && !TextUtils.isEmpty(this.parentIds)) {
            this.parentIds = "";
        }
        this.tabs.get(layoutPosition).msg = item.name;
        this.tabs.get(layoutPosition).codeStr = item.code;
        binding.tl.getTabAt(layoutPosition).setText(item.name);
        if (layoutPosition == 3) {
            binding.flLoading.setVisibility(View.VISIBLE);
            tabs = tabs.subList(0, layoutPosition + 1);
            adapter.setNewInstance(tabs);
            App.api.getUnit(item.id)
                    .enqueue(new JCallback<AreaBean>() {
                        @Override
                        public void onS(Response<AreaBean> response, AreaBean areaBean) {
                            //TODO 这里是为了兼容 单位和普通地区让code变成id
                            for (AreaBean.DataBean datum : areaBean.data) {
                                datum.id = datum.code;
                            }
                            changeTab(areaBean, 3);
                        }

                        @Override
                        public void onFinish() {
                            super.onFinish();
                            binding.flLoading.setVisibility(View.GONE);
                        }
                    });
            return;
        }
        getTabData(item.id, layoutPosition);
    }


    private void getTabData(String parentId, int layoutPosition) {
        binding.flLoading.setVisibility(View.VISIBLE);
        tabs = tabs.subList(0, layoutPosition + 1);
        adapter.setNewInstance(tabs);
        App.api.getLocation(parentId)
                .enqueue(new JCallback<AreaBean>() {

                    @Override
                    public void onS(Response<AreaBean> response, AreaBean areaBean) {
                        changeTab(areaBean, layoutPosition);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        binding.flLoading.setVisibility(View.GONE);
                    }
                });
    }

    private void changeTab(AreaBean areaBean, int layoutPosition) {
        int newP = layoutPosition;
        if (areaBean.data != null && areaBean.data.size() > 0) {
            newP = layoutPosition + 1;
            Collections.reverse(areaBean.data);
            tabs = tabs.subList(0, layoutPosition + 1);
            areaBean.msg = mAraes[layoutPosition + 1];
            tabs.add(areaBean);
            adapter.setNewInstance(tabs);
            if (!TextUtils.isEmpty(parentIds)) {
                restoreData(areaBean, newP);
            }
            binding.tl.selectTab(binding.tl.getTabAt(layoutPosition + 1));
        } else {
            tabs = tabs.subList(0, layoutPosition + 1);
            adapter.setNewInstance(tabs);
        }

    }

    private void restoreData(AreaBean areaBean, int index) {
        if (TextUtils.isEmpty(parentIds)) {
            return;
        }
        String[] areaIdArray = parentIds.split(",");
        if (areaIdArray.length > index) {
            String id = areaIdArray[index];
            for (AreaBean.DataBean datum : areaBean.data) {
                if (datum.id.equals(id)) {
                    datum.isCheck = true;
                    handleClick(index, datum, true);
                    break;
                }
            }
        }
        StringBuffer sb = new StringBuffer();
        for (AreaBean tab : this.tabs) {
            if (!TextUtils.isEmpty(tab.codeStr)) {
                sb.append(tab.msg+"/");
            }
        }
        if (listener != null) {
            listener.click(null, sb.length() > 0 ? sb.substring(0, sb.length() - 1) : "");
        }
    }
}
