package com.sheep.gamegroup.view.fragment;

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

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.sheep.gamegroup.di.components.DaggerFgtTryMakeMoneyComponent;
import com.sheep.gamegroup.di.modules.TryMakeMoneyModule;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.event.EventTypes;
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.RequestParamEty;
import com.sheep.gamegroup.model.entity.TaskAcceptedEty;
import com.sheep.gamegroup.model.entity.Release_task;
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.util.ViewUtil;
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.Collections;
import java.util.Comparator;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import rx.functions.Action1;


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

public class FgtTryMakeMoney extends BaseFragment implements TryMakeMoneyContract.View {
    @BindView(R.id.recyclerview)
    XRecyclerView view_list;
    @BindView(R.id.empty_view)
    View empty_view;

    @Inject
    TryMakeMoneyPresenter presenter;
    private Activity activity;
    private TryMakeMoneyAdp tryMakeMoneyAdp;
    private List<TaskAcceptedEty> acceptedEtyList = new ArrayList<>();
    private List<Release_task> releaseEtyLists = new ArrayList<>();
    private List<Release_task> releaseEtyListsBegin = new ArrayList<>();
    private List<Release_task> lastCacheReleaseEtyLists = new ArrayList<>();
    private List<Release_task> lastCacheReleaseEtyListsBegin = new ArrayList<>();
    private int about_to_begin = 0;
    private String show_type;//有值代表来自主页
    private boolean isFromHome = false;//来自主页
    private int is_succession;//0:一般任务 1:连续任务


