package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
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.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.FindTag;
import com.sheep.gamegroup.model.entity.GameEntity;
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.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.ViewHolder;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.AdbCommonRecycler;
import com.sheep.gamegroup.view.adapter.TitleFragmentListAdapter;
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 org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

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

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_GAME_OTHER;
import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_GAME_SHEEP;
import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_GAME_TECENT;
import static com.sheep.gamegroup.model.entity.TaskEty.TASK_TYPE_GAME_XIAO_MI;
import static com.sheep.gamegroup.view.adapter.PlayGameListAdapter.setOnClickGameEntity;

/**
 * Created by ljy on 2018/9/3.
 */

public class FgtPlayGame extends BaseFragment {
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.every_day_more_tv)
    TextView everyDayMoreTv;
    @BindView(R.id.every_day_play_list)
    RecyclerView everyDayPlayList;
    @BindView(R.id.recent_hot_more_tv)
    TextView recentHotMoreTv;
    @BindView(R.id.recent_hoe_list)
    RecyclerView recentHoeList;
    @BindView(R.id.tabLayout)
    TabLayout indicator;
    @BindView(R.id.viewpager_act_game_details)
    ViewPager pager;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.bottom_line_text)
    TextView bottom_line_text;
    Unbinder unbinder;

    public static final int WHAT_UPDATE_VP_HEIGHT = 1;//刷新viewpager高度
    public static final int WHAT_UPDATE_BOTTOM_LINE = 3;//刷新底线（双击我回到顶部）
    public static final int WHAT_UPDATE_FOOT_VIEW_CALL_BACK = 4;//刷新发布任务列表的加载更多的状态回调
    private Activity activity;
    private List<GameEntity> everyDayPlayListData = new ArrayList<>();
    private List<GameEntity> hotListData = new ArrayList<>();

    private List<SlideshowEty> slideshowEtyLists = new ArrayList<>();
    private List<String> slideshowTitleList = new ArrayList<>();

    private List<FindTag> list = ListUtil.emptyList();
    private TitleFragmentListAdapter mAdapter;
    private int curPosition = 0;

    Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            FgtPlayGameSon item;
            switch (msg.what) {
                case WHAT_UPDATE_VP_HEIGHT:
                    item = (FgtPlayGameSon) mAdapter.getItem(curPosition);
                    if (pager == null || item == null) {
                        return;
                    }
                    int count = item.getDataCount();
                    item.setNoFresh();
                    ViewGroup.LayoutParams params = pager.getLayoutParams();
                    params.height = count == 0 ? G.HEIGHT / 2 : (count * getResources().getDimensionPixelSize(R.dimen.content_padding_96) + getResources().getDimensionPixelSize(R.dimen.frg_app_details_icon));
                    pager.setLayoutParams(params);
                case WHAT_UPDATE_FOOT_VIEW_CALL_BACK://发布任务列表的加载更多的回调
                    if(msg.obj instanceof String) {
                        String obj = (String) msg.obj;
                        switch (obj) {
                            case "onLoadingMore":
                                bottom_line_text.setText("羊羊努力加载中...");
                                break;
                            case "onLoadMoreComplete":
                                bottom_line_text.setText("上拉下载更多，双击我回到顶部");
                                break;
                            case "onSetNoMore":
                                break;
                        }
                    }
                    break;
                case WHAT_UPDATE_BOTTOM_LINE://刷新底线
                    item = (FgtPlayGameSon) mAdapter.getItem(curPosition);
                    if (mAdapter == null || item == null) {
                        return;
                    }
                    bottom_line_text.setText(item.isNoMore() ?"我是有底线的，双击我回到顶部" : "双击我回到顶部");
                    break;
            }
        }
    };

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

    @Override
    public void onViewCreated() {
        activity = getActivity();
        EventBus.getDefault().register(this);

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

        //每日必玩、近期最热
        LinearLayoutManager playHotManager = new LinearLayoutManager(SheepApp.getInstance(), LinearLayoutManager.HORIZONTAL, false);
        //每日必玩
        everyDayPlayList.setHasFixedSize(true);
        everyDayPlayList.setNestedScrollingEnabled(false);
        everyDayPlayList.setLayoutManager(playHotManager);
        everyDayPlayList.setAdapter(new AdbCommonRecycler<GameEntity>(SheepApp.getInstance(), everyDayPlayListData) {
            @Override
            public int getViewIdByType(int type) {
                return R.layout.item_hot_welfare;
            }

            @Override
            public void convert(ViewHolder holder, GameEntity welfareCenter) {
                ImageView item_hot_welfare_iv =  holder.itemView.findViewById(R.id.item_hot_welfare_iv);
                TextView item_hot_welfare_tv = holder.itemView.findViewById(R.id.item_hot_welfare_tv);
                if(welfareCenter == null){
                    ViewUtil.setDefaultText(item_hot_welfare_tv);
                } else {
                    // 加载数据
                    ViewUtil.setText(item_hot_welfare_tv, welfareCenter.getApp().getName());
                    GlideImageLoader.setGameImage(item_hot_welfare_iv, welfareCenter.getApp().getIcon());
                    setOnClickGameEntity(activity, holder.itemView, welfareCenter);
                }
            }
        });
        //近期最热
        LinearLayoutManager hotManager = new LinearLayoutManager(SheepApp.getInstance(), LinearLayoutManager.HORIZONTAL, false);
        recentHoeList.setHasFixedSize(true);
        recentHoeList.setNestedScrollingEnabled(false);
        recentHoeList.setLayoutManager(hotManager);
        recentHoeList.setAdapter(new AdbCommonRecycler<GameEntity>(SheepApp.getInstance(), hotListData) {
            @Override
            public int getViewIdByType(int type) {
                return R.layout.item_hot_welfare;
            }

            @Override
            public void convert(ViewHolder holder, GameEntity welfareCenter) {
                ImageView item_hot_welfare_iv = holder.itemView.findViewById(R.id.item_hot_welfare_iv);
                TextView item_hot_welfare_tv = holder.itemView.findViewById(R.id.item_hot_welfare_tv);
                if(welfareCenter == null){
                    ViewUtil.setDefaultText(item_hot_welfare_tv);
                } else {
                    // 加载数据
                    ViewUtil.setText(item_hot_welfare_tv, welfareCenter.getApp().getName());
                    GlideImageLoader.setGameImage(item_hot_welfare_iv, welfareCenter.getApp().getIcon());
                    setOnClickGameEntity(activity, holder.itemView, welfareCenter);
                }
            }
        });
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
            }
        });

        mAdapter = new TitleFragmentListAdapter(getChildFragmentManager());

        //tab
        initTab();
    }

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

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

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    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) {
                        CommonUtil.getInstance().clickBanner(activity,i, slideshowEtyLists);
                    }
                });

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

    private void initData(){

        //轮播
        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) {
                slideshowEty.setObjects(CommonUtil.getInstance().getValue(slideshowEty.getExt()));
                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) {
                                    slideshowEty.setObjects(CommonUtil.getInstance().getValue(slideshowEty.getExt()));
                                    slideshowEtyLists.add(slideshowEty);
                                    slideshowTitleList.add(slideshowEty.getTitle());
                                }
                                bindBanner();
                            }
                        }
                        notifyDataSetChanged();
                    }
                });

        //每日必玩
        SheepApp.getInstance().getNetComponent().getApiService().playgameDailyOrHotOrTypePlay(1, 10, 0,1,0)
                .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)) {//有缓存时不会加载，没有缓存时获取到数据会加载
                            everyDayPlayListData.clear();
                            everyDayPlayListData.addAll(newList);
                            everyDayPlayList.getAdapter().notifyDataSetChanged();
                            notifyDataSetChanged();
                        }
                    }

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

        //近期最热
        SheepApp.getInstance().getNetComponent().getApiService().playgameDailyOrHotOrTypePlay(1, 10, 1,0,0)
                .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)) {//有缓存时不会加载，没有缓存时获取到数据会加载
                            hotListData.clear();
                            hotListData.addAll(newList);
                            recentHoeList.getAdapter().notifyDataSetChanged();
                            notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        notifyDataSetChanged();
                    }
                });
    }
    private void notifyDataSetChanged() {
        refresh.setRefreshing(false);
    }

    /**
     * tab
     * @param
     */
    private void initTab(){
        List<FindTag> newList = new ArrayList<>();
        newList.add(new FindTag(TASK_TYPE_GAME_SHEEP, "平台游戏"));
        newList.add(new FindTag(TASK_TYPE_GAME_XIAO_MI, "小米游戏"));
        newList.add(new FindTag(TASK_TYPE_GAME_TECENT, "腾讯游戏"));
        newList.add(new FindTag(TASK_TYPE_GAME_OTHER, "其他"));
        if (!ListUtil.isEmpty(newList)) {
            list.clear();
            ListUtil.addAll(list, newList);
            int i = 0;
            for(FindTag findTag:list){
                FgtPlayGameSon item = FgtPlayGameSon.newInstance(findTag.getId());
                item.setSelected(i == 0);//默认选中第一个
                mAdapter.add(item, findTag.getName());
                i++;
            }
            pager.setAdapter(mAdapter);
            indicator.setupWithViewPager(pager);
            pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int i, float v, int i1) {

                }

                @Override
                public void onPageSelected(int i) {
//                    FIND_TAG.onEvent("find_tag_name", ListUtil.hasIndex(list, i - 1) );
                    FgtPlayGameSon lastItem = (FgtPlayGameSon) mAdapter.getItem(curPosition);
                    curPosition = i;
                    FgtPlayGameSon item = (FgtPlayGameSon) mAdapter.getItem(curPosition);
                    lastItem.setSelected(false);
                    item.setSelected(true);
                    mHandler.sendEmptyMessage(WHAT_UPDATE_VP_HEIGHT);//重新计算viewpager高度
                }

                @Override
                public void onPageScrollStateChanged(int i) {

                }
            });
            CommonUtil.getInstance().reflex(indicator, activity);
