package com.gh.gamecenter.libao;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.ViewSkeletonScreen;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.base.fragment.BaseFragment;
import com.gh.gamecenter.common.eventbus.EBReuse;
import com.gh.gamecenter.common.view.CustomDividerItemDecoration;
import com.gh.gamecenter.common.view.SwipeLayout;
import com.gh.gamecenter.databinding.FragmentLibaoNewBinding;
import com.gh.gamecenter.feature.entity.LibaoEntity;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by khy on 5/09/17.
 */

public class LibaoNewFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    private TextView mFooterHint;
    private LinearLayoutManager mLayoutManager;

    private LinearLayoutManager mHistoryLm;
    private LibaoHistoryAdapter mHistoryAdapter;
    private LibaoNewAdapter mAdapter;

    public final static int LIBAO_NEW_REQUEST = 5; // 刷新礼包状态

    private boolean mHistoryIsEmpty;
    private boolean mIsDone; // 判断最新礼包列表是否加载完成,准备加载历史礼包
    private ViewSkeletonScreen mSkeleton;
    private FragmentLibaoNewBinding mBinding;

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mAdapter = new LibaoNewAdapter(getContext(), LibaoNewFragment.this, LibaoNewFragment.this, mEntrance);
            mBinding.libao1RvList.setAdapter(mAdapter);
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == LIBAO_NEW_REQUEST && mAdapter.getSkipPosition() != -1) {
            // 更新对应位置
            mAdapter.notifyItemChanged(mAdapter.getSkipPosition());
            mAdapter.setSkipPosition(-1);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_libao_new;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = FragmentLibaoNewBinding.bind(mCachedView);
        mBinding.godfather.setDragEdge(SwipeLayout.DragEdge.Bottom);
        mBinding.godfather.setSwipeEnabled(false);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mBinding.libao1RvList.setLayoutManager(mLayoutManager);
        mBinding.reuseNoConnection.getRoot().setOnClickListener(this);
        mAdapter = new LibaoNewAdapter(getContext(), this, this, mEntrance);
        mBinding.libao1RvList.addItemDecoration(getItemDecoration());
        mBinding.libao1RvList.setAdapter(mAdapter);

        mBinding.libao1RvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && mLayoutManager.findLastVisibleItemPosition() + 1 == mAdapter.getItemCount()) {
                    if (mHistoryIsEmpty && mFooterHint != null) {
                        mFooterHint.setText(R.string.loading_complete);
                    }
                    if (!mAdapter.isOver() && !mAdapter.isLoading() && !mAdapter.isNetworkError()) {
                        mIsDone = false;
                        mAdapter.addLibaoList();
                    }
                }

                if (mLayoutManager.findFirstVisibleItemPosition() == 0) {
                    mBinding.godfather.setDragEdge(SwipeLayout.DragEdge.Left);
                } else {
                    if (mBinding.godfather.getDragEdge() != SwipeLayout.DragEdge.Bottom)
                        mBinding.godfather.setDragEdge(SwipeLayout.DragEdge.Bottom);
                }

                if (mLayoutManager.findLastCompletelyVisibleItemPosition() + 1 != mAdapter.getItemCount()) {
                    mBinding.godfather.setSwipeEnabled(false);
                } else {
                    if (mIsDone && !mHistoryIsEmpty) {
                        mBinding.godfather.setSwipeEnabled(true);
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int position = mLayoutManager.findFirstCompletelyVisibleItemPosition();
                if (position == 0 && Math.abs(dy) > 10) {
                    EventBus.getDefault().post(new EBReuse(Libao1Fragment.OPEN_LIBAO_APPBAR));
                }
            }
        });

        mBinding.godfather.addSwipeListener(new SwipeLayout.SwipeListener() {
            @Override
            public void onStartOpen(SwipeLayout layout) {

            }

            @Override
            public void onOpen(SwipeLayout layout) {
                mBinding.godfather.setSwipeEnabled(true);
                EventBus.getDefault().post(new EBReuse(LibaoFragment.LIBAO_OPENPAGE));
                if (mFooterHint != null) {
                    mFooterHint.setText("下拉回到最新礼包");
                }
            }

            @Override
            public void onStartClose(SwipeLayout layout) {

            }

            @Override
            public void onClose(SwipeLayout layout) {
                EventBus.getDefault().post(new EBReuse(LibaoFragment.LIBAO_CLOSEPAGE));
                mBinding.godfather.setSwipeEnabled(false);
                mAdapter.notifyItemChanged(mAdapter.getItemCount() - 1);
            }

            @Override
            public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
            }

            @Override
            public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
            }
        });


        // 历史礼包
        mHistoryAdapter = new LibaoHistoryAdapter(getContext(), this);
        mHistoryLm = new LinearLayoutManager(getActivity());
        mBinding.libao1RvHistory.setLayoutManager(mHistoryLm);
        mBinding.libao1RvHistory.setAdapter(mHistoryAdapter);
        mBinding.libao1RvHistory.addItemDecoration(getItemDecoration());
        mBinding.libao1RvHistory.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && mHistoryLm.findLastVisibleItemPosition() + 1 == mHistoryAdapter.getItemCount()) {
                    if (!mHistoryAdapter.isOver() && !mHistoryAdapter.isLoading() && !mHistoryAdapter.isNetworkError()) {
                        mIsDone = false;
                        mHistoryAdapter.loadList();
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                mBinding.godfather.setEnabled(mHistoryLm.findFirstCompletelyVisibleItemPosition() == 0);
            }
        });

    }

    private RecyclerView.ItemDecoration getItemDecoration() {
        Drawable historyInsetDivider = ContextCompat.getDrawable(requireContext(), com.gh.gamecenter.common.R.drawable.divider_item_line_space_16);
        CustomDividerItemDecoration historyItemDecoration = new CustomDividerItemDecoration(requireContext(), false, false, true, false);
        historyItemDecoration.setDrawable(historyInsetDivider);
        return historyItemDecoration;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mSkeleton = Skeleton.bind(mBinding.libaoSkeleton).shimmer(false).load(R.layout.fragment_libao_skeleton).show();
    }

    @Override
    public void loadDone() { // 数据加载成功回调
        stopRefresh();
        mBinding.reuseLoading.getRoot().setVisibility(View.GONE);
        mSkeleton.hide();
    }

    // 数据加载完毕
    @Override
    public void loadDone(Object obj) {
        super.loadDone(obj);
        if ("NULL".equals(obj.toString())) {
            mHistoryIsEmpty = true;
            return;
        }

        mIsDone = true;
        int i = mBinding.libao1RvList.getChildCount() - 1;
        if (i > 0) {
            View view = mBinding.libao1RvList.getChildAt(i);
            mFooterHint = view.findViewById(com.gh.gamecenter.common.R.id.footerview_hint);
        }
    }

    @Override
    public void loadError() { // 数据加载失败回调
        stopRefresh();
        mBinding.reuseLoading.getRoot().setVisibility(View.GONE);
        mBinding.libao1RvList.setVisibility(View.GONE);
        mBinding.reuseNoConnection.getRoot().setVisibility(View.VISIBLE);
    }

    @Override
    public void loadEmpty() {
        stopRefresh();
        mBinding.reuseLoading.getRoot().setVisibility(View.GONE);
        mBinding.reuseNoneData.getRoot().setVisibility(View.VISIBLE);
        mBinding.reuseNoConnection.getRoot().setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.reuse_no_connection) {
            mBinding.libao1RvList.setVisibility(View.VISIBLE);
            mBinding.reuseLoading.getRoot().setVisibility(View.VISIBLE);
            mBinding.reuseNoConnection.getRoot().setVisibility(View.GONE);
            postDelayedRunnable(runnable, 1000);
        }
    }

    @Override
    public void onRefresh() {
        postDelayedRunnable(runnable, 1000);
    }

    private void stopRefresh() {
        Fragment parentFragment = getParentFragment();
        if (parentFragment instanceof Libao1Fragment) {
            ((Libao1Fragment) parentFragment).stopRefresh();
        }
    }

    @Override
    public void onListClick(View view, int position, Object data) {
        super.onListClick(view, position, data);
        LibaoEntity libaoEntity = (LibaoEntity) data;
        mAdapter.setSkipPosition(position);
        Intent intent = LibaoDetailActivity.getIntent(getContext(), libaoEntity, view.getId() == R.id.libao_btn_status, mEntrance + "+(礼包中心:最新)");
        startActivityForResult(intent, LIBAO_NEW_REQUEST);
    }

    @Override
    protected void onDarkModeChanged() {
        super.onDarkModeChanged();
        mBinding.libao1RvList.getRecycledViewPool().clear();
        mAdapter.notifyItemRangeChanged(0, mAdapter.getItemCount());
        if (mBinding.libao1RvList.getItemDecorationCount() > 0) {
            mBinding.libao1RvList.removeItemDecorationAt(0);
            mBinding.libao1RvList.addItemDecoration(getItemDecoration());
        }

        mBinding.libao1RvHistory.getRecycledViewPool().clear();
        mHistoryAdapter.notifyItemRangeChanged(0, mHistoryAdapter.getItemCount());
        if (mBinding.libao1RvHistory.getItemDecorationCount() > 0) {
            mBinding.libao1RvHistory.removeItemDecorationAt(0);
            mBinding.libao1RvHistory.addItemDecoration(getItemDecoration());
        }
    }
}
