package com.gh.gamecenter.info;

import android.app.Dialog;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

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

import com.gh.common.filter.RegionSettingHelper;
import com.gh.common.util.CheckLoginUtils;
import com.gh.common.util.NewsUtils;
import com.gh.gamecenter.ConcernActivity;
import com.gh.gamecenter.GameNewsActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.base.fragment.BaseFragment;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.gamecenter.common.eventbus.EBReuse;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.core.utils.DisplayUtils;
import com.gh.gamecenter.core.utils.StringUtils;
import com.gh.gamecenter.databinding.DialogStrategySelectGameBinding;
import com.gh.gamecenter.databinding.FragmentInfoStrategyBinding;
import com.gh.gamecenter.eventbus.EBUISwitch;
import com.gh.gamecenter.feature.entity.GameEntity;
import com.gh.gamecenter.feature.entity.NewsEntity;
import com.gh.gamecenter.feature.eventbus.EBConcernChanged;
import com.gh.gamecenter.feature.utils.ApkActiveUtils;
import com.gh.gamecenter.login.user.UserManager;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.newsdetail.NewsDetailActivity;
import com.gh.gamecenter.retrofit.RetrofitManager;
import com.jakewharton.rxbinding2.view.RxView;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

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

/**
 * Created by khy on 2017/4/7.
 * 资讯-攻略界面,guilds/strategy会比较好
 */