    private static final int LIST_COUNT = 3;//tryMakeMoneyAdp 总共有3条数据
    private static final RecyleObj NULL = RecyleObj.make(RecyleType.NONE, null);//空数据
    private Comparator<Release_task> comparator = new Comparator<Release_task>() {
        @Override
        public int compare(Release_task item1, Release_task item2) {
            return item2.getLastNum1Or0() - item1.getLastNum1Or0();
        }
    };
    private void notifyDataSetChanged() {
        progress++;
        if(empty_view == null || view_list == null){
            return;
        }
        tryMakeMoneyAdp.clear();
        if (!ListUtil.isEmpty(acceptedEtyList))
            tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.RUN_TASK, acceptedEtyList));
        if (!ListUtil.isEmpty(releaseEtyLists)) {
            Collections.sort(releaseEtyLists, comparator);
            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();
        if(progress != 6 && showEmpty){
            //每次刷新数据有6处地方调用notifyDataSetChanged，progress都会+1，没有数据的情况下，没有到最后一步不调用空view
        } else {
            CommonUtil.getInstance().updateEmptyView(empty_view, showEmpty);
        }
        view_list.refreshComplete();
        view_list.loadMoreComplete();
        notifyBottomLine(false);
        if (isFromHome && isSelected)
            EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.FGT_SHEEP_REFRESH_H));
    }

    private void notifyBottomLine(boolean noMore) {
        if(bottomLine != null) {
            if (isFromHome){//主页不展示底线，用主页自带的底线
                bottomLine.setVisibility(View.GONE);
                return;
            }
            int count = getDataCount();
            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)
                            view_list.scrollToPosition(0);
                    }
                });
            }
        }
    }

    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) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            about_to_begin = bundle.getInt("type", 0);
            show_type = bundle.getString("show_type", "");
            isFromHome = !TextUtils.isEmpty(show_type);
            per_page = isFromHome ? 100 : per_page;//主页直接加载100条数据，不然会卡，待解决卡的问题后修改回去
            switch (show_type){
                case "is_hot":
                    isGetRelease = true;
                    break;
                case "about_to_begin":
                    isGetReleaseBegin = true;
                    break;
                default:
                    isGetRelease = true;
                    isGetReleaseBegin = true;
                    break;
            }
        }
        return rootView;
    }

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

    @Override
    public void onViewCreated() {
        activity = getActivity();
        initView();
        initListener();
        ViewUtil.refreshXrv(view_list);
//        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.getInstance().getNetComponent())
                .tryMakeMoneyModule(new TryMakeMoneyModule(FgtTryMakeMoney.this))
                .build()
                .inject(FgtTryMakeMoney.this);
        view_list.setLayoutManager(new LinearLayoutManager(activity));
        view_list.setHasFixedSize(true);
        view_list.setNestedScrollingEnabled(false);
        tryMakeMoneyAdp = new TryMakeMoneyAdp(activity);
        tryMakeMoneyAdp.addType(about_to_begin);
        tryMakeMoneyAdp.addShowType(show_type);
        tryMakeMoneyAdp.setIs_succession(getIs_succession());
        tryMakeMoneyAdp.addPresenter(presenter);
        for (int i = 0; i < LIST_COUNT; i++) {
            tryMakeMoneyAdp.add(NULL);
        }
        view_list.setAdapter(tryMakeMoneyAdp);

        bottomLine = ViewUtil.setBottomLine(view_list, isFromHome ? new Action1<String>() {
            @Override
            public void call(String msg) {
                if (isFromHome && isSelected)
                    EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.FGT_SHEEP_FOOT_VIEW_CALL_BACK).setData(msg));
            }
        } : null);

    }
    private View bottomLine;

    public void initListener() {
        view_list.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }

            @Override
            public void onLoadMore() {
                boolean noMoreRelease = true;
                boolean noMoreReleaseBegin = true;

                if(isGetRelease) {
                    if (ListUtil.size(releaseEtyLists) >= per_page * releasePage) {
                        releasePage += 1;
                        noMoreRelease = false;
                        //先加载缓存
                        getReleaseFromACache(0);
                        //再加载网络数据
                        getReleaseFromNetWork(0);
                    }
                }
                if(isGetReleaseBegin) {
                    if (ListUtil.size(releaseEtyListsBegin) >= per_page * releaseBeginPage) {
                        releaseBeginPage += 1;
                        noMoreReleaseBegin = false;
                        //先加载缓存
                        getReleaseFromACache(1);
                        //再加载网络数据
                        getReleaseFromNetWork(1);
                    }
                }
                if(noMoreRelease && noMoreReleaseBegin){
                    view_list.setNoMore(true);
                    noMore = true;
                    notifyBottomLine(true);
                    if (isFromHome)
                        EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.FGT_SHEEP_SET_BOTTOM_LINE));
                }
            }
        });
    }

    private boolean isFirstCache = false;//是否首先尝试缓存

    //先尝试缓存数据，无缓存数据时，再尝试获取网络数据
    public void initData() {
        isFirstCache = true;
        mInitData();
    }

    //强制刷新数据
    public void refreshData() {
        isFirstCache = false;
        noMore = false;
        if (isFromHome)
            EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.FGT_SHEEP_SET_BOTTOM_LINE));
        releasePage = 1;
        releaseBeginPage = 1;
        acceptedEtyList.clear();
        releaseEtyLists.clear();
        releaseEtyListsBegin.clear();
        mInitData();
    }

    private int releasePage = 1;
    private int releaseBeginPage = 1;
    private int per_page = DataUtil.PER_PAGE;
    //是否获取发布的任务列表
    private boolean isGetRelease = false;
    //是否获取即将开始的列表
    private boolean isGetReleaseBegin = false;

    private int progress = 0;//数据加载进度
    public void mInitData() {
        progress = 0;
        if (!acceptedEtyList.isEmpty()) {
            acceptedEtyList.clear();
            notifyDataSetChanged();
        }
        CommonUtil.getInstance().resetEmptyView(empty_view);
        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(getIs_succession(), 0), TaskAcceptedEty.class);
            }
            if (ListUtil.isEmpty(cacheTaskAcceptedEtyList)) {
                acceptedEtyList.clear();
            } else {
                acceptedEtyList = cacheTaskAcceptedEtyList;
                if (!ListUtil.isEmpty(acceptedEtyList)) {//清除时间数据，缓存数据不显示时间
                    for (TaskAcceptedEty taskAcceptedEty : acceptedEtyList) {
                        taskAcceptedEty.setEnd_time(0);
                    }
                }
            }
        }
        initAcceptedTaskList();
        if(isGetRelease) {
            //先加载缓存
            getReleaseFromACache(0);
            //再加载网络数据
            getReleaseFromNetWork(0);
        }
        if(isGetReleaseBegin) {
            //先加载缓存
            getReleaseFromACache(1);
            //再加载网络数据
            getReleaseFromNetWork(1);
        }
    }

    /**
     * 获取正在运行的任务
     */
    private void initAcceptedTaskList() {
        if (isGameTask) {
            presenter.runGameTask();
        } else if (TextUtils.isEmpty(show_type)) {
            presenter.returnTask(is_succession, 0);
        } else {//主页不加载数据
//            presenter.returnTask(3, 0);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // any time,when you finish your activity or fragment,call this below
        if(view_list != null){
            view_list.destroyDrawingCache(); // this will totally release XR's memory
            view_list = null;
        }
    }

    @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().updateAutoCheck(null);
        refreshData();
    }

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

    public int getIs_succession() {
        return isFromHome ? 3 : is_succession;
    }

    @Override
    public void returnTaskTaskUpdateView(Object object) {
        boolean isNewData = DataUtil.getInstance().isNewData(isGameTask ? ApiKey.run_game_task : ApiKey.new_run_task(getIs_succession(), 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();
    }

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

    /**
     * 获取已经发布任务
     *
     * @param baseMessage
     */
    @Override
    public void releaseTaskTaskUpdateView(BaseMessage baseMessage, int about_to_begin) {
        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.release_task(about_to_begin == 0 ? releasePage : releaseBeginPage, per_page, about_to_begin, task_type, getIs_succession()));
        if (isNewData) {
            List<Release_task> releaseEtyList = baseMessage.getDataList(Release_task.class);
            switch (about_to_begin) {
                case 0:
                    ListUtil.removeAll(releaseEtyLists, lastCacheReleaseEtyLists);
                    ListUtil.addAll(releaseEtyLists, releaseEtyList);
                    break;
                case 1:
                    ListUtil.removeAll(releaseEtyListsBegin, lastCacheReleaseEtyListsBegin);
                    ListUtil.addAll(releaseEtyListsBegin, releaseEtyList);
                    break;
            }
        }
        notifyDataSetChanged();
    }

    @Override
    public void failReleaseTask2View(BaseMessage baseMessage, int about_to_begin) {
        notifyDataSetChanged();
    }

    private int onResumeCount = 0;

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

    @Override
    public void onPause() {
        super.onPause();
        if (tryMakeMoneyAdp != null) {
            tryMakeMoneyAdp.cancelAllTimers();
        }
    }

    //从ACache获取发布的任务列表
    private void getReleaseFromACache(int about_to_begin) {
        try {
            List<Release_task> cacheTaskReleaseEtyList = DataUtil.getInstance().getCacheList(ApiKey.release_task(about_to_begin == 0 ? releasePage : releaseBeginPage, per_page, about_to_begin, task_type, getIs_succession()), Release_task.class);
            switch (about_to_begin) {
                case 0:
                    lastCacheReleaseEtyLists = cacheTaskReleaseEtyList;
                    ListUtil.addAll(releaseEtyLists, cacheTaskReleaseEtyList);
                    break;
                case 1:
                    lastCacheReleaseEtyListsBegin = cacheTaskReleaseEtyList;
                    ListUtil.addAll(releaseEtyListsBegin, cacheTaskReleaseEtyList);
                    break;
            }
            notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //从网络获取发布的任务列表
    private void getReleaseFromNetWork(int about_to_begin) {
        RequestParamEty paramEty = new RequestParamEty();
        paramEty.setHashMap(
                CommonUtil.getInstance()
                        .setHashMap(about_to_begin == 0 ? releasePage : releaseBeginPage,
                                per_page,
                                SheepApp.getInstance().getConnectAddress().getPlatForm(),
                                TextUtils.isEmpty(show_type) ? 0 : show_type.equals("is_hot") ? 1 : 0,
                                0,
                                about_to_begin,
                                task_type,
                                getIs_succession()));
        presenter.releaseTask(paramEty);
    }

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

    private boolean noMore = false;
    public boolean isNoMore() {
        return noMore;
    }
    private boolean isSelected = true;

    public void setSelected(boolean selected) {
        isSelected = selected;
    }
}
