package com.sheep.gamegroup.view.fragment;

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

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.download.DownloadTask;
import com.kfzs.duanduan.utils.ApkUtils;
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.view.adapter.TryMakeMoneyAdp;
import com.sheep.gamegroup.view.customview.SheepmSwipeRefreshLayout;
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 butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.android.schedulers.AndroidSchedulers;
import rx.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)
    RecyclerView recyclerview;
    @BindView(R.id.refresh)
    SheepmSwipeRefreshLayout refresh;
    @BindView(R.id.empty_view)
    View empty_view;
    Unbinder unbinder;
    private Activity activity;
    private TryMakeMoneyAdp tryMakeMoneyAdp;
    private int page = 1;//页数
    private int per_page = 100;
    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();

    }

    public void initListener() {
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });
        recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                int topRowVerticalPosition =
                        (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();

                refresh.setEnabled(topRowVerticalPosition >= 0);
            }
        });
    }

    private void initData() {
        refresh.setRefreshing(true);
        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 checkAndInitView() {
        if(refresh == null)
            refresh = findViewById(R.id.refresh);
        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();
        refresh.setRefreshing(false);
    }

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

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

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

    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning protected void running(DownloadTask task) {
//        downloadTaskService.setDownloadTaskPercent(p, task.getCurrentProgress()/1024d/1024d,task.getFileSize()/1024d/1024d,0,task.getKey());
        try {
            int p = task.getPercent();    //任务进度百分比
            String speed = task.getConvertSpeed();    //转换单位后的下载速度，单位转换需要在配置文件中打开
            System.out.println("Aria "+task.getKey()+",p " + p + ", speed = " + speed);
            String url = task.getKey();
            TextView tvProgress = recyclerview.findViewWithTag(TryMakeMoneyAdp.PUBLIC_TAG_PREFIX_TEXTVIEW_LIST + url);
            if (tvProgress == null) {
                return;
            }
            tvProgress.setText(String.format(Locale.CHINA, "%d%%",Math.abs(p)));

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

    @Download.onTaskStop void taskStop(DownloadTask task) {
    }

    @Download.onNoSupportBreakPoint void onNoSupportBreakPoint(DownloadTask task) {
    }

    @Download.onTaskCancel void taskCancel(DownloadTask task) {
//        downloadTaskService.deleteDownloadTaskByDownloadUrl(task.getKey());
        try {
            String url = task.getKey();

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

    @Download.onTaskFail void taskFail(DownloadTask task) {
        try {
            String url = task.getKey();

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

    @Download.onTaskComplete void taskComplete(DownloadTask task) {
        try {
            String url = task.getKey();
            TextView tvProgress = recyclerview.findViewWithTag(TryMakeMoneyAdp.PUBLIC_TAG_PREFIX_TEXTVIEW_LIST + url);
            if (tvProgress == null) {
                return;
            }
            tvProgress.setText("开始安装");
        } catch (Exception e) {
            e.printStackTrace();
        }
        ApkUtils.installApk(activity, task.getDownloadPath());
    }
}
