package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.content.Intent;
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 com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kfzs.duanduan.event.BigEvent;
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.GridViewEntity;
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.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 com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

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 int position = 0;
    private List<TaskReleaseEty> releaseEtyLists = new ArrayList<>();
    private int type = 0;
    private GridViewEntity gridViewEntity;//选中的
    private int is_succession;//0:一般任务 1:连续任务

    private void notifyDataSetChanged(){
        tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.RELEASE_TASK, releaseEtyLists),position);
        tryMakeMoneyAdp.refreshAdapter();
        if(tryMakeMoneyAdp.isEmpty() && releaseEtyLists.isEmpty()){

            empty_view.setVisibility(View.VISIBLE);
        }
        refresh.setRefreshing(false);
    }
    public static FgtTryMakeMoney newInstance(int type){
        FgtTryMakeMoney fgtTryMakeMoney = new FgtTryMakeMoney();
        Bundle bundle = new Bundle();
        bundle.putInt("type", 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);
        }
        return rootView;
    }

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

    @Override
    public void onViewCreated() {

        initView();
    }


//    @Override
//    protected void initView(Bundle savedInstanceState) {
//
//        setContentView(R.layout.fgt_try_makemoney_layout);
//        initView();
//        initListener();
//    }
    public void initView() {
        is_succession = ((TryMakeMoneyact)getActivity()).getIsSuccession();//0:一般任务 1:连续任务
        EventBus.getDefault().register(this);
        activity = getActivity();
//        ButterKnife.bind(this, mContentView);
        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);
        for (int i = 0; i < 2; i++) {
            tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.NONE, null));
        }
        recyclerview.setAdapter(tryMakeMoneyAdp);

        initListener();

    }

    public void initListener() {
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
            }
        });
        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);
            }
        });
    }
    public void reFresh(){
//        if(refresh.isRefreshing()){
//            return;
//        }
        refresh.setRefreshing(true);
        initData();
    }
    public void initData() {
        empty_view.setVisibility(View.GONE);
        position = 0;
        releaseEtyLists.clear();
        tryMakeMoneyAdp.clear();
        tryMakeMoneyAdp.addType(type);
        for (int i = 0; i < 2; i++) {
            tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.NONE, null));
        }
        tryMakeMoneyAdp.setTaskAcceptedEty(null);
        tryMakeMoneyAdp.setIs_succession(is_succession);
        gridViewEntity = ((TryMakeMoneyact)getActivity()).getTabValue();
        RequestParameEty parameEty = new RequestParameEty();
        parameEty.setHashMap(
                CommonUtil.getInstance()
                        .setHashMap(1,
                                100,
                                1,
                                0,
                                0,
                                type==2 ? 1 : type,
                                gridViewEntity == null ? -1 :gridViewEntity.getId(),
                                ((TryMakeMoneyact)getActivity()).getIsSuccession()));
        presenter.releaseTask(parameEty);
    }

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

        EventBus.getDefault().unregister(this);
    }

    @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 o) {
        G.showToast("取消任务成功");
        CommonUtil.getInstance().setTAskEnty(null);
        reFresh();
    }

    @Override
    public void giveUpTaskFailView(Object o) {
        G.showToast("访问失败");
    }

    @Override
    public void returnTaskTaskUpdataView(Object o) {

        try{
            position = 0;
            BaseMessage baseMessage = (BaseMessage) o;
            List<TaskAcceptedEty> taskAcceptedEty = JSONArray.parseArray(JSONArray.toJSONString(baseMessage.getData()), TaskAcceptedEty.class);
            if(taskAcceptedEty != null && taskAcceptedEty.size()>0){
                tryMakeMoneyAdp.add(RecyleObj.make(RecyleType.RUN_TASK, taskAcceptedEty),position);
                tryMakeMoneyAdp.addPresenter(presenter);
                position ++;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        notifyDataSetChanged();
    }

    @Override
    public void failReturnTask2View(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(" 网络错误！");
        }
        notifyDataSetChanged();
    }

    /**
     *  获取已经发布任务
     * @param o
     */
    @Override
    public void releaseTaskTaskUpdataView(Object o) {
        try{
            position = 0;
            BaseMessage baseMessage = (BaseMessage) o;
            List<TaskReleaseEty> releaseEtyList = JSONArray.parseArray(JSONArray.toJSONString(baseMessage.getData()), TaskReleaseEty.class);
            if(releaseEtyList != null){
                releaseEtyLists.addAll(releaseEtyList);
            }

//            mhandler.sendEmptyMessage(0);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(type == 2){
            notifyDataSetChanged();
        }else {
            CommonUtil.getInstance()
                    .getRunTask(presenter,
                            ((TryMakeMoneyact)getActivity()).getIsSuccession());
        }

    }

    @Override
    public void failReleaseTask2View(Object o) {

        if(type == 2){
            notifyDataSetChanged();
        }else {
            CommonUtil.getInstance()
                    .getRunTask(presenter,
                            ((TryMakeMoneyact)getActivity()).getIsSuccession());
        }
    }

    @Subscribe
    public void onEventMainThread(BigEvent event){
        switch (event.getEventTypes()){
            case ONFRESH_TRYMAKEMANY_PAGE:
//                reFresh();
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    /**
     * 滚动到顶部
     */
    private boolean move;
    private String string = "0";
    private void goTop(){
        final LinearLayoutManager manager = (LinearLayoutManager) recyclerview.getLayoutManager();
        int fir = manager.findFirstVisibleItemPosition();
        int end = manager.findLastVisibleItemPosition();
        final int p = Integer.parseInt(string);
        if (p <= fir) {
            recyclerview.scrollToPosition(p);
        } else if (p <= end) {
            int top = recyclerview.getChildAt(p - fir).getTop();
            recyclerview.scrollBy(0, top);
        } else {
            recyclerview.scrollToPosition(p);    //先让当前view滚动到列表内
            move = true;
        }
        recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener()
        {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (move) {
                    move = false;
                    int n = p - manager.findFirstVisibleItemPosition();
                    if (n >= 0 && n < recyclerView.getChildCount()) {
                        recyclerView.scrollBy(0, recyclerView.getChildAt(n).getTop()); //滚动到顶部
                    }
                }
            }
        });
    }

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

    @Override
    public void onResume() {
        super.onResume();
        if (presenter != null) {
            reFresh();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {

            if(tryMakeMoneyAdp != null){

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