package com.gh.gamecenter.libao;

import static com.gh.gamecenter.libao.Libao1Fragment.OPEN_LIBAO_APPBAR;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.View;

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.gh.gamecenter.LibaoDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.base.fragment.BaseFragment;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.view.CustomDividerItemDecoration;
import com.gh.gamecenter.databinding.FragmentLibaoSerachBinding;
import com.gh.gamecenter.entity.LibaoEntity;
import com.gh.gamecenter.common.eventbus.EBReuse;

import org.greenrobot.eventbus.EventBus;

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

public class LibaoSearchFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    private FragmentLibaoSerachBinding mBinding;
    private LinearLayoutManager mLayoutManager;
    private LibaoSearchAdapter mAdapter;

    public final static int LIBAO_SEARCH_REQUEST = 6; // 刷新礼包状态


    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mAdapter = new LibaoSearchAdapter(LibaoSearchFragment.this, LibaoSearchFragment.this, mEntrance);
            mBinding.libaoSearchRvList.setAdapter(mAdapter);
        }
    };

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

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

    @Override
    protected void initView(View view) {
        super.initView(view);
        mBinding = FragmentLibaoSerachBinding.bind(view);
        mBinding.libaoSearchRvList.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mBinding.libaoSearchRvList.setLayoutManager(mLayoutManager);
        mBinding.reuseNoConnection.getRoot().setOnClickListener(this);

        mAdapter = new LibaoSearchAdapter(this, this, mEntrance);

        mBinding.libaoSearchRvList.addItemDecoration(getItemDecoration());
        mBinding.libaoSearchRvList.setAdapter(mAdapter);

        mBinding.libaoSearchRvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && mLayoutManager.findLastVisibleItemPosition() + 1 == mAdapter.getItemCount()) {
                    if (!mAdapter.isOver() && !mAdapter.isLoading() && !mAdapter.isNetworkError()) {
                        mAdapter.addLibaoList();
                    }
                }
            }

            @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(OPEN_LIBAO_APPBAR));
                }
            }
        });

    }

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

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


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

    @Override
    public void loadEmpty() {
        colseRefresh();
        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.libaoSearchRvList.setVisibility(View.VISIBLE);
            mBinding.reuseLoading.getRoot().setVisibility(View.VISIBLE);
            mBinding.reuseNoConnection.getRoot().setVisibility(View.GONE);
            postDelayedRunnable(runnable, 1000);
        }
    }

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


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

    public void search() {
        if (mBinding.reuseNoneData.getRoot().getVisibility() == View.VISIBLE) {
            mBinding.reuseNoneData.getRoot().setVisibility(View.GONE);
        }
        postRunnable(runnable);
    }

    @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, mEntrance + "+(礼包中心:最新)");
        startActivityForResult(intent, LIBAO_SEARCH_REQUEST);
    }

    @Override
    protected void onDarkModeChanged() {
        super.onDarkModeChanged();
        ExtensionsKt.setRootBackgroundColor(mBinding.getRoot(), R.color.background);
        mBinding.libaoSearchRvList.getRecycledViewPool().clear();
        mAdapter.notifyItemRangeChanged(0, mAdapter.getItemCount());
        if (mBinding.libaoSearchRvList.getItemDecorationCount() > 0) {
            mBinding.libaoSearchRvList.removeItemDecorationAt(0);
            mBinding.libaoSearchRvList.addItemDecoration(getItemDecoration());
        }
    }
}
