package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kfzs.appstore.utils.adapter.recyclerview.RecyclerViewAdapter;
import com.kfzs.appstore.utils.adapter.recyclerview.ViewHolder;
import com.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.gamegroup.absBase.BaseRefreshLoadMoreFragment;
import com.sheep.gamegroup.helper.ImageListHelper;
import com.sheep.gamegroup.model.entity.AppInfoExtDetail;
import com.sheep.gamegroup.model.entity.Applications;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.Entry;
import com.sheep.gamegroup.model.entity.GameEntity;
import com.sheep.gamegroup.model.entity.GameInfoList;
import com.sheep.gamegroup.model.entity.ShowAll;
import com.sheep.gamegroup.model.entity.UserComment;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.TextViewUtil;
import com.sheep.gamegroup.util.TimeUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.AdpGcGameAppComment;
import com.sheep.gamegroup.view.adapter.AdpGcGameAppInfoList;
import com.sheep.gamegroup.view.adapter.AdpGcGameAppList;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import rx.functions.Action1;

/**
 * Created by realicing on 2018/11/1.
 * realicing@sina.com
 * 玩转游戏 详情
 */
public class FgtGcGameAppDetail extends BaseRefreshLoadMoreFragment implements Action1<List<UserComment>>{
    @BindView(R.id.gc_game_app_detail_pic_list)
    RecyclerView gc_game_app_detail_pic_list;
    @BindView(R.id.gc_game_app_detail_info_list)
    RecyclerView recyclerView;

    public static FgtGcGameAppDetail newInstance(int appId) {
        FgtGcGameAppDetail fgt = new FgtGcGameAppDetail();
        fgt.appId = appId;
        return fgt;
    }

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


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

    @Override
    public void onViewCreated() {
        ImageListHelper.initList(getActivity(), gc_game_app_detail_pic_list, pictureList);
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        recyclerView.setAdapter(new AdpGcGameAppInfoList(gameInfoListArrayList));
        refreshData();
    }

