package com.gh.gamecenter.libao;

import static com.gh.gamecenter.common.constant.Constants.LOGIN_TAG;

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

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.gh.common.util.CheckLoginUtils;
import com.gh.gamecenter.ConcernActivity;
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.utils.ExtensionsKt;
import com.gh.gamecenter.common.view.CustomDividerItemDecoration;
import com.gh.gamecenter.databinding.FragmentLibao2Binding;
import com.gh.gamecenter.eventbus.EBUISwitch;
import com.gh.gamecenter.feature.entity.LibaoEntity;
import com.gh.gamecenter.feature.eventbus.EBConcernChanged;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by khy on 2016/12/12.
 */
public class Libao2Fragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    private FragmentLibao2Binding mBinding;
    private LinearLayoutManager mLayoutManager;
    private Libao2FragmentAdapter adapter;

    public final static int LIBAO_CONCERN_REQUEST = 7; // 刷新礼包状态
    public final static int CONCERN_CHANGE_REQUEST = 8; // 配合 isConcernChanged 观察关注的游戏是否改变(刷新整个列表)

    private boolean isConcernChanged;

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (getActivity() != null && !getActivity().isFinishing()) {
                adapter = new Libao2FragmentAdapter(getContext(), Libao2Fragment.this, Libao2Fragment.this, mEntrance);
                mBinding.libao2RvList.setAdapter(adapter);
                adapter.addList();
            }
        }
    };

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

    @Override
    protected void initView(View view) {
        super.initView(view);
        mBinding = FragmentLibao2Binding.bind(view);
        mBinding.libao2SrlRefresh.setColorSchemeResources(com.gh.gamecenter.common.R.color.primary_theme);
        mBinding.libao2SrlRefresh.setOnRefreshListener(this);
        mBinding.reuseNoConnection.reuseNoConnection.setOnClickListener(this);
        mBinding.reuseNoneData.reuseNoneDataTv.setOnClickListener(this);

        mBinding.libao2RvList.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mBinding.libao2RvList.setLayoutManager(mLayoutManager);
        adapter = new Libao2FragmentAdapter(getContext(), this, this, mEntrance);
        mBinding.libao2RvList.addItemDecoration(getItemDecoration());
        mBinding.libao2RvList.setAdapter(adapter);

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

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isConcernChanged = false;

    }

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

    @Override
    public void loadDone() { // 数据加载成功回调
        mBinding.libao2SrlRefresh.setRefreshing(false);
        mBinding.reuseLoading.getRoot().setVisibility(View.GONE);
        mBinding.libao2RvList.setVisibility(View.VISIBLE);
        mBinding.reuseNoneData.getRoot().setVisibility(View.GONE);
    }

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

    @Override
    public void loadEmpty() { // 数据为空回调
        mBinding.libao2SrlRefresh.setRefreshing(false);
        mBinding.reuseLoading.getRoot().setVisibility(View.GONE);
        mBinding.libao2RvList.setVisibility(View.GONE);
        mBinding.reuseNoneData.getRoot().setVisibility(View.VISIBLE);
//        mBinding.reuseNoneData.reuseNoneDataTv.setText(R.string.game_empty);
//        mBinding.reuseNoneData.reuseNoneDataTv.setTextColor(getResources().getColor(R.color.c7c7c7));
    }

    @Override
    public void loadDone(Object obj) {
        super.loadDone(obj);
        mBinding.libao2SrlRefresh.setRefreshing(false);
        mBinding.reuseLoading.getRoot().setVisibility(View.GONE);
        mBinding.reuseNoneData.getRoot().setVisibility(View.VISIBLE);
        mBinding.reuseNoneData.reuseNoneDataTv.setText(com.gh.gamecenter.feature.R.string.login_hint);
        mBinding.reuseNoneData.reuseNoneDataTv.setTextColor(getResources().getColor(com.gh.gamecenter.common.R.color.text_theme));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == LIBAO_CONCERN_REQUEST && adapter.getSkipPosition() != -1) {
            // 更新对应位置
            adapter.notifyItemChanged(adapter.getSkipPosition());
            adapter.setSkipPosition(-1);
        } else if (requestCode == CONCERN_CHANGE_REQUEST && isConcernChanged) {
            mBinding.reuseNoneData.getRoot().setVisibility(View.GONE);
            mBinding.libao2SrlRefresh.setEnabled(true);
            mBinding.libao2SrlRefresh.setRefreshing(true);
            mBinding.libao2RvList.setVisibility(View.GONE);
            mBinding.reuseLoading.getRoot().setVisibility(View.VISIBLE);
            postRunnable(runnable);
            isConcernChanged = false;
        }
    }

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

    public void onClick(View v) { // 重新连接
        switch (v.getId()) {
            case R.id.reuse_no_connection:
                mBinding.libao2SrlRefresh.setRefreshing(true);
                mBinding.libao2RvList.setVisibility(View.VISIBLE);
                mBinding.reuseLoading.getRoot().setVisibility(View.VISIBLE);
                mBinding.reuseNoConnection.getRoot().setVisibility(View.GONE);
                postDelayedRunnable(runnable, 1000);
                break;
            case R.id.reuseNoneDataTv:
                String hint = getString(com.gh.gamecenter.feature.R.string.login_hint);
                if (hint.equals(mBinding.reuseNoneData.reuseNoneDataTv.getText().toString())) {
                    CheckLoginUtils.checkLogin(getContext(), "礼包中心-关注-请先登录", null);
                }
                break;
        }
    }

    // 资讯Fragment界面切换事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBUISwitch busNine) {
        if (LibaoFragment.EB_LIBAOACTIVITY_TAG.equals(busNine.getFrom())) {
            if (busNine.getPosition() == 1 && mBinding.reuseLoading.getRoot().getVisibility() == View.VISIBLE) {
                adapter.addList();
            }
        }
    }

    // 关注事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBConcernChanged changed) {
        isConcernChanged = true;
    }

    @Override
    public void onListClick(View view, int position, Object data) {
        super.onListClick(view, position, data);
        Intent intent;
        switch (view.getId()) {
            case R.id.newsdetail_item_comment:
                intent = ConcernActivity.getIntent(getContext(), mEntrance + "+(礼包中心:关注)");
                startActivityForResult(intent, CONCERN_CHANGE_REQUEST);
                break;
            default:
                LibaoEntity libaoEntity = (LibaoEntity) data;
                adapter.setSkipPosition(position);
                intent = LibaoDetailActivity.getIntent(getContext(), libaoEntity, view.getId() == R.id.libao_btn_status, mEntrance + "+(礼包中心:关注)");
                startActivityForResult(intent, LIBAO_CONCERN_REQUEST);
                break;
        }
    }

    // 登录事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBReuse reuse) {
        if (reuse.getType().equals(LOGIN_TAG)) { // 登入
            postRunnable(runnable);
        }
    }

    @Override
    protected void onDarkModeChanged() {
        super.onDarkModeChanged();
        ExtensionsKt.setRootBackgroundColor(mBinding.getRoot(), com.gh.gamecenter.common.R.color.ui_surface);
        mBinding.libao2RvList.getRecycledViewPool().clear();
        adapter.notifyItemRangeChanged(0, adapter.getItemCount());
        if (mBinding.libao2RvList.getItemDecorationCount() > 0) {
            mBinding.libao2RvList.removeItemDecorationAt(0);
            mBinding.libao2RvList.addItemDecoration(getItemDecoration());
        }
    }
}
