package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
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.scwang.smartrefresh.layout.SmartRefreshLayout;
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.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.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 java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * Created by realicing on 2018/10/10.
 * realicing@sina.com
 * 主页发布的任务列表或者即将开始的任务列表
 */
public class FgtHomeTaskReleaseList extends BaseFragment implements TryMakeMoneyContract.View {
    @BindView(R.id.view_list)
    RecyclerView 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() {
        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();
        updateEmptyView();
        refreshOrLoadMoreComplete();
        resetViewPagerHeight();
    }


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

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

    public FgtHomeTaskReleaseList() {
    }

    @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);
            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.net_empty_rv;
    }

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

    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(FgtHomeTaskReleaseList.this))
                .build()
                .inject(FgtHomeTaskReleaseList.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);

    }

    public void initListener() {
    }

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

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

    //强制刷新数据
    public void refreshData() {
        isFirstCache = false;
        noMore = false;
        releasePage = 1;
        releaseBeginPage = 1;
        acceptedEtyList.clear();
        releaseEtyLists.clear();
        releaseEtyListsBegin.clear();
        mInitData();
    }


    public void loadMoreData() {
        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){
            noMore = true;
            if(smartRefreshLayout != null && getUserVisibleHint()) {
                smartRefreshLayout.setNoMoreData(noMore);
            }
        }
        notifyDataSetChanged();
    }
    private int releasePage = 1;
    private int releaseBeginPage = 1;
    private int per_page = DataUtil.PER_PAGE;
    //是否获取发布的任务列表
    private boolean isGetRelease = false;
    //是否获取即将开始的列表
    private boolean isGetReleaseBegin = false;

    public void mInitData() {
        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) {
            if(presenter != null)
                presenter.runGameTask();
        } else if (TextUtils.isEmpty(show_type)) {
            if(presenter != null)
                presenter.returnTask(is_succession, 0);
        } else {//主页不加载数据
//            presenter.returnTask(3, 0);
        }
    }

    @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.addAllItem(releaseEtyLists, releaseEtyList);
                    break;
                case 1:
                    ListUtil.removeAll(releaseEtyListsBegin, lastCacheReleaseEtyListsBegin);
                    ListUtil.addAllItem(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.addAllItem(releaseEtyLists, cacheTaskReleaseEtyList);
                    break;
                case 1:
                    lastCacheReleaseEtyListsBegin = cacheTaskReleaseEtyList;
                    ListUtil.addAllItem(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()));
        if(presenter != null)
            presenter.releaseTask(paramEty);
    }

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

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


    //加载完成时更新header或footer
    protected void refreshOrLoadMoreComplete() {
        if(smartRefreshLayout != null && getUserVisibleHint()) {
            if (releasePage == 1) {
                smartRefreshLayout.finishRefresh();
            } else {
                smartRefreshLayout.finishLoadMore();
            }
        }
    }
    //重新设置ViewPager的高度
    protected void resetViewPagerHeight() {
        if(viewPager != null && getUserVisibleHint()){
            int count = getDataCount();
            ViewGroup.LayoutParams params = viewPager.getLayoutParams();
            params.height = count == 0 ? G.HEIGHT / 2 : (count * getItemHeight()) + getResources().getDimensionPixelSize(R.dimen.content_padding);
//            LogUtil.println("resetViewPagerHeight", count, about_to_begin, show_type, getItemHeight(), params.height);
            viewPager.setLayoutParams(params);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        resetViewPagerHeight();
        if(smartRefreshLayout != null && getUserVisibleHint()) {
            smartRefreshLayout.setNoMoreData(noMore);
        }
    }
    protected int getItemHeight(){
        return SheepApp.getInstance().getResources().getDimensionPixelSize(R.dimen.content_padding_96);
    }

    //是否显示无数据占位图
    protected void updateEmptyView(){
        boolean showEmpty = acceptedEtyList.isEmpty() && releaseEtyLists.isEmpty() && releaseEtyListsBegin.isEmpty();
        CommonUtil.getInstance().updateEmptyView(empty_view, showEmpty);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        view_list = null;
        viewPager = null;
        smartRefreshLayout = null;
    }

    protected ViewPager viewPager;
    protected SmartRefreshLayout smartRefreshLayout;

    public ViewPager getViewPager() {
        return viewPager;
    }

    public void setViewPager(ViewPager viewPager) {
        this.viewPager = viewPager;
    }

    public SmartRefreshLayout getSmartRefreshLayout() {
        return smartRefreshLayout;
    }

    public void setSmartRefreshLayout(SmartRefreshLayout smartRefreshLayout) {
        this.smartRefreshLayout = smartRefreshLayout;
    }
}
