package com.kfzs.duanduan.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
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.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.kfzs.duanduan.BaseCompatFragment;
import com.mdad.sdk.mdsdk.AdManager;
import com.mdad.sdk.mdsdk.GetAdListListener;
import com.mdad.sdk.mdsdk.RewardListener;
import com.mdad.sdk.mdsdk.common.AdData;
import com.sheep.gamegroup.model.entity.AdDataSon;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.GameAgencyRechargePlatformEntity;
import com.sheep.gamegroup.model.entity.RecyleObj;
import com.sheep.gamegroup.model.entity.RecyleType;
import com.sheep.gamegroup.model.entity.TaskReleaseEty;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.view.adapter.AdListAdapter;
import com.sheep.gamegroup.view.adapter.TryMakeMoneyAdp;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.utils.G;

import java.util.Collection;
import java.util.List;

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

/**
 * Created by ljy on 2018/7/19.
 */

public class FgtMiDong extends BaseCompatFragment {

    @BindView(R.id.title)
    View title;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.empty_view)
    View empty_view;
    @BindView(R.id.check_net_ll)
    View check_net_ll;
    @BindView(R.id.view_list)
    RecyclerView recyclerview;
    private int type;
    private Activity activity;
    private AdListAdapter adListAdapter;
    private int pageNo = 1;
    private int pageSize = 30;
    private List<AdDataSon> listData = ListUtil.emptyList();

    private int refresh_init_false = 1;

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

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            type = bundle.getInt("type", 0);
        }
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.net_empty_fresh_list_more);
        activity = getActivity();
        ButterKnife.bind(this, mContentView);
        initView();
        initData(false);
    }

    private void initView() {
        title.setVisibility(View.GONE);
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData(true);
                refresh.setRefreshing(false);
            }
        });


        /**
         * recycle view
         */
        recyclerview.setLayoutManager(new LinearLayoutManager(activity));
        adListAdapter = new AdListAdapter(activity, listData);
        recyclerview.setAdapter(adListAdapter);

        /**
         * 任务完成回调
         */
        AdManager.getInstance(activity).setRewardListener(new RewardListener() {
            @Override
            public void doTaskSuccess(String packageName) {
                // packageName 为所完成任务的包名
                G.showToast(activity, packageName + "", Toast.LENGTH_SHORT);
            }

            @Override
            public void doTaskFail(String error) {
                G.showToast(activity, error + "", Toast.LENGTH_SHORT);
            }
        });
        initListen();
    }

    private void initData(final boolean isRefresh) {
        empty_view.setVisibility(View.INVISIBLE);
        SysAppUtil.checkNet(new Action1<Integer>() {
            @Override
            public void call(Integer result) {
                if (result != 0) {//无网络
                    if (check_net_ll != null)
                        check_net_ll.setVisibility(View.VISIBLE);
                } else {
                    if (check_net_ll != null)
                        check_net_ll.setVisibility(View.GONE);
                }
            }
        });
        try{
            loadData(false, isRefresh);
        }catch (Exception e){
            e.printStackTrace();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    loadData(false, isRefresh);
                }
            }, 500);
        }
    }

    private void notifyDataSetChanged() {
        CommonUtil.getInstance().updateEmptyView(empty_view, listData.isEmpty());
        refresh.setRefreshing(false);
        adListAdapter.notifyDataSetChanged();
    }

    private void loadData(boolean isLoadMore, final boolean isRefresh) {
        /**
         * 异步获取普通任务，回调是在主线程，可以直接更新UI，加载更多的逻辑只需更新pageNo和pageSize即可。
         */
        if (isLoadMore)
            pageNo++;
        else
            pageNo = 1;
        if (type == 0) {
            AdManager.getInstance(activity).getAdListAsync(activity, new GetAdListListener() {
                @Override
                public void onLoadAdSuccess(List<AdData> list) {
                    refresh.setRefreshing(false);
                    if (list != null) {
                        if (pageNo == 1)
                            listData.clear();

                        for (AdData adData : list) {
                            AdDataSon adDataSon = new AdDataSon();
                            adDataSon.setAdData(adData);
                            listData.add(adDataSon);
                        }
//                        listData.addAll((Collection<? extends AdDataSon>) list);
                        adListAdapter.setData(listData);
                    }
                    notifyDataSetChanged();
                }

                @Override
                public void onLoadAdFailure() {
                    if(refresh_init_false == 1){
                        initData(isRefresh);
                    }
                    refresh_init_false++;
                    refresh.setRefreshing(false);
                    if (isRefresh)
                        G.showToast(activity, "网络异常，请稍后再试", Toast.LENGTH_SHORT);
                    notifyDataSetChanged();
                }

                @Override
                public void onAdEmpty() {
                    if (isRefresh)
                        G.showToast(activity, "暂无数据", Toast.LENGTH_SHORT);
                    notifyDataSetChanged();

                }
            }, pageNo, pageSize);

        } else {
            /**
             * 异步获取签到任务，回调是在主线程，可以直接更新UI，加载更多的逻辑只需更新pageNo和pageSize即可。
             */
            AdManager.getInstance(activity).getSignListAsync(activity, new GetAdListListener() {
                @Override
                public void onLoadAdSuccess(List<AdData> list) {
                    refresh.setRefreshing(false);
                    if (list != null && list.size() > 0) {
                        if (pageNo == 1)
                            listData.clear();
                        for (AdData adData : list) {
                            AdDataSon adDataSon = new AdDataSon();
                            adDataSon.setAdData(adData);
                            listData.add(adDataSon);
                        }
                        adListAdapter.setData(listData);
                        adListAdapter.setSign(true);
                    } else {
                        if (isRefresh)
                            G.showToast(activity, "暂无数据", Toast.LENGTH_SHORT);
                    }
                    notifyDataSetChanged();
                }

                @Override
                public void onLoadAdFailure() {
                    refresh.setRefreshing(false);
                    if (isRefresh)
                        G.showToast(activity, "网络异常，请稍后再试", Toast.LENGTH_SHORT);
                    notifyDataSetChanged();
                }

                @Override
                public void onAdEmpty() {
                    refresh.setRefreshing(false);
                    if (isRefresh)
                        G.showToast(activity, "暂无数据", Toast.LENGTH_SHORT);
                    notifyDataSetChanged();

                }
            }, pageNo, pageSize);
        }

    }

    private void initListen() {
        recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {//滑动到了底部
                    if (listData.size() >= pageNo * pageSize) {
                        loadData(true, false);
                    } else {
//                        G.showToast("没有更多数据了");
                    }

                }
            }
        });
    }

    /**
     * 刷新数据
     */
    public void refreshData() {
        if (adListAdapter != null)
            adListAdapter.notifyDataSetChanged();
    }
}
