package com.gingersoft.gsa.cloud.ui.adapter;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.common.R2;
import com.gingersoft.gsa.cloud.ui.R;
import com.gingersoft.gsa.cloud.ui.bean.SectionCheckItem;
import com.qmuiteam.qmui.widget.section.QMUIDefaultStickySectionAdapter;
import com.qmuiteam.qmui.widget.section.QMUISection;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionAdapter;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionLayout;

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

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2020-02-09
 * 修订历史：2020-02-09
 * 描述：
 */
public class BaseRadioSectionAdapter extends QMUIDefaultStickySectionAdapter<SectionCheckItem, SectionCheckItem> {

    private Context context;
    public final static String SEPARATOR = ",";
    private String tab = "";

    public BaseRadioSectionAdapter(Context context) {
        this.context = context;
    }

    public BaseRadioSectionAdapter(Context context, int backgroundColor) {
        this.context = context;
        this.backgroundColor = backgroundColor;
    }


    private int backgroundColor = Color.WHITE;
    private onRefreshListener onRefreshListener;

    @NonNull
    @Override
    protected QMUIStickySectionAdapter.ViewHolder onCreateSectionHeaderViewHolder(@NonNull ViewGroup viewGroup) {
        return new HeaderViewHolder(View.inflate(viewGroup.getContext(), R.layout.item_radio_section_header, null));
    }

    @NonNull
    @Override
    protected ViewHolder onCreateSectionItemViewHolder(@NonNull ViewGroup viewGroup) {
        return new ItemViewHolder(View.inflate(viewGroup.getContext(), R.layout.item_radio_section_item, null));
    }