//            pager.setOffscreenPageLimit(mAdapter.getCount());
            notifyDataSetChanged();
        }
    }

    @OnClick({R.id.every_day_more_tv, R.id.recent_hot_more_tv, R.id.bottom_line})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.every_day_more_tv:
                Jump2View.getInstance().goEverydayOrCurrentHotGame(activity, 0);
                break;
            case R.id.recent_hot_more_tv:
                Jump2View.getInstance().goEverydayOrCurrentHotGame(activity, 1);
                break;
            case R.id.bottom_line://我是有底线的，双击我回到顶部
                scrollView.fullScroll(NestedScrollView.FOCUS_UP);
                break;
        }
    }
    @Subscribe
    public void onEventMainThread(BigEvent event) {
        switch (event.getEventTypes()) {
            case FGT_PLAY_GAME_REFRESH_H:
                mHandler.sendEmptyMessage(WHAT_UPDATE_VP_HEIGHT);
                break;
            case FGT_PLAY_GAME_FOOT_VIEW_CALL_BACK:
                Message msg = Message.obtain();
                msg.what = WHAT_UPDATE_FOOT_VIEW_CALL_BACK;
                msg.obj = event.getData();
                if(msg.obj != null)
                    mHandler.sendMessage(msg);
                break;
            case FGT_PLAY_GAME_SET_BOTTOM_LINE:
                mHandler.sendEmptyMessage(WHAT_UPDATE_BOTTOM_LINE);
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }
}