    //ActGcGameAppDetail调用该方法传入对应的游戏数据
    public void loadData(final GameEntity gameEntity) {
        if(gc_game_app_detail_pic_list == null){
            Observable.just(1).delay(100L, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new AbsObserver<Integer>() {
                        @Override
                        public void onNext(Integer integer) {
                            loadData(gameEntity);
                        }
                    });
            return;
        }
        Applications gameApp;
        if (gameEntity == null || (gameApp = gameEntity.getApp()) == null)
            return;
        ListUtil.removeItem(gameInfoListArrayList, new ListUtil.CallBack<GameInfoList, Boolean>() {
            @Override
            public Boolean call(GameInfoList gameInfoList) {
                return SORT_GAME_INTRO == gameInfoList.getSort() || SORT_GAME_INFO == gameInfoList.getSort();
            }
        });
        //游戏图片banner
        String pictures = gameApp.getPictures();
        if (!TextUtils.isEmpty(pictures)) {
            pictureList.clear();
            ListUtil.addAll(pictureList, pictures.split(";"));
            ListUtil.removeNull(pictureList);
            ViewUtil.setVisibility(gc_game_app_detail_pic_list, true);
            ViewUtil.notifyDataSetChanged(gc_game_app_detail_pic_list);
        } else {
            ViewUtil.setVisibility(gc_game_app_detail_pic_list, false);
        }
        String intro = gameApp.getIntro();
        if (!TextUtils.isEmpty(intro)) {
            gameInfoListArrayList.add(new GameInfoList("游戏介绍", new RecyclerViewAdapter<ShowAll>(SheepApp.getInstance(), R.layout.item_gc_game_app_intro, ListUtil.asList(new ShowAll(intro))) {
                @Override
                public void convert(ViewHolder viewHolder, ShowAll showAll, int position) {
                    TextViewUtil.initIntroView(viewHolder.itemView, showAll);
                }
            }).setSort(SORT_GAME_INTRO));
        }
        final List<Entry<String, String>> entryList = ListUtil.emptyList();
        entryList.add(new Entry<>("当前版本", gameApp.getVersions()));
        entryList.add(new Entry<>("大小", gameApp.getPackage_size()));
        entryList.add(new Entry<>("更新日期", TimeUtil.TimeStamp2Date(gameApp.getUpdated_at(), "yyyy-MM-dd")));
        entryList.add(new Entry<>("发行商", gameApp.getManufacturer()));

        if(gameApp.getExt_detail() != null) {
            try {
                List<AppInfoExtDetail> list = JSONObject.parseArray(gameApp.getExt_detail(), AppInfoExtDetail.class);
                if (!ListUtil.isEmpty(list)) {
                    for (AppInfoExtDetail item : list) {
                        try {
                            entryList.add(new Entry<>(item.getTitle(), item.getValue()));
                        } catch (Exception e) {
                            e.printStackTrace();
                            if(TestUtil.isDev())
                                G.showToast(e.getMessage());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                if(TestUtil.isDev())
                    G.showToast(e.getMessage());
            }
        }
        gameInfoListArrayList.add(new GameInfoList("详细信息", new RecyclerViewAdapter<Entry<String, String>>(SheepApp.getInstance(), R.layout.item_gc_game_info, entryList) {
            @Override
            public void convert(ViewHolder viewHolder, Entry<String, String> item, int position) {
                View item_gc_game_info_top = viewHolder.itemView.findViewById(R.id.item_gc_game_info_top);
                TextView item_gc_game_info_key = viewHolder.itemView.findViewById(R.id.item_gc_game_info_key);
                TextView item_gc_game_info_value = viewHolder.itemView.findViewById(R.id.item_gc_game_info_value);
                View item_gc_game_info_bottom = viewHolder.itemView.findViewById(R.id.item_gc_game_info_bottom);
                ViewUtil.setVisibility(item_gc_game_info_top, position == 0);
                ViewUtil.setVisibility(item_gc_game_info_bottom, position + 1 == entryList.size());
                ViewUtil.setText(item_gc_game_info_key, item.getK());
                ViewUtil.setText(item_gc_game_info_value, item.getV());
            }
        }).setSort(SORT_GAME_INFO));
        Collections.sort(gameInfoListArrayList);
        ViewUtil.notifyDataSetChanged(recyclerView);
    }

    //加载相关游戏与热门试玩数据列表
    private void initData(final int sort, final String name, Observable<BaseMessage> observable) {
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        ArrayList<Applications> newList = baseMessage.getDataList(Applications.class);
                        if (!ListUtil.isEmpty(newList)) {
                            gameInfoListArrayList.add(new GameInfoList(name, new AdpGcGameAppList(SheepApp.getInstance(), R.layout.item_gc_game_app_63, newList)).setHorizontal().setSort(sort));
                            Collections.sort(gameInfoListArrayList);
                            ViewUtil.notifyDataSetChanged(recyclerView);
                        }
                        refreshOrLoadMoreComplete();
                    }

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

    private int appId;


    @Override
    public void loadMoreData() {
        setNoMore(true);
        refreshOrLoadMoreComplete();
    }

    @Override
    public void refreshData() {
        ListUtil.removeItem(gameInfoListArrayList, new ListUtil.CallBack<GameInfoList, Boolean>() {
            @Override
            public Boolean call(GameInfoList gameInfoList) {
                return gameInfoList.getSort() == SORT_GAME_RELEVANT || gameInfoList.getSort() == SORT_GAME_HOT;
            }
        });
        initData(SORT_GAME_RELEVANT, "相关游戏", SheepApp.getInstance().getNetComponent().getApiService().getDetailRelevantGames(appId));
        initData(SORT_GAME_HOT, "热门试玩", SheepApp.getInstance().getNetComponent().getApiService().getDetailHotGames(appId));
    }

    //评论列表数据
    private List<UserComment> userCommentList = ListUtil.emptyList();
    public static final int MAX_USER_COMMENT_NUM = 2;//最多显示评论的个数
    @Override
    public void call(List<UserComment> userComments) {
        userCommentList.clear();
        if(userComments != null) {
            for (int i = 0; i < userComments.size(); i++) {
                if(i < MAX_USER_COMMENT_NUM)
                    userCommentList.add(userComments.get(i));
                else
                    break;
            }
        }

        GameInfoList item = ListUtil.getItem(gameInfoListArrayList, new ListUtil.CallBack<GameInfoList, Boolean>(){

            @Override
            public Boolean call(GameInfoList gameInfoList) {
               return gameInfoList.getSort() == SORT_USER_COMMENT;
            }
        });
        if(item == null) {
            gameInfoListArrayList.add(new GameInfoList("用户评价", new AdpGcGameAppComment(userCommentList)).setSort(SORT_USER_COMMENT));
            Collections.sort(gameInfoListArrayList);
        }
        ViewUtil.notifyDataSetChanged(recyclerView);
    }

    //游戏介绍
    public static final int SORT_GAME_INTRO = 1;
    //详细信息
    public static final int SORT_GAME_INFO = 2;
    //用户评价
    public static final int SORT_USER_COMMENT = 3;
    //相关游戏
    public static final int SORT_GAME_RELEVANT = 4;
    //热门试玩
    public static final int SORT_GAME_HOT = 5;
}
