package com.sheep.gamegroup.view.fragment;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;

import com.kfzs.appstore.utils.adapter.recyclerview.RecyclerViewAdapter;
import com.kfzs.appstore.utils.adapter.recyclerview.ViewHolder;
import com.sheep.gamegroup.model.api.ApiService;
import com.sheep.gamegroup.model.entity.AppScoreDetail;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.Applications;
import com.sheep.gamegroup.model.entity.UserComment;
import com.sheep.gamegroup.model.entity.GameAppScore;
import com.sheep.gamegroup.model.entity.GameEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.ApiJSONUtil;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.AdpGcGameAppComment;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;

import java.text.DecimalFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import cn.modificator.waterwave_progress.WaterWaveProgress;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by realicing on 2018/11/1.
 * realicing@sina.com
 * 玩转游戏 评价
 */
public class FgtGcGameAppComment extends BaseListFragment3<UserComment> {


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

    private int app_id;
    private int type = ApiJSONUtil.COMMENT_TYPE_GAME;

    private List<GameAppScore> scoreList = ListUtil.emptyList();
    //头部view
    private View headerView;
    private WaterWaveProgress circularProgressView;
    private RatingBar header_gc_game_app_comment_score;
    private RecyclerView header_gc_game_app_comment_xin_list;

    @Override
    protected RecyclerView.Adapter getAdapter() {
        //头部
        headerView = LayoutInflater.from(SheepApp.getInstance()).inflate(R.layout.header_gc_game_app_comment, null);
        circularProgressView = headerView.findViewById(R.id.header_gc_game_app_comment_score_progress);
        header_gc_game_app_comment_score = headerView.findViewById(R.id.header_gc_game_app_comment_score);

        //评分列表
        resetGameAppScoreNum();
        header_gc_game_app_comment_xin_list = headerView.findViewById(R.id.header_gc_game_app_comment_xin_list);
        header_gc_game_app_comment_xin_list.setHasFixedSize(true);
        header_gc_game_app_comment_xin_list.setNestedScrollingEnabled(false);
        header_gc_game_app_comment_xin_list.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        header_gc_game_app_comment_xin_list.setAdapter(new RecyclerViewAdapter<GameAppScore>(SheepApp.getInstance(), R.layout.item_xin_progress, scoreList) {
            @Override
            public void convert(ViewHolder viewHolder, GameAppScore item, int position) {
                TextView item_xin_progress_tv = viewHolder.itemView.findViewById(R.id.item_xin_progress_tv);
                ProgressBar item_xin_progress = viewHolder.itemView.findViewById(R.id.item_xin_progress);
                ViewUtil.setText(item_xin_progress_tv, item.getStar());
                item_xin_progress.setProgress(item.getNum());
                item_xin_progress.setMax(item.getMax());
            }
        });

        //评论列表
        AdpGcGameAppComment adapter = new AdpGcGameAppComment(list);
        adapter.addHeaderView(headerView);
        return adapter;
    }

    @Override
    protected String getKey(int page, int per_page) {
        return String.format(Locale.CHINA, "app/game_user/app_comment_list?page_no=%d&page_size=%d&app_id=%d&comment_type=%d", page, per_page, app_id, type);
    }

    @Override
    protected Observable<BaseMessage> getApi(ApiService apiService) {
        return apiService.getGameUserAppCommentList(page, per_page, app_id, type);
    }

    private Action1<List<UserComment>> listAction1;

    public void setListAction1(Action1<List<UserComment>> listAction1) {
        this.listAction1 = listAction1;
    }

    @Override
    protected void loadList(List<UserComment> addList) {
        super.loadList(addList);
        if(listAction1 != null && page == 1 && !ListUtil.isEmpty(addList))
            listAction1.call(addList);
    }

    @Override
    protected Class<UserComment> getTClass() {
        return UserComment.class;
    }

    //不会用到了，因为评分系统重新做了一套，以前的没用了
    public void loadData(GameEntity gameEntity) {
        Applications gameApp;
        if ((gameApp = gameEntity.getApp()) != null) {
            updateScore(gameApp.getScore());
        }
    }

    //更新评分
    public void updateScore(float score) {
        int progress = (int) score;
        //显示评分
        if (circularProgressView != null) {
            circularProgressView.setMaxProgress(10);
            circularProgressView.setProgress(progress);
            circularProgressView.setText(new DecimalFormat("0.0").format(score));
        }
        if (header_gc_game_app_comment_score != null) {
            header_gc_game_app_comment_score.setMax(10);
            header_gc_game_app_comment_score.setProgress(progress);
        }
    }

    @Override
    public void refreshData() {
        initAppScoreNum();
        super.refreshData();
    }

    //评分排序方法
    private Comparator<GameAppScore> scoreComparable = new Comparator<GameAppScore>() {
        @Override
        public int compare(GameAppScore item1, GameAppScore item2) {
            return item2.getStar() - item1.getStar();
        }
    };

    //加载评分列表
    private void initAppScoreNum() {
        scoreList.clear();
        notifyHeaderDataSetChanged();
        SheepApp.getInstance().getNetComponent().getApiService().getGameUserAppScoreDetail(app_id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        scoreList.clear();
                        AppScoreDetail appScoreDetail = baseMessage.getData(AppScoreDetail.class);
                        if (appScoreDetail != null) {
                            updateScore(appScoreDetail.getScore());
                            List<GameAppScore> newScoreList = appScoreDetail.toGameAppScoreList();
                            if (ListUtil.isEmpty(newScoreList))
                                resetGameAppScoreNum();
                            else {
                                scoreList.addAll(newScoreList);
                                Collections.sort(scoreList, scoreComparable);
                            }
                        }
                        notifyHeaderDataSetChanged();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        resetGameAppScoreNum();
                        notifyHeaderDataSetChanged();
                        updateScore(10);//默认10分
                    }
                });
    }

    //刷新头部view
    private void notifyHeaderDataSetChanged() {
        if (header_gc_game_app_comment_xin_list != null)
            header_gc_game_app_comment_xin_list.getAdapter().notifyDataSetChanged();

        if (empty_view != null) {
            empty_view.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (headerView != null) {
                        int height = headerView.getHeight();
                        CommonUtil.getInstance().setEmptyViewMargin(empty_view, (int) (height * 0.9), (int) (height * 0.3));
                    }
                }
            }, 100L);
        }
    }

    //重置评分列表
    private void resetGameAppScoreNum() {
        for (int i = 0; i < 5; i++) {//5星满分
            GameAppScore item = new GameAppScore();
            item.setNum(0);
            item.setStar(5 - i);
            scoreList.add(item);
        }
    }

}
