package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.greendao.download.DownLoadInfo;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.OrienteeringDetail;
import com.sheep.gamegroup.model.entity.RecyleObj;
import com.sheep.gamegroup.model.entity.RecyleType;
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.ViewUtil;
import com.sheep.gamegroup.view.adapter.TryMakeMoneyAdp;
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 org.afinal.simplecache.ApiKey;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;
import java.util.Locale;

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

/**
 * Created by ljy on 2018/6/12.
 */

public class FgtMyGame extends BaseFragment {

    @BindView(R.id.empty_view_img)
    ImageView imgListEmpty;
    @BindView(R.id.empty_view_msg)
    TextView txtListEmpty;
    @BindView(R.id.recyclerview)
    XRecyclerView recyclerview;
    @BindView(R.id.empty_view)
    View empty_view;
    private Activity activity;
    private TryMakeMoneyAdp tryMakeMoneyAdp;
    private int page = 1;//页数
    private int per_page = DataUtil.PER_PAGE;
    private List<OrienteeringDetail> list = ListUtil.emptyList();
    private int type = 0;

    public static FgtMyGame newInstance(int type) {
        FgtMyGame fgtTryMakeMoney = new FgtMyGame();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        fgtTryMakeMoney.setArguments(bundle);
        return fgtTryMakeMoney;
    }

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

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

    @Subscribe
    public void initView() {

//        EventBus.getDefault().register(this);

        recyclerview.setLayoutManager(new LinearLayoutManager(activity));
        tryMakeMoneyAdp = new TryMakeMoneyAdp(activity);
        tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.NONE, null));
        recyclerview.setAdapter(tryMakeMoneyAdp);
        initListener();
        bottomLine = ViewUtil.setBottomLine(recyclerview);

    }

    private View bottomLine;

    public void initListener() {
        recyclerview.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                refreshData();
            }

            @Override
            public void onLoadMore() {
                if (ListUtil.size(list) >= per_page * page) {
                    page += 1;
                    refreshData();
                } else {
                    recyclerview.setNoMore(true);
                }
            }
        });
    }

    private void initData() {
        List<OrienteeringDetail> newList = DataUtil.getInstance().getCacheList(ApiKey.my_games, OrienteeringDetail.class);
        if (!ListUtil.isEmpty(newList)) {
            ListUtil.addAll(list, newList);
            notifyDataSetChanged();
        }
        refreshData();
    }

    private void refreshData() {
        SheepApp.getInstance().getNetComponent().getApiService().getMyGames(page, per_page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        list = baseMessage.getDataList(OrienteeringDetail.class);
                        notifyDataSetChanged();
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        G.showToast(baseMessage);
                        list.clear();
                        notifyDataSetChanged();
                    }
                });
    }

    private void notifyBottomLine(boolean noMore) {
        if (bottomLine != null) {
            int count = list.size();
            bottomLine.setVisibility(count == 0 ? View.INVISIBLE : View.VISIBLE);
            if (noMore) {
                final boolean isCanScrollToPosition = count > 10;//页数大于一页才显示点击回到顶部
                TextView bottom_line_text = bottomLine.findViewById(R.id.bottom_line_text);
                bottom_line_text.setText(isCanScrollToPosition ? "我是有底线的，点击我回到顶部" : "我是有底线的");
                bottomLine.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (isCanScrollToPosition)
                            recyclerview.scrollToPosition(0);
                    }
                });
            }
        }
    }

    private void checkAndInitView() {
        if (empty_view == null)
            empty_view = findViewById(R.id.empty_view);
    }

    private void notifyDataSetChanged() {
        checkAndInitView();
        boolean isEmpty = tryMakeMoneyAdp.isEmpty() && list.isEmpty();
        CommonUtil.getInstance().updateEmptyView(empty_view, isEmpty);
        if (!isEmpty) {
            tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.GAME_TASK, list), 0);
        }
        tryMakeMoneyAdp.refreshAdapter();
        recyclerview.refreshComplete();
        recyclerview.loadMoreComplete();

        notifyBottomLine(false);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            type = bundle.getInt("type", 0);
        }
        return rootView;
    }

    private int onResumeCount = 0;

    @Override
    public void onResume() {
        super.onResume();
        switch (onResumeCount) {
            case 0:
                initData();//第一次先加载缓存
                break;
            default:
                refreshData();
                break;
        }
        onResumeCount++;
    }

    //在这里处理任务执行中的状态，如进度进度条的刷新
    protected void running(DownLoadInfo task) {
        try {
            int p = task.getMPercent();    //任务进度百分比
            String speed = task.getAverageSpeed();    //转换单位后的下载速度，单位转换需要在配置文件中打开
            String url = task.getMDownloadUrl();
            TextView tvProgress = recyclerview.findViewWithTag(TryMakeMoneyAdp.PUBLIC_TAG_PREFIX_TEXTVIEW_LIST + url);
            if (tvProgress == null) {
                return;
            }
            tvProgress.setText(String.format(Locale.CHINA, "%d%%(%s)", Math.abs(p), speed));//添加下载速度

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void taskCancel(DownLoadInfo task) {
        try {
            String url = task.getMDownloadUrl();

            TextView tvProgress = recyclerview.findViewWithTag(TryMakeMoneyAdp.PUBLIC_TAG_PREFIX_TEXTVIEW_LIST + url);
            if (tvProgress == null) {
                return;
            }
            tvProgress.setText("已经取消");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void taskFail(DownLoadInfo task) {
        try {
            String url = task.getMDownloadUrl();

            TextView tvProgress = recyclerview.findViewWithTag(TryMakeMoneyAdp.PUBLIC_TAG_PREFIX_TEXTVIEW_LIST + url);
            if (tvProgress == null) {
                return;
            }
            tvProgress.setText("下载失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void taskComplete(DownLoadInfo task) {
        try {
            String url = task.getMDownloadUrl();
            TextView tvProgress = recyclerview.findViewWithTag(TryMakeMoneyAdp.PUBLIC_TAG_PREFIX_TEXTVIEW_LIST + url);
            if (tvProgress == null) {
                return;
            }
            tvProgress.setText("开始安装");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Subscribe
    public void onEventMainThread(BigEvent event) {
        if (event.getData() instanceof DownLoadInfo) {
            DownLoadInfo task = (DownLoadInfo) event.getData();
            switch (event.getEventTypes()) {
                case DOWNLOAD_RUNNING:
                    running(task);
                    break;
                case DOWNLOAD_STOP:
//                    taskStop(task);
                    break;
                case DOWNLOAD_COMPLETE:
                    taskComplete(task);
                    break;
                case DOWNLOAD_CANCEL:
                    taskCancel(task);
                    break;
                case DOWNLOAD_FAIL:
                    taskFail(task);
                    break;
            }
        }
    }

}
