package com.gh.gamecenter.info;

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

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;

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

import com.gh.gamecenter.common.callback.OnRequestCallBackListener;
import com.gh.gamecenter.common.base.activity.ToolBarActivity;
import com.gh.common.filter.RegionSettingHelper;
import com.gh.gamecenter.eventbus.EBAddComment;
import com.gh.gamecenter.eventbus.EBDeleteComment;
import com.gh.gamecenter.feature.utils.ApkActiveUtils;
import com.gh.common.util.CheckLoginUtils;
import com.gh.common.util.DataCollectionUtils;
import com.gh.gamecenter.core.utils.MtaHelper;
import com.gh.gamecenter.core.utils.StringUtils;
import com.gh.common.view.Concern_LinearLayout;
import com.gh.gamecenter.common.view.CustomDividerItemDecoration;
import com.gh.gamecenter.ConcernActivity;
import com.gh.gamecenter.LibaoDetailActivity;
import com.gh.gamecenter.MessageDetailActivity;
import com.gh.gamecenter.NewsDetailActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.ShareCardActivity;
import com.gh.gamecenter.ShareCardPicActivity;
import com.gh.gamecenter.WebActivity;
import com.gh.gamecenter.databinding.FragmentInfoConcernBinding;
import com.gh.gamecenter.entity.ConcernEntity;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.entity.LibaoEntity;
import com.gh.gamecenter.entity.LibaoStatusEntity;
import com.gh.gamecenter.feature.entity.MeEntity;
import com.gh.gamecenter.feature.entity.UserDataLibaoEntity;
import com.gh.gamecenter.eventbus.EBConcernChanged;
import com.gh.gamecenter.common.eventbus.EBNetworkState;
import com.gh.gamecenter.common.eventbus.EBReuse;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.common.base.fragment.ToolbarFragment;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.halo.assistant.fragment.myconcern.MyConcernRecommendAdapter;

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

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by khy on 2016/8/15.
 * 资讯-关注界面
 */
public class ConcernFragment extends ToolbarFragment implements SwipeRefreshLayout.OnRefreshListener {

    private FragmentInfoConcernBinding mBinding;

    public final static int NEWS_MESSAGE_LIBAO_REQUEST = 3; // 刷新礼包状态
    public final static int NEWS_MESSAGE_ARTICLE_REQUEST = 4; // 刷新文章评论数

    private ConcernAdapter mAdapter;
    private MyConcernRecommendAdapter mConcernRecommendAdapter;

