package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.kfzs.appstore.utils.adapter.recyclerview.RecyclerViewAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.GameEntity;
import com.sheep.gamegroup.model.entity.GameListTag;
import com.sheep.gamegroup.model.entity.GameListType;
import com.sheep.gamegroup.model.entity.GameRecommend;
import com.sheep.gamegroup.model.entity.ListTypeList;
import com.sheep.gamegroup.model.entity.SlideshowEty;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.ObservableUtil;
import com.sheep.gamegroup.util.RefreshUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.AdpGameCenter1_2List;
import com.sheep.gamegroup.view.adapter.AdpGameCenter3_3List;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.base.BaseFragment;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.afinal.simplecache.ApiKey;

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

import butterknife.BindView;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by realicing on 2018/10/30.
 * realicing@sina.com
 */
public class FgtPlayGame extends BaseFragment {
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.play_game_act)
    RecyclerView play_game_act;
    @BindView(R.id.play_game_list_3_rv)
    RecyclerView play_game_list_3_rv;
    @BindView(R.id.play_game_list_2_rv)
    RecyclerView play_game_list_2_rv;
    @BindView(R.id.play_game_list_x_rv)
    RecyclerView play_game_list_x_rv;
    @BindView(R.id.refresh)
    SmartRefreshLayout refresh;
    Unbinder unbinder;

    private Activity activity;
    //游戏首页活动列表
    private List<SlideshowEty> gameActList = new ArrayList<>();
    //每日必玩", "近期最热", "猜你喜欢
    private List<GameListType> gameListTypeList3 = new ArrayList<>();
    private List<ListTypeList<GameEntity, GameListType>> gameEntityList3 = new ArrayList<>();
    //天天更新与重点推荐
    private List<GameListType> gameListTypeList2 = new ArrayList<>();
    private List<ListTypeList<GameRecommend, GameListType>> gameListTypeList2List = new ArrayList<>();
    //预下载和tag列表的数据
    private List<ListTypeList<GameEntity, GameListType>> gameEntityListx = new ArrayList<>();
    private List<SlideshowEty> slideshowEtyLists = new ArrayList<>();
    private List<String> slideshowTitleList = new ArrayList<>();


    @Override
    public int getLayoutId() {
        return R.layout.fgt_play_game;
    }

    public static final int[] gameActBgIds = {R.drawable.shape_purple_gradient_solid_rectangle_5, R.drawable.shape_orange_gradient_solid_rectangle_5, R.drawable.shape_light_blue_gradient_solid_rectangle_5};

    @Override
    public void onViewCreated() {
        activity = getActivity();

        //banner
        LinearLayout.LayoutParams bannerLayoutParams = (LinearLayout.LayoutParams) banner.getLayoutParams();
        bannerLayoutParams.height = G.WIDTH * 25 / 72;
        banner.setLayoutParams(bannerLayoutParams);

        //游戏首页活动列表
        LinearLayoutManager playGameActManager = new LinearLayoutManager(SheepApp.getInstance(), LinearLayoutManager.HORIZONTAL, false);
        play_game_act.setHasFixedSize(true);
        play_game_act.setNestedScrollingEnabled(false);
        play_game_act.setLayoutManager(playGameActManager);
        play_game_act.setAdapter(new RecyclerViewAdapter<SlideshowEty>(SheepApp.getInstance(), R.layout.item_game_act, gameActList) {
            @Override
            public void convert(com.kfzs.appstore.utils.adapter.recyclerview.ViewHolder viewHolder, final SlideshowEty item, int position) {
                View item_game_act_start = viewHolder.itemView.findViewById(R.id.item_game_act_start);
                View item_game_act_content = viewHolder.itemView.findViewById(R.id.item_game_act_content);
                View item_game_act_end = viewHolder.itemView.findViewById(R.id.item_game_act_end);
                ImageView item_game_act_iv = viewHolder.itemView.findViewById(R.id.item_game_act_iv);
                TextView item_game_act_tv = viewHolder.itemView.findViewById(R.id.item_game_act_tv);
                ViewUtil.setVisibility(item_game_act_start, position == 0);
                ViewUtil.setVisibility(item_game_act_end, position + 1 == gameActList.size());
                item_game_act_content.setBackgroundResource(gameActBgIds[position % gameActBgIds.length]);
                if (item == null) {
                    ViewUtil.setDefaultText(item_game_act_tv);
                } else {
                    ViewUtil.setImage(item_game_act_iv, item.getUrl());
                    ViewUtil.setText(item_game_act_tv, item.getTitle());
                }
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            CommonUtil.getInstance().clickBanner(activity, item);
                        } catch (Exception e) {
                            G.showToast(e.getMessage());
                        }
                    }
                });

            }
        });

        //每日必玩、近期最热、猜你喜欢
        play_game_list_3_rv.setHasFixedSize(true);
        play_game_list_3_rv.setNestedScrollingEnabled(false);
        play_game_list_3_rv.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        play_game_list_3_rv.setAdapter(new AdpGameCenter3_3List(activity, gameEntityList3).setShowFirstTop(false));
        //天天更新、重点推荐
        play_game_list_2_rv.setHasFixedSize(true);
        play_game_list_2_rv.setNestedScrollingEnabled(false);
        play_game_list_2_rv.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        play_game_list_2_rv.setAdapter(new AdpGameCenter1_2List(activity, gameListTypeList2List));
        //预下载与其它列表
        play_game_list_x_rv.setHasFixedSize(true);
        play_game_list_x_rv.setNestedScrollingEnabled(false);
        play_game_list_x_rv.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        play_game_list_x_rv.setAdapter(new AdpGameCenter3_3List(activity, gameEntityListx));

        refresh.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData();
            }
        });
        RefreshUtil.newInstance().publicParameter(refresh, activity);
        initGameListType3List();
        initGameListType2List();
        if(refresh != null)
            refresh.autoRefresh();
    }

    public static final String[] gameListType3Titles = {"每日必玩", "近期最热", "猜你喜欢"};
    public static final int[] gameListType3IsHots = {1, 0, 0};
    public static final int[] gameListType3DailyPlays = {0, 1, 0};

    private void initGameListType3List() {
        //每日必玩", "近期最热", "猜你喜欢
        for (int i = 0; i < gameListType3Titles.length; i++) {
            GameListType gameListType = new GameListType();
            gameListType.setTitle(gameListType3Titles[i]);
            gameListType.setPer_page(20);
            gameListType.setIs_hot(gameListType3IsHots[i]);
            gameListType.setDaily_play(gameListType3DailyPlays[i]);
            gameListTypeList3.add(gameListType);
        }
    }

    public static final String[] gameListType2Titles = {"天天更新", "重点推荐"};
    public static final int[] gameListType2DisplayTypes = {1, 2};

    private void initGameListType2List() {
        //天天更新", "重点推荐
        for (int i = 0; i < gameListType2Titles.length; i++) {
            GameListType gameListType = new GameListType();
            gameListType.setTitle(gameListType2Titles[i]);
            gameListType.setDisplay_type(gameListType2DisplayTypes[i]);
            gameListTypeList2.add(gameListType);
        }
    }

    private void refreshData() {
        initBanner();
        initBannerAct();
        initGameList3();
        initRecommendList();
        initGameTagList();
    }

    private void initBannerAct() {
        gameActList.clear();
        ViewUtil.notifyDataSetChanged(play_game_act);
        SheepApp.getInstance().getNetComponent().getApiService().gameBannerAct()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        ArrayList<SlideshowEty> newList = baseMessage.getDataList(SlideshowEty.class);
                        if (!ListUtil.isEmpty(newList)) {
                            gameActList.addAll(newList);
                        }
                        ViewUtil.notifyDataSetChanged(play_game_act);
                        notifyDataSetChanged();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        notifyDataSetChanged();
                    }
                });
    }

    //天天更新、重点推荐
    private void initRecommendList() {
        gameListTypeList2List.clear();
        ViewUtil.notifyDataSetChanged(play_game_list_2_rv);
        Observable.fromIterable(gameListTypeList2)
                .subscribe(new AbsObserver<GameListType>() {
                    @Override
                    public void onNext(final GameListType gameListType) {
                        SheepApp.getInstance().getNetComponent().getApiService().getRecommendList(gameListType.getDisplay_type())
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                                    @Override
                                    public void onNext(BaseMessage baseMessage) {
                                        List<GameRecommend> newList = baseMessage.getDatas(GameRecommend.class);
                                        if (!ListUtil.isEmpty(newList)) {
                                            gameListTypeList2List.add(new ListTypeList<>(gameListType, newList));
                                            ViewUtil.notifyDataSetChanged(play_game_list_2_rv);
                                            notifyDataSetChanged();
                                        }
                                    }

                                    @Override
                                    public void onError(BaseMessage baseMessage) {
                                        notifyDataSetChanged();
                                    }
                                });
                    }
                });
    }

    //预下载下面的tagList
    private void initGameTagList() {
        gameEntityListx.clear();
        ViewUtil.notifyDataSetChanged(play_game_list_x_rv);
        //预下载
        GameListType gameListType = new GameListType();
        gameListType.setTitle("预下载");
        gameListType.setDownload_type(GameListType.T_DOWNLOAD_TYPE_YES);
        initGameList(play_game_list_x_rv, gameEntityListx, gameListType);
        //其它tag
        SheepApp.getInstance().getNetComponent().getApiService().getGameTagList()
                .subscribeOn(Schedulers.io())
                .flatMap(new Function<BaseMessage, Observable<GameListTag>>() {
                    @Override
                    public Observable<GameListTag> apply(BaseMessage baseMessage) throws Exception {
                        ArrayList<GameListTag> gameListTagList = baseMessage.getDataList(GameListTag.class);
                        return Observable.fromIterable(gameListTagList);
                    }
                })
                .filter(new Predicate<GameListTag>() {
                    @Override
                    public boolean test(GameListTag gameListTag) {
                        return gameListTag != null;
                    }
                })
                .subscribe(new AbsObserver<GameListTag>() {

                    @Override
                    public void onNext(GameListTag gameListTag) {
                        initGameList(play_game_list_x_rv, gameEntityListx, gameListTag.toGameListType());
                    }
                });
    }

    //刷新banner数据
    private void initBanner() {
        //轮播
        List<SlideshowEty> cacheSlideshowEtyList = DataUtil.getInstance().getCacheList(ApiKey.slideshowGame, SlideshowEty.class);
        if (ListUtil.isEmpty(cacheSlideshowEtyList)) {
            banner.setVisibility(View.GONE);
        } else {
            slideshowEtyLists.clear();
            slideshowTitleList.clear();
            for (SlideshowEty slideshowEty : cacheSlideshowEtyList) {
                slideshowEtyLists.add(slideshowEty);
                slideshowTitleList.add(slideshowEty.getTitle());
            }
            bindBanner();
        }

        SheepApp.getInstance().getNetComponent().getApiService().gameBanner(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onError(BaseMessage baseMessage) {
                        notifyDataSetChanged();
                    }

                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.slideshowGame);
                        if (isNewData) {
                            List<SlideshowEty> slideshowEtyList = baseMessage.getDataList(SlideshowEty.class);
                            if (ListUtil.isEmpty(slideshowEtyList)) {
                                banner.setVisibility(View.GONE);
                            } else {
                                slideshowEtyLists.clear();
                                slideshowTitleList.clear();
                                for (SlideshowEty slideshowEty : slideshowEtyList) {
                                    slideshowEtyLists.add(slideshowEty);
                                    slideshowTitleList.add(slideshowEty.getTitle());
                                }
                                bindBanner();
                            }
                        }
                        notifyDataSetChanged();
                    }
                });
    }

    private void bindBanner() {
        //结束轮播
        banner.stopAutoPlay();
        banner.setVisibility(View.VISIBLE);
        //设置图片加载器
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object o, ImageView imageView) {
                if (o instanceof SlideshowEty)
                    Glide.with(context).load(((SlideshowEty) o).getUrl()).apply(new RequestOptions().dontAnimate()).into(imageView);
            }
        })
                .setDelayTime(4000)
                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE)
                //设置图片集合
                .setImages(slideshowEtyLists).setBannerTitles(slideshowTitleList)
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int i) {
                        try {
                            CommonUtil.getInstance().clickBanner(activity, i, slideshowEtyLists);
                        } catch (Exception e) {
                            G.showToast(e.getMessage());
                        }
                    }
                });

        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }

    @Override
    public void onStart() {
        super.onStart();
        //结束轮播
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }

    //刷新每日必玩、近期最热、猜你喜欢的数据
    private void initGameList3() {
        gameEntityList3.clear();
        Observable.fromIterable(gameListTypeList3)
                .subscribe(new AbsObserver<GameListType>() {

                    @Override
                    public void onNext(final GameListType gameListType) {
                        initGameList(play_game_list_3_rv, gameEntityList3, gameListType);
                    }
                });
    }

    private void initGameList(final RecyclerView playGameListRv, final List<ListTypeList<GameEntity, GameListType>> gameEntityListList, final GameListType gameListType) {
        if (gameListType == null) {
            return;
        }
        ObservableUtil.getObservable(SheepApp.getInstance().getNetComponent().getApiService(), gameListType).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        List<GameEntity> newList = baseMessage.getDatas(GameEntity.class);
                        if (!ListUtil.isEmpty(newList)) {
                            gameEntityListList.add(new ListTypeList<>(gameListType, newList));
                            ViewUtil.notifyDataSetChanged(playGameListRv);
                        }
                        notifyDataSetChanged();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        notifyDataSetChanged();
                    }
                });
    }

    private void notifyDataSetChanged() {
        if (refresh != null) {
            refresh.finishRefresh();
        }
    }
}
