package com.unis.sxzcl.widget;

import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.module.LoadMoreModule;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.unis.sxzcl.R;

import org.jetbrains.annotations.NotNull;

/**
 * 包名: com.unis.icon.widget
 * 类名: BottomMultipleAdapter
 * 作用描述:
 * 创建人: mQ
 * 创建时间: 2020/11/13 10:56
 * 更新人:
 * 更新时间: 2020/11/13 10:56
 * 更新说明:
 * 版本号: 1.0
 */
public class BottomMultipleAdapter extends BaseQuickAdapter<MultipleBean, BaseViewHolder> implements LoadMoreModule {

    private int mSelIndex = -1;

    private Callback mCallback;

    public BottomMultipleAdapter(Callback callback) {
        super(R.layout.item_bottom_multiple);
        mCallback = callback;
    }

    @Override
    protected void convert(@NotNull final BaseViewHolder holder, final MultipleBean bean) {
        final int position = getItemPosition(bean);

        //设置标题
        holder.setText(R.id.tv_name, bean.getName());
        //根据选中状态设置文字颜色
        holder.setTextColorRes(R.id.tv_name, position == mSelIndex ?
                R.color.colorWhite : R.color.colorTextBlack);
        //根据选中状态设置背景颜色
        holder.itemView.setBackgroundResource(position == mSelIndex ?
                R.color.colorTheme : R.color.colorWhite);

        //监听点击事件
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setSelIndex(position);
                //回调所选值
                if (mCallback != null)
                    mCallback.onItemClick(bean);
            }
        });
    }

    /**
     * 设置选中项
     *
     * @param index
     */
    public void setSelIndex(int index) {
        //获得之前选中项
        int oldIndex = mSelIndex;
        //设定当前选中项
        mSelIndex = index;

        // oldIndex未越界时 刷新之前选中的项
        if (oldIndex >= 0 && oldIndex <= getData().size() - 1)
            notifyItemChanged(oldIndex);
        // index未越界时 刷新选中项
        if (mSelIndex >= 0 && mSelIndex <= getData().size() - 1)
            notifyItemChanged(mSelIndex);
    }

    public int getSelIndex() {
        return mSelIndex;
    }

    /**
     * 获取已选中值
     *
     * @return
     */
    public MultipleBean getSelBean() {
        if (mSelIndex >= 0)
            return getData().get(mSelIndex);
        else
            return null;
    }

    public interface Callback {
        void onItemClick(MultipleBean bean);
    }
}