package com.gingersoft.gsa.cloud.ui.recylcler.event;

import android.graphics.Color;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.core.table.TableManagerItem;
import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionHeader;
import com.jess.arms.base.DefaultAdapter;
import com.qmuiteam.qmui.widget.section.QMUIDefaultStickySectionAdapter;
import com.qmuiteam.qmui.widget.section.QMUISection;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionAdapter;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import lombok.SneakyThrows;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2020-06-10
 * 修订历史：2020-06-10
 * 描述：
 */

public class RecyItemTouchHelperCallback<H extends QMUISection.Model<H>, T extends QMUISection.Model<T>> extends ItemTouchHelper.Callback {
    private final String TAG = getClass().getSimpleName();
    private RecyclerView.Adapter mAdapter;
    boolean isSwipeEnable;
    boolean isFirstDragUnable;
    private String ids;

    public RecyItemTouchHelperCallback(RecyclerView.Adapter adapter) {
        mAdapter = adapter;
        isSwipeEnable = true;
        isFirstDragUnable = false;
    }

    public RecyItemTouchHelperCallback(RecyclerView.Adapter adapter, boolean isSwipeEnable, boolean isFirstDragUnable) {
        mAdapter = adapter;
        this.isSwipeEnable = isSwipeEnable;
        this.isFirstDragUnable = isFirstDragUnable;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            int swipeFlags = 0;
            return makeMovementFlags(dragFlags, swipeFlags);
        } else {
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
            return makeMovementFlags(dragFlags, swipeFlags);
        }
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        int fromPosition = viewHolder.getAdapterPosition();
        int toPosition = target.getAdapterPosition();
        if (isFirstDragUnable && toPosition == 0) {
            return false;
        }
        if (fromPosition < toPosition) {
            if (mAdapter instanceof QMUIStickySectionAdapter) {
                QMUIStickySectionAdapter sectionAdapter = (QMUIStickySectionAdapter) mAdapter;
                QMUIStickySectionAdapter.ViewHolder holder = (QMUIStickySectionAdapter.ViewHolder) viewHolder;
                QMUISection<H, T> qmuiSections = sectionAdapter.getSection(holder.getAdapterPosition());
                List<?> list = qmuiSections.getItemList();

                int fromIndex = sectionAdapter.getItemIndex(fromPosition);
                int toIndex = sectionAdapter.getItemIndex(toPosition);

                if (toIndex < 0 || fromIndex < 0) {
                    return false;
                }
                if ((fromIndex + 1) == list.size()) {
                    return false;
                }
                LoganManager.w_tableMode(TAG, LoganManager.EVENT_SCOLL + "調整餐檯排序fromIndex=" + fromIndex + " toIndex=" +toIndex);
                Collections.swap(list, fromIndex, toIndex);
                ids = getTableIds((List<TableManagerItem>) list);
            } else {
                Collections.swap(((DefaultAdapter) mAdapter).getInfos(), fromPosition, toPosition);
                ids = null;
            }
        } else {
            if (mAdapter instanceof QMUIStickySectionAdapter) {
                QMUIStickySectionAdapter sectionAdapter = (QMUIStickySectionAdapter) mAdapter;
                QMUIStickySectionAdapter.ViewHolder holder = (QMUIStickySectionAdapter.ViewHolder) viewHolder;
                QMUISection<H, T> qmuiSections = sectionAdapter.getSection(holder.getAdapterPosition());
                List<?> list = qmuiSections.getItemList();

                int fromIndex = sectionAdapter.getItemIndex(fromPosition);
                int toIndex = sectionAdapter.getItemIndex(toPosition);

                if (toIndex < 0 || fromIndex < 0) {
                    return false;
                }
                if ((fromIndex + 1) == list.size()) {
                    return false;
                }
                LoganManager.w_tableMode(TAG, LoganManager.EVENT_SCOLL + "調整餐檯排序fromIndex=" + fromIndex + " toIndex=" + toIndex);
                Collections.swap(list, fromIndex, toIndex);
                ids = getTableIds((List<TableManagerItem>) list);
            } else {
                Collections.swap(((DefaultAdapter) mAdapter).getInfos(), fromPosition, toPosition);
                ids = null;
            }
        }
        mAdapter.notifyItemMoved(fromPosition, toPosition);
        return true;
    }


    private String getTableIds(List<TableManagerItem> qmuiSectionList) {
        StringBuilder builder = new StringBuilder();
        for (TableManagerItem tableItem : qmuiSectionList) {
            if (tableItem.getLayoutType() == 0) {
                builder.append(tableItem.getId());
                builder.append(",");
            }
        }
        String str = builder.toString();
        if (str.endsWith(",")) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        int adapterPosition = viewHolder.getAdapterPosition();
        mAdapter.notifyItemRemoved(adapterPosition);
        if (mAdapter instanceof QMUIDefaultStickySectionAdapter) {
            ((QMUIDefaultStickySectionAdapter) mAdapter).getCurrentData().remove(adapterPosition);
        } else {
            ((DefaultAdapter) mAdapter).getInfos().remove(adapterPosition);
        }
    }

    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
        if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
            viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
        }
        super.onSelectedChanged(viewHolder, actionState);
    }

    @Override
    public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        super.clearView(recyclerView, viewHolder);
        viewHolder.itemView.setBackgroundColor(Color.WHITE);
//        mAdapter.notifyDataSetChanged();
        if (onMoveListener != null) {
            onMoveListener.onMoveFinish(mAdapter, ids);
        }
    }

    @Override
    public boolean isLongPressDragEnabled() {
        return !isFirstDragUnable;
    }

    @Override
    public boolean isItemViewSwipeEnabled() {
        return isSwipeEnable;
    }

    private onMoveListener onMoveListener;

    public void setOnMoveListener(RecyItemTouchHelperCallback.onMoveListener onMoveListener) {
        this.onMoveListener = onMoveListener;
    }

    public interface onMoveListener {
        void onMoveFinish(RecyclerView.Adapter adapter, String ids);
    }
}