    private LinearLayoutManager layoutManager;
    private RecyclerView.ItemDecoration mItemDecoration;

    Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            mAdapter = new ConcernAdapter(getContext(), ConcernFragment.this, ConcernFragment.this);
            mBinding.news1RvList.setAdapter(mAdapter);
        }
    };

    @Override
    protected int getLayoutId() {
        return 0;
    }

    @Override
    protected View getInflatedLayout() {
        mBinding = FragmentInfoConcernBinding.inflate(getLayoutInflater());
        return mBinding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setNavigationTitle(R.string.discover_game_trends);
    }

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

        mBinding.news1SrlRefresh.setColorSchemeResources(R.color.theme);
        mBinding.news1SrlRefresh.setOnRefreshListener(this);

        mBinding.news1RvList.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(getActivity());
        mBinding.news1RvList.setLayoutManager(layoutManager);

        mBinding.news1RvList.addItemDecoration(getItemDecoration());
        mAdapter = new ConcernAdapter(getContext(), this, this);
        mBinding.news1RvList.setAdapter(mAdapter);
        mBinding.news1RvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && layoutManager.findLastVisibleItemPosition() + 1 == mAdapter.getItemCount()) {
                    if (!mAdapter.isOver() && !mAdapter.isLoading() && !mAdapter.isNetworkError()) {
                        mAdapter.addList();
                    }
                }
            }
        });

        mBinding.reuseNoneData.reuseResetLoadTv.setOnClickListener(v -> {
            if (mBinding.reuseNoneData.reuseNoneDataTv.getText().equals(getString(R.string.login_hint))) {
                CheckLoginUtils.checkLogin(getContext(), "游戏动态-请先登录", null);
            }
        });

        mBinding.reuseNoConnection.getRoot().setOnClickListener(v -> refresh());

        mBinding.concernRlTitle.setOnClickListener(v -> {
            if (mBinding.concernRvRecommend.getVisibility() == View.VISIBLE) {
                ((Concern_LinearLayout) mCachedView).hideRecyclerView();
            } else {
                ((Concern_LinearLayout) mCachedView).showRecyclerView();
            }
        });
    }

    public RecyclerView.ItemDecoration getItemDecoration() {
        Drawable insetDivider = ContextCompat.getDrawable(requireContext(), R.drawable.divider_item_line_space_16);
        CustomDividerItemDecoration itemDecoration = new CustomDividerItemDecoration(requireContext(), false, false, true, false);
        itemDecoration.setDrawable(insetDivider);
        mItemDecoration = itemDecoration;
        return mItemDecoration;
    }

    @Override
    public void onMenuItemClick(MenuItem menuItem) {
        if (menuItem.getItemId() == R.id.menu_concern) {
            MtaHelper.onEvent("我的光环_新", "游戏动态", "关注按钮");
            Intent intent = ConcernActivity.getIntent(getContext(), "(游戏动态：工具栏)");
            startActivity(intent);
        }
    }

    @Override
    public void loadDone() { // 数据加载成功回调
        mBinding.news1SrlRefresh.setEnabled(true);
        mBinding.news1SrlRefresh.setRefreshing(false);
        mBinding.reuseNoneData.reuseNoneData.setVisibility(View.GONE);
        mBinding.concernRvRecommend.setVisibility(View.GONE);
        mBinding.concernRlTitle.setVisibility(View.GONE);
        mBinding.reuseLoading.getRoot().setVisibility(View.GONE);
        mBinding.news1RvList.setVisibility(View.VISIBLE);

        ((ToolBarActivity) requireActivity()).clearMenu();
        initMenu(R.menu.menu_concern);
    }

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

    @Override
    public void loadNotFound() {
        mBinding.news1SrlRefresh.setRefreshing(false);
        mBinding.reuseLoading.getRoot().setVisibility(View.GONE);
        mBinding.news1RvList.setVisibility(View.GONE);
        mBinding.reuseDataException.getRoot().setVisibility(View.VISIBLE);
    }

    @Override
    public void loadEmpty() { // 数据为空回调
        mBinding.news1SrlRefresh.setRefreshing(false);
        mBinding.reuseLoading.getRoot().setVisibility(View.GONE);
        mBinding.news1RvList.setVisibility(View.GONE);
        mBinding.reuseNoneData.reuseNoneData.setVisibility(View.VISIBLE);
        mBinding.news1SrlRefresh.setEnabled(false);

        showRecommendGames();

        if (TextUtils.isEmpty(UserManager.getInstance().getToken())) {
            mBinding.reuseNoneData.reuseNoneDataIv.setVisibility(View.GONE);
            mBinding.reuseNoneData.reuseResetLoadTv.setVisibility(View.GONE);
            mBinding.reuseNoneData.reuseNoneDataDescTv.setVisibility(View.GONE);
            mBinding.reuseNoneData.reuseNoneDataTv.setText(getString(R.string.login_hint));
            mBinding.reuseNoneData.reuseNoneDataTv.setTextColor(getResources().getColor(R.color.theme_font));
        } else {
            mBinding.reuseNoneData.reuseNoneDataIv.setVisibility(View.VISIBLE);
            mBinding.reuseNoneData.reuseResetLoadTv.setVisibility(View.GONE);
            mBinding.reuseNoneData.reuseNoneDataDescTv.setVisibility(View.VISIBLE);
            mBinding.reuseNoneData.reuseNoneDataDescTv.setText(getString(R.string.my_game_dynamics_no_data_desc));
            mBinding.reuseNoneData.reuseNoneDataTv.setText(getString(R.string.my_game_dynamics_no_data));
            mBinding.reuseNoneData.reuseNoneDataTv.setTextColor(getResources().getColor(R.color.text_title));
        }

        ((ToolBarActivity) requireActivity()).clearMenu();
    }

    private void showRecommendGames() {
        // 先请求用户已关注的游戏数据
        RetrofitManager.getInstance().getApi()
                .getConcern(UserManager.getInstance().getUserId())
                .map(RegionSettingHelper.filterGame)
                .map(ApkActiveUtils.filterMapperList)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Response<List<GameEntity>>() {
                    @Override
                    public void onResponse(List<GameEntity> response) {
                        initRecommendAdapter(response);
                    }

                    @Override
                    public void onError(Throwable e) {
                        initRecommendAdapter(new ArrayList<>());
                    }
                });
    }

    private void initRecommendAdapter(List<GameEntity> response) {
        if (!isAdded()) return;

        mConcernRecommendAdapter = new MyConcernRecommendAdapter(getContext(),
                new OnRequestCallBackListener() {
                    @Override
                    public void loadDone() {
                        mBinding.concernRlTitle.setVisibility(View.VISIBLE);
                        mBinding.concernRvRecommend.setVisibility(View.VISIBLE);

                        int size = mConcernRecommendAdapter.getItemCount();
                        mBinding.concernRvRecommend.setAdapter(mConcernRecommendAdapter);
                        mBinding.concernRvRecommend.setLayoutManager(new GridLayoutManager(getContext(), Math.min(size, 4)));
                        mConcernRecommendAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void loadDone(Object obj) {
                        mBinding.concernRlTitle.setVisibility(View.VISIBLE);
                        mBinding.concernRvRecommend.setVisibility(View.VISIBLE);

                        int size = mConcernRecommendAdapter.getItemCount();
                        mBinding.concernRvRecommend.setAdapter(mConcernRecommendAdapter);
                        mBinding.concernRvRecommend.setLayoutManager(new GridLayoutManager(getContext(), Math.min(size, 4)));
                        mConcernRecommendAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void loadError() {

                    }

                    @Override
                    public void loadEmpty() {
                        onRefresh();
                    }

                    @Override
                    public void loadNotFound() {
                        // do nothing
                    }
                },
                response,
                mEntrance);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (mAdapter.getSkipPosition() == -1) {
            return;
        }

        switch (requestCode) {
            case NEWS_MESSAGE_ARTICLE_REQUEST:
                // 更新对应位置
                mAdapter.notifyItemChanged(mAdapter.getSkipPosition());
                mAdapter.setSkipPosition(-1);
                break;
            case NEWS_MESSAGE_LIBAO_REQUEST:
                if (resultCode != Activity.RESULT_OK) break;
                UserDataLibaoEntity resultUserLibaoData = data.getParcelableExtra(UserDataLibaoEntity.TAG);
                ConcernEntity skipEntity = mAdapter.getSkipEntity();
                if (skipEntity != null) { // 插入礼包详情返回的礼包数据
                    MeEntity userData = skipEntity.getMe();
                    if (userData == null) {
                        userData = new MeEntity();
                        ArrayList<UserDataLibaoEntity> libaoList = new ArrayList<>();
                        libaoList.add(resultUserLibaoData);
                        userData.setUserDataLibaoList(libaoList);
                    } else {
                        if (userData.getUserDataLibaoList() == null) {
                            ArrayList<UserDataLibaoEntity> libaoList = new ArrayList<>();
                            libaoList.add(resultUserLibaoData);
                            userData.setUserDataLibaoList(libaoList);
                        } else {
                            userData.getUserDataLibaoList().add(resultUserLibaoData);
                        }
                    }
                    skipEntity.setMe(userData); // 要重新设回去 不然没效果 0.0
                }
                mAdapter.notifyItemChanged(mAdapter.getSkipPosition());
                mAdapter.setSkipPosition(-1);
                break;
        }
    }

    // 连接上网络事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBNetworkState busNetworkState) {
        if (busNetworkState.isNetworkConnected()) {
            if (mBinding.reuseNoConnection.getRoot().getVisibility() == View.VISIBLE) {
                refresh();
            } else if (mAdapter.isNetworkError()) {
                mAdapter.setNetworkError(false);
                mAdapter.notifyItemChanged(mAdapter.getItemCount() - 1);
                mAdapter.addList();
            }
        }
    }

    private void refresh() {
        mBinding.news1SrlRefresh.setRefreshing(true);
        mBinding.news1RvList.setVisibility(View.VISIBLE);
        mBinding.reuseLoading.getRoot().setVisibility(View.VISIBLE);
        mBinding.reuseNoConnection.getRoot().setVisibility(View.GONE);
        postRunnable(mRunnable);
    }

    // 关注事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBConcernChanged changed) {
        if (!isResumed()) {
            refresh();
        } else {
            if (mAdapter.getItemCount() == 0) {
                mBinding.reuseNoneData.reuseNoneDataIv.setVisibility(View.GONE);
                mBinding.reuseNoneData.reuseNoneDataTv.setVisibility(View.GONE);
                mBinding.reuseNoneData.reuseNoneDataDescTv.setVisibility(View.GONE);
                mBinding.reuseNoneData.reuseResetLoadTv.setVisibility(View.VISIBLE);
                mBinding.reuseNoneData.reuseResetLoadTv.setText("点击刷新");
                mBinding.reuseNoneData.reuseResetLoadTv.setTextColor(getResources().getColor(R.color.background_white));
                mBinding.reuseNoneData.reuseResetLoadTv.setOnClickListener(v -> {
                    refresh();
                    mBinding.reuseNoneData.reuseResetLoadTv.setOnClickListener(null);
                });
            }
        }
        mConcernRecommendAdapter.concernGame(changed.getGameId());
    }

    // 登录事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBReuse reuse) {
        if (reuse.getType().equals(LOGIN_TAG)) { // 登入
            mBinding.reuseNoneData.reuseNoneDataIv.setVisibility(View.GONE);
            mBinding.news1SrlRefresh.setEnabled(true);
            mBinding.news1SrlRefresh.setRefreshing(true);
            mBinding.news1RvList.setVisibility(View.VISIBLE);
            mBinding.reuseLoading.getRoot().setVisibility(View.VISIBLE);
            postRunnable(mRunnable);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddComment(EBAddComment event) {
        mAdapter.getNewsCommentnum(mAdapter.getConcernList());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeleteComment(EBDeleteComment event) {
        mAdapter.getNewsCommentnum(mAdapter.getConcernList());
    }

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

    @Override
    public void onListClick(View view, int position, Object data) {
        super.onListClick(view, position, data);
        ConcernEntity concernEntity = (ConcernEntity) data;

        final String entrance = StringUtils.buildString("(资讯:关注[" + position + "])");

        Intent intent;
        switch (view.getId()) {
            case R.id.news_digest_comment:
                mAdapter.setSkipPosition(position);
                intent = MessageDetailActivity.getIntentByEntity(getContext(), concernEntity, entrance);
                startActivityForResult(intent, NEWS_MESSAGE_ARTICLE_REQUEST);
                break;
            case R.id.news_digest_share:
                if (concernEntity.getImg() != null && concernEntity.getImg().size() > 0) {
                    ShareCardPicActivity.startShareCardPicActivity(getContext(), concernEntity, entrance);
                } else {
                    String shareContent;
                    if (concernEntity.getBrief() != null) {
                        shareContent = concernEntity.getBrief();
                    } else {
                        shareContent = concernEntity.getContent();
                    }
                    startActivity(ShareCardActivity.getIntent(getContext(), concernEntity, shareContent));
                }
                break;
            default: // 默认是 viewholder item
                mAdapter.setSkipPosition(position);
                if ("libao".equals(concernEntity.getType())) {
                    LibaoEntity entity = null;
                    for (LibaoStatusEntity libaoStatusEntity : mAdapter.getLibaoStatusList()) {
                        if (concernEntity.getId().equals(libaoStatusEntity.getId())) {
                            entity = LibaoEntity.Companion.createLibaoEntity(concernEntity, libaoStatusEntity);
                        }
                    }
                    intent = LibaoDetailActivity.getIntent(getContext(), entity, entrance);
                    startActivityForResult(intent, NEWS_MESSAGE_LIBAO_REQUEST);
                } else {
                    DataCollectionUtils.uploadClick(getContext(), "列表", "资讯-关注", concernEntity.getTitle());

                    //统计阅读量
                    mAdapter.statNewsViews(concernEntity, position);
                    if (concernEntity.getLink() != null) {
                        intent = WebActivity.getIntentByNews(getContext(), concernEntity, entrance);
                        startActivityForResult(intent, NEWS_MESSAGE_ARTICLE_REQUEST);
                    } else {
                        intent = NewsDetailActivity.getIntentById(getContext(), concernEntity.getId(), entrance);
                        startActivityForResult(intent, NEWS_MESSAGE_ARTICLE_REQUEST);
                    }
                }
                break;
        }
    }

    @Override
    protected void onDarkModeChanged() {
        super.onDarkModeChanged();
        mAdapter.notifyItemRangeChanged(0, mAdapter.getItemCount());
        if (mConcernRecommendAdapter != null)
            mConcernRecommendAdapter.notifyItemRangeChanged(0, mConcernRecommendAdapter.getItemCount());
        mBinding.news1RvList.removeItemDecoration(mItemDecoration);
        mBinding.news1RvList.addItemDecoration(getItemDecoration());
        mBinding.getRoot().setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.background_white));
        mBinding.divider.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.divider));
    }
}