public class StrategyFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,
        OnStrategyDialogCallBackListener {

    private FragmentInfoStrategyBinding mBinding;

    private Dialog dialog;
    private View dialogContentView;
    private LinearLayoutManager mLayoutManager;
    private StrategyAdapter mStrategyAdapter;
    private StrategyDialogAdapter mStrategyDialogAdapter;

    private List<GameEntity> mConcernGame;

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            mStrategyAdapter = new StrategyAdapter(getContext(), StrategyFragment.this, StrategyFragment.this);
            mBinding.strategyRv.setAdapter(mStrategyAdapter);
            mStrategyAdapter.addList();
        }
    };

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

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

    @Override
    protected void initView(View view) {
        super.initView(view);

        mConcernGame = new ArrayList<>();

        mBinding.strategyRefresh.setColorSchemeResources(com.gh.gamecenter.common.R.color.primary_theme);
        mBinding.strategyRefresh.setOnRefreshListener(this);
        mCachedView.setBackgroundColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.ui_surface));

        mStrategyAdapter = new StrategyAdapter(getContext(), this, this);
        mLayoutManager = new LinearLayoutManager(getContext());
        mBinding.strategyRv.setLayoutManager(mLayoutManager);
        mBinding.strategyRv.setAdapter(mStrategyAdapter);

        mBinding.strategyRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (mLayoutManager.findLastVisibleItemPosition() + 1 == mStrategyAdapter.getItemCount()
                        && newState == RecyclerView.SCROLL_STATE_IDLE && mStrategyAdapter.isCanLoading()) {
                    mStrategyAdapter.addList();
                }
            }
        });

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

        // 防抖处理
        RxView.clicks(mBinding.strategySelectGameRl)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(aVoid -> {
                    if (mConcernGame.size() > 1 || (mConcernGame.size() == 1
                            && !Constants.GHZS_GAME_ID.equals(mConcernGame.get(0).getId()))) {
                        OnSelectGameClickListener();
                    } else {
                        CheckLoginUtils.checkLogin(getContext(), "资讯(攻略-我关注的游戏)", () -> {
                            Intent intent = ConcernActivity.getIntent(getContext(), "资讯(攻略-我关注的游戏)");
                            startActivity(intent);
                        });
                    }
                });
    }

    private void getConcernGame() {
        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) {
                        super.onResponse(response);
                        mConcernGame.clear();
                        mConcernGame.addAll(response);
                    }
                });
    }

    public void OnSelectGameClickListener() {
        isShowPopupBg(true);

        dialogContentView = View.inflate(getContext(), R.layout.dialog_strategy_select_game, null);
        RecyclerView selectGameRv = dialogContentView.findViewById(R.id.dialog_strategy_select_game_rv);
        RelativeLayout allGameRl = dialogContentView.findViewById(R.id.dialog_strategy_select_game_rl);

        if (mConcernGame.size() >= 8) {
            ViewGroup.LayoutParams params = selectGameRv.getLayoutParams();
            params.height = DisplayUtils.dip2px(getContext(), 43 * 8);
            selectGameRv.setLayoutParams(params);
        }

        int widthPixels = getResources().getDisplayMetrics().widthPixels;
        allGameRl.setLayoutParams(new LinearLayout.LayoutParams((widthPixels * 9) / 10,
                DisplayUtils.dip2px(getContext(), 50)));

        allGameRl.setOnClickListener(v -> {
            isShowPopupBg(false);
            Intent intent = ConcernActivity.getIntent(getContext(), "资讯(攻略-我关注的游戏)");
            startActivity(intent);
        });

        selectGameRv.setLayoutManager(new LinearLayoutManager(getContext()));
        mStrategyDialogAdapter = new StrategyDialogAdapter(StrategyFragment.this, mConcernGame);
        selectGameRv.setAdapter(mStrategyDialogAdapter);


        dialog = new Dialog(getContext());

        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(dialogContentView);
        dialog.show();


        dialogContentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowPopupBg(false);
            }
        });
    }

    public void isShowPopupBg(boolean isShow) {
        if (!isShow) {
            if (dialog != null) {
                dialog.cancel();
            }
        }
    }

    @Override
    public void loadDone() {
        super.loadDone();
        mBinding.strategyRefresh.setRefreshing(false);
        mBinding.reuseLoading.getRoot().setVisibility(View.GONE);
        mBinding.strategyRv.setVisibility(View.VISIBLE);
        mBinding.reuseNoneData.getRoot().setVisibility(View.GONE);
    }

    @Override
    public void loadError() {
        super.loadError();
        mBinding.strategyRefresh.setRefreshing(false);
        mBinding.reuseLoading.getRoot().setVisibility(View.GONE);
        mBinding.strategyRv.setVisibility(View.GONE);
        mBinding.reuseNoConnection.getRoot().setVisibility(View.VISIBLE);
    }

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

    public void reconnection() { // 重新连接
        mBinding.strategyRv.setVisibility(View.VISIBLE);
        mBinding.reuseLoading.getRoot().setVisibility(View.VISIBLE);
        mBinding.reuseNoConnection.getRoot().setVisibility(View.GONE);
        postDelayedRunnable(runnable, 1000);
    }

    @Override
    public void selectPosition(int position, GameEntity gameEntity) {
        isShowPopupBg(false);
        Intent intent = GameNewsActivity.getIntent(getContext(), gameEntity.getName(), gameEntity.getId(), "资讯-攻略(我关注的游戏)");
        getContext().startActivity(intent);
    }

    // 资讯Fragment界面切换事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBUISwitch busNine) {
        if (InfoWrapperFragment.EB_NEWSFRAGMENT_TAG.equals(busNine.getFrom())) {
            if (busNine.getPosition() == InfoWrapperFragment.INDEX_STRATEGY && mBinding.reuseLoading.getRoot().getVisibility() == View.VISIBLE) {
                mStrategyAdapter.addList();
                if (!TextUtils.isEmpty(UserManager.getInstance().getToken())) {
                    getConcernGame();
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBConcernChanged changed) {
        getConcernGame();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EBReuse reuse) {
        if (Constants.LOGIN_TAG.equals(reuse.getType()) || Constants.LOGOUT_TAG.equals(reuse.getType())) {
            getConcernGame();
        }
    }


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

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

        Map<String, Object> map = new HashMap<>();
        map.put("page", "资讯-攻略");
        map.put("news", newsEntity.getTitle());
        map.put("news_id", newsEntity.getId());
        DataCollectionManager.onEvent(getContext(), "click-item", map);

        // 统计阅读量
        NewsUtils.statNewsViews(newsEntity.getId());
        NewsDetailActivity.startNewsDetailActivity(getContext(), newsEntity,
                StringUtils.buildString("(资讯:攻略[" + position + "])"));
    }

    @Override
    protected void onDarkModeChanged() {
        super.onDarkModeChanged();
        mCachedView.setBackgroundColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.ui_surface));
        mBinding.container.setBackgroundColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.ui_surface));
        mStrategyAdapter.notifyItemRangeChanged(0, mStrategyAdapter.getItemCount());
        if (dialog != null && dialogContentView != null && mStrategyDialogAdapter != null) {
            DialogStrategySelectGameBinding binding = DialogStrategySelectGameBinding.bind(dialogContentView);
            mStrategyDialogAdapter.notifyItemRangeChanged(0, mStrategyDialogAdapter.getItemCount());
            binding.dialogStrategySelectGameRv.setBackgroundColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.ui_surface));
            binding.dialogStrategySelectGameRl.setBackgroundColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.ui_surface));
            binding.desTv.setBackgroundColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.cutting_line));
            binding.desTv.setTextColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.title));
            binding.titleTv.setTextColor(ContextCompat.getColor(requireContext(), com.gh.gamecenter.common.R.color.text_theme));
        }
    }
}