    @Override
    protected void onBindSectionHeader(QMUIStickySectionAdapter.ViewHolder holder, int position, QMUISection<SectionCheckItem, SectionCheckItem> section) {
        super.onBindSectionHeader(holder, position, section);
        HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder;
        headerViewHolder.tvTitle.setText(tab + section.getHeader().getText());
        headerViewHolder.cbSection.setChecked(section.getHeader().isChecked());
        headerViewHolder.cbSection.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (buttonView.isPressed()) {
                if (isChecked) {
                    onCheckedChangeListener.onChange("", isChecked, section.getHeader());
                } else {
                    //當前item取消選中，下面的子類全部設置為取消
                    section.getHeader().setChecked(false);
                    downTraversal(section.getItemList());
                    if (onRefreshListener != null) {
                        onRefreshListener.onRefresh();
                    }
                }
            }
        });
        headerViewHolder.itemView.setBackgroundColor(backgroundColor);
    }

    public void downTraversal(List<SectionCheckItem> itemList) {
        if (itemList != null) {
            for (int i = 0; i < itemList.size(); i++) {
                itemList.get(i).setChecked(false);
                if (itemList.get(i) != null) {
                    downTraversal(itemList.get(i).getSectionCheckItems());
                }
            }
        }
    }

    @Override
    protected void onBindSectionItem(ViewHolder holder, int position, QMUISection<SectionCheckItem, SectionCheckItem> section, int itemIndex) {
        super.onBindSectionItem(holder, position, section, itemIndex);
        ItemViewHolder viewHolder = (ItemViewHolder) holder;
        int itemCount = section.getItemCount();
        if (itemCount > 0) {
            int alpha = Color.alpha(backgroundColor) - 20;
            int red = Color.red(backgroundColor) - 20;
            int green = Color.green(backgroundColor) - 20;
            int blue = Color.blue(backgroundColor) - 20;
            if (alpha < 0 || alpha > 255) {
                alpha = 0;
            }
            if (red < 0 || red > 255) {
                red = 0;
            }
            if (green < 0 || green > 255) {
                green = 0;
            }
            if (blue < 0 || blue > 255) {
                blue = 0;
            }
            BaseRadioSectionAdapter baseRadioSectionAdapter = new BaseRadioSectionAdapter(context, Color.argb(alpha, red, green, blue));
            baseRadioSectionAdapter.setTab(tab + "\u3000");
            List<QMUISection<SectionCheckItem, SectionCheckItem>> sections = new ArrayList<>();
            SectionCheckItem itemHeader = section.getItemAt(itemIndex);
            sections.add(new QMUISection<>(itemHeader, section.getItemAt(itemIndex).getSectionCheckItems(), false));
            baseRadioSectionAdapter.setData(sections);
            viewHolder.sectionLayout.setAdapter(baseRadioSectionAdapter);
            viewHolder.sectionLayout.setLayoutManager(new LinearLayoutManager(context) {
                @Override
                public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                    return new RecyclerView.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                }
            });

            baseRadioSectionAdapter.setOnRefreshListener(onRefreshListener);
            baseRadioSectionAdapter.setCallback(new Callback<SectionCheckItem, SectionCheckItem>() {
                @Override
                public void loadMore(QMUISection<SectionCheckItem, SectionCheckItem> section, boolean loadMoreBefore) {
                    if (callback != null) {
                        callback.loadMore(section, loadMoreBefore);
                    }
                }

                @Override
                public void onItemClick(ViewHolder holder, int position) {
                    if (sections.get(position).getItemCount() > 0) {
                        baseRadioSectionAdapter.toggleFold(position, false);
                    } else {
                        onItemClickListener.onClick(sections.get(position).getHeader().getId(), sections.get(position).getHeader().getSort(), itemIndex + "");
                    }
                }

                @Override
                public boolean onItemLongClick(ViewHolder holder, int position) {
                    if (callback != null) {
                        callback.onItemLongClick(holder, position);
                    }
                    return false;
                }
            });
            baseRadioSectionAdapter.setOnItemClickListener((id, position1, positions) -> {
                onItemClickListener.onClick(id, sections.get(0).getHeader().getSort(), position1 + SEPARATOR + positions);
            });
            baseRadioSectionAdapter.setOnCheckedChangeListener((positions, isChecked, section1) -> {
                if (section1 != null) {
                    onCheckedChangeListener.onChange(sections.get(0).getHeader().getSort() + SEPARATOR + section.getItemList().indexOf(section1), isChecked, null);
                } else {
                    onCheckedChangeListener.onChange(sections.get(0).getHeader().getSort() + SEPARATOR + positions, isChecked, null);
                }
            });
            viewHolder.sectionLayout.setVisibility(View.VISIBLE);
        } else {
            viewHolder.sectionLayout.setVisibility(View.GONE);
        }
    }

    private OnCheckedChangeListener onCheckedChangeListener;

    private OnItemClickListener onItemClickListener;

    public interface OnCheckedChangeListener {
        void onChange(String positions, boolean isChecked, SectionCheckItem section);
    }

    private Callback<SectionCheckItem, SectionCheckItem> callback;

    @Override
    public void setCallback(Callback<SectionCheckItem, SectionCheckItem> callback) {
        super.setCallback(callback);
        this.callback = callback;
    }

    public interface OnItemClickListener {
        /**
         * 遞歸傳遞上來點擊的下標
         *
         * @param id        點擊的item的id
         * @param positions 下標集合
         */
        void onClick(int id, int position, String positions);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
        this.onCheckedChangeListener = onCheckedChangeListener;
    }

    public void setOnRefreshListener(BaseRadioSectionAdapter.onRefreshListener onRefreshListener) {
        this.onRefreshListener = onRefreshListener;
    }

    /**
     * 刷新adapter，複選框選中之後不能刷新adapter，需要判斷recyclerview的狀態進行刷新
     */
    public interface onRefreshListener {
        void onRefresh();
    }

    public void setTab(String tab) {
        this.tab = tab;
    }

    public class HeaderViewHolder extends QMUIStickySectionAdapter.ViewHolder {
//        @BindView(R2.id.tv_radio_section_title)
        TextView tvTitle;//功能名
//        @BindView(R2.id.cb_radio_section)
        CheckBox cbSection;

        public HeaderViewHolder(View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tv_radio_section_title);
            cbSection = itemView.findViewById(R.id.cb_radio_section);
//            ButterKnife.bind(this, itemView);
        }

        public int getSectionCheckItemItem(int position) {
            return getSectionIndex(position);
        }
    }

    public class ItemViewHolder extends QMUIStickySectionAdapter.ViewHolder {
//        @BindView(R2.id.item_radio_section_layout)
        QMUIStickySectionLayout sectionLayout;

        public ItemViewHolder(View itemView) {
            super(itemView);
            sectionLayout = itemView.findViewById(R.id.item_radio_section_layout);
//            ButterKnife.bind(this, itemView);
        }

    }
}
