package com.sybotan.android.demo.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.TextView;


import java.util.List;

/**
 * function="基于Recycleview的万能适配器"
 * Created by wangmaobo on 2018/4/3.
 */
public abstract class BaseRecyclerViewAdapter<T>
        extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    protected List<T> mBeans;
    protected Context mContext;
    private int mLastAnimatedPosition = -1;
    public OnItemClickListener mOnItemClickListener;
    protected LayoutInflater inflater;
    /*
     * 是否开启item动画
     */
    private boolean mAnimateItems = false;
    private int viewType;
    private boolean mIsFirst = true;
    public ViewGroup parent;

    public BaseRecyclerViewAdapter(Context context, List<T> beans) {
        mContext = context;
        mBeans = beans;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        this.viewType = viewType;
        this.parent = parent;
        inflater = LayoutInflater.from(mContext);
        View view = inflater.inflate(getItemLayoutId(viewType), parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        itemAnimation(holder.itemView, position);
        ViewHolder viewHolder = (ViewHolder) holder;
        onBindDataToView(viewHolder, mBeans.get(position));
    }

    @Override
    public int getItemCount() {
        return mBeans == null ? 0 : mBeans.size();
    }

    public void add(T bean) {
        mBeans.add(bean);
        notifyDataSetChanged();
    }

    public void addAll(List<T> beans) {
        mBeans.addAll(beans);
        notifyDataSetChanged();
    }

    public void clear() {
        mBeans.clear();
        notifyDataSetChanged();
    }

    /**
     * item动画
     */
    private void itemAnimation(View itemView, int position) {
        if (!mAnimateItems) return;
        if (position > mLastAnimatedPosition) {
            mLastAnimatedPosition = position;
            itemView.setTranslationY(getScreenHeight());
            itemView.setRotation(360);
            itemView.animate()
                    .translationY(0)
                    .rotation(0)
                    .setStartDelay(1000 * position)
                    .setInterpolator(new DecelerateInterpolator(3.f))
                    .setDuration(800)
                    .start();
        }
    }

    private int getScreenHeight() {
        return mContext.getResources().getDisplayMetrics().heightPixels;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private final SparseArray<View> mViews;
        private View itemView;

        public ViewHolder(View itemView) {
            super(itemView);
            mViews = new SparseArray<>();
            this.itemView = itemView;
            this.itemView.setOnClickListener(v -> {
                onItemClick(getAdapterPosition());
                if (mOnItemClickListener != null)
                    setOnItemClick(v, getAdapterPosition());
            });
            setTextChangedListener(this, itemView);
            setRatingBarListener(this, itemView);
        }

        public <T extends View> T getView(int viewId) {
            View view = mViews.get(viewId);
            if (view == null) {
                view = itemView.findViewById(viewId);
                mViews.put(viewId, view);
            }
            return (T) view;
        }

        public ViewHolder setText(int viewId, String text) {
            if (TextUtils.isEmpty(text)) {
                text = "";
            }
            TextView tv = getView(viewId);
            tv.setText(text);
            return this;
        }

        public ViewHolder setHint(int viewId, String text) {
            TextView tv = getView(viewId);
            tv.setHint(text);
            return this;
        }

        public ViewHolder setAlpha(int viewId, float alpha) {
            View view = getView(viewId);
            view.setAlpha(alpha);
            return this;
        }

        /**
         * 如果text为空，显示“--”
         *
         * @param viewId
         * @param text
         * @return
         */
        public ViewHolder setTextNotNull(int viewId, String text) {
            if (TextUtils.isEmpty(text)) {
                text = "--";
            }
            TextView tv = getView(viewId);
            tv.setText(text);

            return this;
        }

        public ViewHolder setTextHint(int viewId, String hint) {
            if (TextUtils.isEmpty(hint)) {
                return this;
            }
            TextView tv = getView(viewId);
            tv.setHint(hint);
            return this;
        }

        public ViewHolder setRightIconGone(int viewId, boolean isGone) {
            if (isGone) {
                getView(viewId).getLayoutParams().width = 0;
            } else {
                getView(viewId).getLayoutParams().width = 16;
            }
            return this;
        }

        public ViewHolder setEditEnable(int viewId, boolean isEnable) {
            if (isEnable) {
                getView(viewId).setEnabled(isEnable);
            } else {
                getView(viewId).setEnabled(isEnable);
            }
            return this;
        }

        public ViewHolder setBackground(int viewId, int drawableId) {
            View view = getView(viewId);
            view.setBackground(mContext.getResources().getDrawable(drawableId));
            return this;
        }

        /**
         * 如果text为空，控件隐藏
         *
         * @param viewId
         * @param text
         * @return
         */
        public ViewHolder setTextAndView(int viewId, String text) {
            TextView tv = getView(viewId);
            if (TextUtils.isEmpty(text)) {
                tv.setVisibility(View.GONE);
            } else {
                tv.setText(text);
                tv.setVisibility(View.VISIBLE);
            }
            return this;
        }

        public ViewHolder setProjectName(int viewId, String text) {
            TextView tv = getView(viewId);
            return this;
        }

        public ViewHolder setTextColor(int viewId, int textColorId) {
            TextView tv = getView(viewId);
            tv.setTextColor(textColorId);
            return this;
        }


        public ViewHolder setClickListener(int viewId) {
            View v = getView(viewId);
            v.setOnClickListener(v1 -> onSingleViewClick(v1, getAdapterPosition()));
            return this;
        }

        public ViewHolder cancelClickListener(int viewId) {
            View v = getView(viewId);
            v.setOnClickListener(null);
            return this;
        }

        public ViewHolder setVisible(int viewId) {
            View v = getView(viewId);
            v.setVisibility(View.VISIBLE);
            return this;
        }

        public ViewHolder setInVisible(int viewId) {
            View v = getView(viewId);
            v.setVisibility(View.GONE);
            return this;
        }

        public ViewHolder setInVisibleTwo(int viewId) {
            View v = getView(viewId);
            v.setVisibility(View.INVISIBLE);
            return this;
        }

        public int getCurrentPosition() {
            return getAdapterPosition();
        }

    }

    /**
     * 绑定布局id
     *
     * @param viewType
     * @return
     */
    protected abstract int getItemLayoutId(int viewType);

    /**
     * 绑定数据
     *
     * @param holder
     * @param t
     */
    protected abstract void onBindDataToView(ViewHolder holder, T t);

    /**
     * 支持多种ItemType
     *
     * @param position
     * @return
     */
    @Override
    public abstract int getItemViewType(int position);

    /**
     * ItemView里的某个子控件的单击事件(如果需要，重写此方法就行)
     * 只有在{@link #onBindDataToView}注册了{@link ViewHolder#setClickListener}才有效果
     *
     * @param position
     */
    protected void onSingleViewClick(View view, int position) {

    }

    /**
     * ItemView的单击事件(如果需要，重写此方法就行)
     *
     * @param position
     */
    protected void onItemClick(int position) {

    }

    /**
     * 为edittext添加文本监听(如果需要，重写此方法就行)
     *
     * @param holder
     * @param itemView
     */
    protected void setTextChangedListener(ViewHolder holder, View itemView) {

    }

    protected void setRatingBarListener(ViewHolder holder, View itemView) {

    }

    /**
     * 为Adapter添加item点击方法
     */
    public BaseRecyclerViewAdapter setOnItemClickListener(OnItemClickListener listener) {
        mOnItemClickListener = listener;
        return this;
    }

    public interface OnItemClickListener {
        void onItemClick(BaseRecyclerViewAdapter adapter, View view, int position);
    }

    private void setOnItemClick(View v, int position) {
        mOnItemClickListener.onItemClick(BaseRecyclerViewAdapter.this, v, position);
    }

    public View.OnTouchListener onTouchListener = (v, event) -> {
        if (MotionEvent.ACTION_DOWN == event.getAction()) {
            v.getParent().requestDisallowInterceptTouchEvent(true);
        } else if (MotionEvent.ACTION_UP == event.getAction()) {
            v.getParent().requestDisallowInterceptTouchEvent(false);
        }
        return false;
    };

}
