package com.sheep.gamegroup.view.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.kfzs.duanduan.utils.StatusBarUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.absBase.ILoadMore;
import com.sheep.gamegroup.absBase.IRefresh;
import com.sheep.gamegroup.model.entity.Applications;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.GameInfoList;
import com.sheep.gamegroup.model.entity.LatelyGame;
import com.sheep.gamegroup.model.entity.UserFocus;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.ApiUtil;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.RefreshUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.util.share.ShareLinkConfig;
import com.sheep.gamegroup.view.adapter.AdpGcGameAppInfoList;
import com.sheep.gamegroup.view.adapter.AdpGcGameAppList;
import com.sheep.gamegroup.view.adapter.TitleFragmentListAdapter;
import com.sheep.gamegroup.view.fragment.FgtUserAppHomeCommentList;
import com.sheep.gamegroup.view.fragment.FgtUserAppHomeReplyList;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;

import org.afinal.simplecache.ApiKey;

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

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

/**
 * Created by realicing on 2018/11/5.
 * realicing@sina.com
 */
public class ActUserAppHome extends BaseActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        StatusBarUtils.setTranslucent(this);
        super.onCreate(savedInstanceState);
    }

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

    @BindView(R.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.user_app_home_bg)
    ImageView user_app_home_bg;
    @BindView(R.id.user_app_home_avatar)
    ImageView user_app_home_avatar;
    @BindView(R.id.user_app_home_num_fans)
    TextView user_app_home_num_fans;
    @BindView(R.id.user_app_home_num_focus_users)
    TextView user_app_home_num_focus_users;
    @BindView(R.id.user_app_home_num_focus_games)
    TextView user_app_home_num_focus_games;
    @BindView(R.id.user_app_home_num_like)
    TextView user_app_home_num_like;
    @BindView(R.id.user_app_home_focus)
    TextView user_app_home_focus;
    @BindView(R.id.user_app_home_name)
    TextView user_app_home_name;
    @BindView(R.id.user_app_home_game_list)
    RecyclerView user_app_home_game_list;
    @BindView(R.id.user_app_home_focus_ll)
    View user_app_home_focus_ll;

    private int focus_user_id;
    private TitleFragmentListAdapter mAdapter;

    private ArrayList<GameInfoList> gameInfoListArrayList = ListUtil.emptyList();

    @Override
    public void initView() {
        focus_user_id = DataUtil.getObject(getIntent(), Integer.class);
        if(TextUtils.equals(String.valueOf(focus_user_id), DataUtil.getInstance().getUserId())){//用户不能关注自己
            ViewUtil.setVisibility(user_app_home_focus_ll, false);
        }
        //viewPager
        mAdapter = new TitleFragmentListAdapter(getSupportFragmentManager());
        FgtUserAppHomeCommentList fgtUserAppHomeCommentList = new FgtUserAppHomeCommentList();
        fgtUserAppHomeCommentList.setFocus_user_id(focus_user_id);
        fgtUserAppHomeCommentList.setSmartRefreshLayout(refresh);
        FgtUserAppHomeReplyList fgtUserAppHomeReplyList = new FgtUserAppHomeReplyList();
        fgtUserAppHomeReplyList.setFocus_user_id(focus_user_id);
        fgtUserAppHomeReplyList.setSmartRefreshLayout(refresh);
        mAdapter.add(fgtUserAppHomeCommentList, "评论");
        mAdapter.add(fgtUserAppHomeReplyList, "回复");
        viewPager.setAdapter(mAdapter);
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
        tabLayout.setupWithViewPager(viewPager);
        CommonUtil.getInstance().reflex(tabLayout, this);
        //refresh
        refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData();
            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadMoreData();
            }
        });
        RefreshUtil.newInstance().publicParameterLoadMore(refresh, this);


        user_app_home_game_list.setHasFixedSize(true);
        user_app_home_game_list.setNestedScrollingEnabled(false);
        user_app_home_game_list.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        AdpGcGameAppInfoList adpGcGameAppInfoList = new AdpGcGameAppInfoList(gameInfoListArrayList);
        adpGcGameAppInfoList.bindToRecyclerView(user_app_home_game_list);
    }

    @Override
    public void initData() {
        initDetailFromACache();
        initGameListFromACache();
        refreshData();
    }

    //从缓存获取用户主页详情
    private void initDetailFromACache() {
        UserFocus userFocus = DataUtil.getInstance().getCacheResult(ApiKey.getGameUserDetail(focus_user_id), UserFocus.class);
        checkData(userFocus);
    }

    //从网络获取用户主页详情
    private void initDetailFromNet() {
        SheepApp.getInstance().getNetComponent().getApiService().getGameUserDetail(focus_user_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.getGameUserDetail(focus_user_id));
                        if (isNewData) {
                            UserFocus userFocus = baseMessage.getData(UserFocus.class);
                            checkData(userFocus);
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        if (TestUtil.isDev()) G.showToast(baseMessage);
                    }
                });
    }

    //从缓存获取用户主页详情
    private void initGameListFromACache() {
        LatelyGame latelyGame = DataUtil.getInstance().getCacheResult(ApiKey.getGameUserLatelyGame(focus_user_id), LatelyGame.class);
        checkLatelyGame(latelyGame);
    }

    //从网络获取最近游戏与同类游戏
    private void initGameList() {
        SheepApp.getInstance().getNetComponent().getApiService().getGameUserLatelyGame(focus_user_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.getGameUserLatelyGame(focus_user_id));
                        if (isNewData) {
                            LatelyGame latelyGame = baseMessage.getData(LatelyGame.class);
                            checkLatelyGame(latelyGame);
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        if (TestUtil.isDev()) G.showToast(baseMessage);
                    }
                });
    }

    //检查数据
    private void checkLatelyGame(LatelyGame latelyGame) {
        if (latelyGame != null) {
            loadLatelyGame(latelyGame);
        }
    }

    private List<Applications> latelyGameList = ListUtil.emptyList();
    private List<Applications> sameGameList = ListUtil.emptyList();
    public static final String NAME_LATELY = "在玩的游戏";
    public static final String NAME_SAME = "同类游戏";

    //加载最近游戏与同类游戏
    private void loadLatelyGame(LatelyGame latelyGame) {
        reloadList(latelyGameList, latelyGame.getLately(), NAME_LATELY);
        reloadList(sameGameList, latelyGame.getSame(), NAME_SAME);
        user_app_home_game_list.getAdapter().notifyDataSetChanged();
    }

    //重新加载列表
    private void reloadList(List<Applications> list, List<Applications> addList, final String name) {
        list.clear();
        if (!ListUtil.isEmpty(addList)) {
            list.addAll(addList);
        }
        if (ListUtil.getItem(gameInfoListArrayList, new ListUtil.CallBack<GameInfoList, Boolean>() {
            @Override
            public Boolean call(GameInfoList gameInfoList) {
                return TextUtils.equals(gameInfoList.getName(), name);
            }
        }) == null) {
            gameInfoListArrayList.add(new GameInfoList(name, new AdpGcGameAppList(SheepApp.getInstance(), R.layout.item_gc_game_app_63, list)).setHorizontal().setShowBottomLine(true).setShowTopLine(false));
        }
    }

    //检查数据
    private void checkData(UserFocus userFocus) {
        if (userFocus == null) {
            resetView();
        } else {
            loadData(userFocus);
        }
    }

    //方块化一些包含具体数据的TextView控件
    private void resetView() {
        ViewUtil.setDefaultText(user_app_home_name);
        ViewUtil.setDefaultText(user_app_home_num_fans);
        ViewUtil.setDefaultText(user_app_home_num_focus_users);
        ViewUtil.setDefaultText(user_app_home_num_focus_games);
        ViewUtil.setDefaultText(user_app_home_num_like);
        ViewUtil.setDefaultText(user_app_home_focus);
    }

    private UserFocus userFocus;

    //加载数据
    private void loadData(UserFocus userFocus) {
        this.userFocus = userFocus;
        ViewUtil.setText(user_app_home_name, userFocus.getNick_name());
        ViewUtil.setAvatar(user_app_home_avatar, userFocus.getAvatar());
        ViewUtil.setBlur(user_app_home_bg, userFocus.getAvatar());
        ViewUtil.setText(user_app_home_num_fans, userFocus.getFan());
        ViewUtil.setText(user_app_home_num_focus_users, userFocus.getFocus_user());
        ViewUtil.setText(user_app_home_num_focus_games, userFocus.getFocus_game());
        updateLikeTv();
        updateFocusTv();
    }

    //更新点赞数量
    private void updateLikeTv() {
        ViewUtil.setText(user_app_home_num_like, userFocus.getLike());
    }

    //更新关注状态
    private void updateFocusTv() {
        ViewUtil.setText(user_app_home_focus, getString(userFocus.isIs_focus_user() ? R.string.has_focus : R.string.focus));
    }

    //refreshData调用次数
    private int refreshDataCount = 0;

    //刷新数据
    public void refreshData() {
        initDetailFromNet();
        initGameList();
        boolean isRefresh = false;
        if (refreshDataCount != 0) {
            Fragment item = mAdapter.getItem(viewPager.getCurrentItem());
            if (item instanceof IRefresh) {//可刷新，就调用当前fragment刷新数据
                ((IRefresh) item).refreshData();
                isRefresh = true;
            }
        }
        refreshDataCount++;
        if (!isRefresh)
            notifyDataSetChanged();
    }

    //加载更多数据
    private void loadMoreData() {
        Fragment item = mAdapter.getItem(viewPager.getCurrentItem());
        if (item instanceof ILoadMore) {//可加载更多，就调用当前fragment刷新数据
            ((ILoadMore) item).loadMoreData();
        } else {
            notifyDataSetChanged();
        }
    }

    //刷新完成
    private void notifyDataSetChanged() {
        if (refresh != null) {
            refresh.finishRefresh();
            refresh.finishLoadMore();
        }
    }

    //点击返回
    public void onClickBackImg(View view) {
        finish();
    }

    //点击分享
    public void onClickShareImg(View view) {
        //点击分享游戏
//        G.showToast(R.string.coming_soon);
//        FIND_SHARE.onEvent("application_id", id);
//        Jump2View.getInstance().tryShare(this, "find_share_url", "application_id", id);
        new ShareLinkConfig().toShare(this);
    }

    //点击赞
    public void onClickLike(final View view) {
        if (userFocus == null) {
            G.showToast(R.string.loading_data);
            return;
        }
        view.setEnabled(false);
        ApiUtil.postGameUserLike(focus_user_id, new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
            @Override
            public void onNext(BaseMessage baseMessage) {
                G.showToast(R.string.like_success);
                userFocus.plusLike();
                updateLikeTv();
                view.setEnabled(true);
                initDetailFromNet();//通过重新访问接口刷新数据
            }

            @Override
            public void onError(BaseMessage baseMessage) {
                G.showToast(R.string.like_fail);
                view.setEnabled(true);
            }
        });
    }

    //点击关注
    public void onClickFocus(final View view) {
        if (userFocus == null) {
            G.showToast(R.string.loading_data);
            return;
        }
        view.setEnabled(false);
        ApiUtil.postGameUserFocusUser(focus_user_id, new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
            @Override
            public void onNext(BaseMessage baseMessage) {
                G.showToast(userFocus.isIs_focus_user() ? R.string.cancel_focus_success : R.string.focus_success);
                userFocus.toggleFocusUser();
                updateFocusTv();
                view.setEnabled(true);
                initDetailFromNet();//通过重新访问接口刷新数据
            }

            @Override
            public void onError(BaseMessage baseMessage) {
                G.showToast(userFocus.isIs_focus_user() ? R.string.cancel_focus_fail : R.string.focus_fail);
                view.setEnabled(true);
            }
        });
    }
}
