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.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.kfzs.duanduan.event.BigEvent;
import com.kfzs.duanduan.event.EventTypes;
import com.sheep.gamegroup.di.components.DaggerFgtTryMakeMoneyComponent;
import com.sheep.gamegroup.di.modules.TryMakeMoneyModule;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.RecyleObj;
import com.sheep.gamegroup.model.entity.RecyleType;
import com.sheep.gamegroup.model.entity.RequestParameEty;
import com.sheep.gamegroup.model.entity.TaskAcceptedEty;
import com.sheep.gamegroup.model.entity.TaskReleaseEty;
import com.sheep.gamegroup.presenter.TryMakeMoneyContract;
import com.sheep.gamegroup.presenter.TryMakeMoneyPresenter;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.view.activity.GamemakeMoneyAct;
import com.sheep.gamegroup.view.activity.TryMakeMoneyact;
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.EventBus;

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

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * 试玩赚钱
 * Created by ljy on 2018/4/26.
 */

public class FgtTryMakeMoney extends BaseFragment implements TryMakeMoneyContract.View{
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.empty_view)
    View empty_view;
    Unbinder unbinder;

    @Inject
    TryMakeMoneyPresenter presenter;
    private Activity activity;
    private TryMakeMoneyAdp tryMakeMoneyAdp;
    private List<TaskAcceptedEty> acceptedEtyList = new ArrayList<>();
    private List<TaskReleaseEty> releaseEtyLists = new ArrayList<>();
    private List<TaskReleaseEty> releaseEtyListsBegin = new ArrayList<>();
    private int type = 0;
    private String show_type;
    private int is_succession;//0:一般任务 1:连续任务

    private void checkAndInitView() {
        if(refresh == null)
            refresh = findViewById(R.id.refresh);
        if(empty_view == null)
            empty_view = findViewById(R.id.empty_view);
    }
    private static final int LIST_COUNT = 3;//tryMakeMoneyAdp 总共有3条数据
    private static final RecyleObj NULL = RecyleObj.make(RecyleType.NONE, null);//空数据
    private void notifyDataSetChanged(){
        checkAndInitView();
        tryMakeMoneyAdp.clear();
        if(!ListUtil.isEmpty(acceptedEtyList))
            tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.RUN_TASK, acceptedEtyList));
        if(!ListUtil.isEmpty(releaseEtyLists))
            tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.RELEASE_TASK, releaseEtyLists));
        if(!ListUtil.isEmpty(releaseEtyListsBegin))
            tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.BEGIN_TASK, releaseEtyListsBegin));
        tryMakeMoneyAdp.refreshAdapter();
        boolean showEmpty = acceptedEtyList.isEmpty() && releaseEtyLists.isEmpty() && releaseEtyListsBegin.isEmpty();
        CommonUtil.getInstance().updateEmptyView(empty_view, showEmpty);
        refresh.setRefreshing(false);
        if(!TextUtils.isEmpty(show_type))
            EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.FGT_SHEEP_REFRESH_H));
    }
    public static FgtTryMakeMoney newInstance(int type){
        FgtTryMakeMoney fgtTryMakeMoney = new FgtTryMakeMoney();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        fgtTryMakeMoney.setArguments(bundle);
        return fgtTryMakeMoney;
    }
    public static FgtTryMakeMoney newInstance(int type,String show_type){
        FgtTryMakeMoney fgtTryMakeMoney = new FgtTryMakeMoney();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        bundle.putString("show_type", show_type);
        fgtTryMakeMoney.setArguments(bundle);
        return fgtTryMakeMoney;
    }

    public FgtTryMakeMoney() {
    }

    @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);
            show_type = bundle.getString("show_type", "");
        }
        return rootView;
    }

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

    @Override
    public void onViewCreated() {
        activity = getActivity();
        initView();
        initData();
    }
    private String task_type = "-1";
    private boolean isGameTask = false;
    public void initView() {
        if(activity == null){
            return;
        }
        if(activity instanceof TryMakeMoneyact) {//试玩任务、连续任务
            is_succession = ((TryMakeMoneyact) activity).getIsSuccession();
            task_type = "-1";
            isGameTask = false;
        } else if(activity instanceof GamemakeMoneyAct) {//游戏任务
            is_succession = ((GamemakeMoneyAct) activity).getIsSuccession();
            task_type = "1002,1003,1004";
            isGameTask = true;
        }
        DaggerFgtTryMakeMoneyComponent.builder()
                .netComponent(SheepApp.get(activity).getNetComponent())
                .tryMakeMoneyModule(new TryMakeMoneyModule(FgtTryMakeMoney.this))
                .build()
                .inject(FgtTryMakeMoney.this);
        recyclerview.setLayoutManager(new LinearLayoutManager(activity));
        tryMakeMoneyAdp = new TryMakeMoneyAdp(activity);
        tryMakeMoneyAdp.addType(type);
        tryMakeMoneyAdp.addShowType(show_type);
        tryMakeMoneyAdp.setIs_succession(TextUtils.isEmpty(show_type)?is_succession:3);
        tryMakeMoneyAdp.addPresenter(presenter);
        for (int i = 0; i < LIST_COUNT; i++) {
            tryMakeMoneyAdp.add(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 boolean isFirstCache = false;//是否首先尝试缓存
    //先尝试缓存数据，无缓存数据时，再尝试获取网络数据
    public void initData(){
        isFirstCache = true;
        mInitData();
    }
    //强制刷新数据
    public void refreshData(){
        isFirstCache = false;
        if(TextUtils.isEmpty(show_type))
            if(refresh != null)
                refresh.setRefreshing(true);
        mInitData();
    }
    public void mInitData() {
        if(!acceptedEtyList.isEmpty()) {
            acceptedEtyList.clear();
            notifyDataSetChanged();
        }
        CommonUtil.getInstance().resetEmptyView(empty_view);
        //加载缓存
        if(TextUtils.isEmpty(show_type))
            type = 0;
        if(isFirstCache){
            //注释掉获取缓存的正在进行的任务
            List<TaskAcceptedEty> cacheTaskAcceptedEtyList;
            if(isGameTask) {
                cacheTaskAcceptedEtyList = DataUtil.getInstance().getCacheList(ApiKey.run_game_task, TaskAcceptedEty.class);
            } else {
                cacheTaskAcceptedEtyList = DataUtil.getInstance().getCacheList(ApiKey.new_run_task(TextUtils.isEmpty(show_type)?is_succession:3, 0), TaskAcceptedEty.class);
            }
            if (ListUtil.isEmpty(cacheTaskAcceptedEtyList)) {
                acceptedEtyList.clear();
            } else {
                acceptedEtyList = cacheTaskAcceptedEtyList;
                if(!ListUtil.isEmpty(acceptedEtyList)){//清除时间数据，缓存数据不显示时间
                    for (TaskAcceptedEty taskAcceptedEty : acceptedEtyList) {
                        taskAcceptedEty.setEnd_time(0);
                    }
                }
            }
            getFromACache(type);
        }
        //加载网络数据
        if(TextUtils.isEmpty(show_type))//这里为
            type = 0;
        getFromNetWork(type);
    }

    /**
     * 获取正在运行的任务
     */
    private void initAcceptedTaskList() {
        if(isGameTask){
            presenter.runGameTask();
        } else if(!TextUtils.isEmpty(show_type)){

        }
        else {
            presenter.returnTask(TextUtils.isEmpty(show_type)?is_succession:3, 0);
        }
    }

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

    @Override
    public void updateData2View(Object o) {

    }

    @Override
    public void failData2View(Object o) {

    }

    @Override
    public void acceptedTaskUpdataView(Object o) {

    }

    @Override
    public void failAcceptedTask2View(Object o) {
        try {
            BaseMessage baseMessage = (BaseMessage) o;
            switch (baseMessage.getCode()){
                case 300://未查询到数据
                    G.showToast(" 未查询到数据！");
                    break;
                default:
                    G.showToast(" 网络错误！");
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
            G.showToast(" 网络错误！");
        }
    }

    @Override
    public void giveUpTaskSuccesView(Object object) {
        G.showToast("取消任务成功");
        CommonUtil.getInstance().setTAskEnty(null);
        refreshData();
    }

    @Override
    public void giveUpTaskFailView(Object o) {
        try {
            BaseMessage baseMessage = (BaseMessage) o;
            G.showToast(baseMessage.getMsg()+"");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void returnTaskTaskUpdataView(Object object) {
        boolean isNewData = DataUtil.getInstance().isNewData(isGameTask ? ApiKey.run_game_task : ApiKey.new_run_task(TextUtils.isEmpty(show_type)?is_succession:3, 0));
        if(isNewData) {
            if (object instanceof BaseMessage) {
                List<TaskAcceptedEty> taskAcceptedEty = ((BaseMessage) object).getDataList(TaskAcceptedEty.class);
                if (ListUtil.isEmpty(taskAcceptedEty)) {
                    acceptedEtyList.clear();
                } else {
                    acceptedEtyList.clear();
                    acceptedEtyList.addAll(taskAcceptedEty);
                }
                notifyDataSetChanged();
            }
        }
        refresh.setRefreshing(false);
    }

    @Override
    public void failReturnTask2View(Object object) {
        if(!acceptedEtyList.isEmpty()) {
            acceptedEtyList.clear();
            notifyDataSetChanged();
        }
        refresh.setRefreshing(false);
    }

    /**
     *  获取已经发布任务
     * @param object
     */
    @Override
    public void releaseTaskTaskUpdataView(Object object) {
        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.release_task(type, task_type, TextUtils.isEmpty(show_type)?is_succession:3));
        if(isNewData && object instanceof BaseMessage) {
            List<TaskReleaseEty> releaseEtyList = ((BaseMessage) object).getDataList(TaskReleaseEty.class);
            switch (type) {
                case 0:
                    releaseEtyLists.clear();
                    releaseEtyLists.addAll(releaseEtyList);
                    break;
                case 1:
                    releaseEtyListsBegin.clear();
                    releaseEtyListsBegin.addAll(releaseEtyList);
                    break;
            }
            notifyDataSetChanged();
        }
        getFromNetWorkFirst(type);
    }

    @Override
    public void failReleaseTask2View(Object object) {
        switch (type){
            case 0:
                releaseEtyLists.clear();
                break;
            case 1:
                releaseEtyListsBegin.clear();
                break;
        }
        notifyDataSetChanged();
        getFromNetWorkFirst(type);
    }

    private int onResumeCount = 0;
    @Override
    public void onResume() {
        super.onResume();
        if (onResumeCount > 0 && presenter != null){//直接全部刷新
            refreshData();
        }
        onResumeCount++;
    }

    @Override
    public void onPause() {
        super.onPause();
        if(tryMakeMoneyAdp != null){
            tryMakeMoneyAdp.cancelAllTimers();
        }
    }
    /**
     * 发布的任务
     * type: 0 1
     */
    private void getFromACacheFirst(int type){
        if(TextUtils.isEmpty(show_type)){
            this.type = ++type;
            getFromACache(this.type);
        }
    }
    private void getFromACache(int type){
        try {
            if(type > 1){
                return;
            }
            List<TaskReleaseEty> cacheTaskReleaseEtyList = DataUtil.getInstance().getCacheList(ApiKey.release_task(type, task_type, TextUtils.isEmpty(show_type)?is_succession:3), TaskReleaseEty.class);
            switch (type){
                case 0:
                    if(cacheTaskReleaseEtyList == null) {
                        releaseEtyLists.clear();
                    } else {
                        releaseEtyLists.clear();
                        releaseEtyLists.addAll(cacheTaskReleaseEtyList);
                        notifyDataSetChanged();
                        getFromACacheFirst(type);
                    }
                    break;
                case 1:
                    if(cacheTaskReleaseEtyList == null) {
                        releaseEtyListsBegin.clear();
                    } else {
                        releaseEtyListsBegin.clear();
                        releaseEtyListsBegin.addAll(cacheTaskReleaseEtyList);
                        notifyDataSetChanged();
                        getFromACacheFirst(type);
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 发布的任务
     * type: 0 1
     */
    private void getFromNetWorkFirst(int type){
        if(TextUtils.isEmpty(show_type)){
            this.type = ++type;
            getFromNetWork(this.type);
        }
    }
    private void getFromNetWork(int type){
        if(type > 1){
            initAcceptedTaskList();
            return;
        }
        RequestParameEty parameEty = new RequestParameEty();
        parameEty.setHashMap(
                CommonUtil.getInstance()
                        .setHashMap(1,
                                100,
                                SheepApp.getInstance().getConnectAddress().getPlatForm(),
                                TextUtils.isEmpty(show_type)?0:show_type.equals("is_hot")?1:0,
                                0,
                                type,
                                task_type,
                                TextUtils.isEmpty(show_type)?is_succession:3));
        presenter.releaseTask(parameEty);
    }

    public int getDataCount() {
        return acceptedEtyList.size() + releaseEtyLists.size() + releaseEtyListsBegin.size();
    }
}
