package com.sheep.gamegroup.view.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
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.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.GiftBagApp;
import com.sheep.gamegroup.model.entity.Release_task;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.ViewHolder;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.AdbCommonRecycler;
import com.sheep.gamegroup.view.adapter.WelfareAdapter;
import com.sheep.gamegroup.view.adapter.GiftCenterAdapter;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.base.BaseFragment;
import com.sheep.jiuyan.samllsheep.service.DownloadService;

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

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

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by realicing on 2018/8/28.
 * realicing@sina.com
 */
public class FgtWelfareCenter extends BaseFragment{
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.wc_hot_welfare_list)
    RecyclerView wcHotWelfareList;
    @BindView(R.id.wc_all_welfare)
    TextView wcAllWelfare;
    @BindView(R.id.wc_download_welfare_list)
    RecyclerView wcDownloadWelfareList;
    @BindView(R.id.wc_all_gift)
    TextView wcAllGift;
    @BindView(R.id.wc_gift_center_title_line)
    View wc_gift_center_title_line;
    @BindView(R.id.wc_gift_center_title_container)
    View wc_gift_center_title_container;
    @BindView(R.id.wc_gift_center_list)
    RecyclerView wcGiftCenterList;
    @BindView(R.id.bottom_line_text)
    TextView bottomLineText;
    @BindView(R.id.wc_hot_welfare_list_ll)
    LinearLayout wc_hot_welfare_list_ll;
    @BindView(R.id.wc_download_welfare_list_ll)
    LinearLayout wc_download_welfare_list_ll;
    @BindView(R.id.bottom_line)
    LinearLayout bottomLine;

    @Override
    public int getLayoutId() {
        return R.layout.fgt_welfare_center;
    }
    private List<Release_task> hotWelfareList = ListUtil.emptyList();
    private List<Release_task> downloadWelfareList = ListUtil.emptyList();
    private List<GiftBagApp> giftCenterList = ListUtil.emptyList();
    private Activity activity;
    @Override
    public void onViewCreated() {
        activity = getActivity();
        final Context context = SheepApp.getInstance();
        //热门福利
        LinearLayoutManager hotLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
        wcHotWelfareList.setHasFixedSize(true);
        wcHotWelfareList.setNestedScrollingEnabled(false);
        wcHotWelfareList.setLayoutManager(hotLayoutManager);
        wcHotWelfareList.setAdapter(new AdbCommonRecycler<Release_task>(context, hotWelfareList) {
            @Override
            public int getViewIdByType(int type) {
                return R.layout.item_hot_welfare;
            }

            @Override
            public void convert(ViewHolder holder, final Release_task item) {
                ImageView item_hot_welfare_iv = holder.getView(R.id.item_hot_welfare_iv);
                TextView item_hot_welfare_tv = holder.getView(R.id.item_hot_welfare_tv);
                if(item == null || item.getTask() == null){
                    ViewUtil.setDefaultText(item_hot_welfare_tv);
                } else {
                    GlideImageLoader.setGameImage(item_hot_welfare_iv, item.getTask().getIcon());
                    ViewUtil.setText(item_hot_welfare_tv, item.getName());
                    DownloadService.setDownLoadLongClick(holder.itemView, item.getTask());
                }
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(item != null && item.getTask() != null)
                            Jump2View.getInstance().goGameTaskDetailView(activity,  item.getId(), item.getTask().getThird_task_id(),1);
                    }
                });
            }
        });
        //下载福利
        LinearLayoutManager downloadLayoutManager = new LinearLayoutManager(context);
        wcDownloadWelfareList.setHasFixedSize(true);
        wcDownloadWelfareList.setNestedScrollingEnabled(false);
        wcDownloadWelfareList.setLayoutManager(downloadLayoutManager);
        wcDownloadWelfareList.setAdapter(new WelfareAdapter(activity, downloadWelfareList, new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                switch (integer){
                    case WelfareAdapter.TO_REFRESH:
                        refreshDownloadWelfare = true;
                        refreshData();
                        break;
                }
            }
        }));
        //礼包中心
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        wcGiftCenterList.setHasFixedSize(true);
        wcGiftCenterList.setNestedScrollingEnabled(false);
        wcGiftCenterList.setLayoutManager(layoutManager);
        wcGiftCenterList.setAdapter(new GiftCenterAdapter(activity, giftCenterList, new Action1<Integer>() {
            @Override
            public void call(Integer integer) {
                switch (integer){
                    case WelfareAdapter.TO_REFRESH:
                        refreshGiftCenter = true;
                        refreshData();
                        break;
                }
            }
        }));
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
            }
        });
    }

    @Override
    protected void initDataOnVisibleToUser() {
        if(activity == null){
            onViewCreated();
        }
        initData();
    }

    public void initData() {
        refreshHotWelfare = true;
        refreshDownloadWelfare = true;
        refreshGiftCenter = true;
        refreshData();
    }

    private boolean refreshHotWelfare = true;
    private boolean refreshDownloadWelfare = true;
    private boolean refreshGiftCenter = true;
    private final static int DEFAULT_COUNT = 5;//下载福利与礼包中心默认显示条数
    //刷新数据
    private void refreshData() {
        if(refreshHotWelfare || refreshDownloadWelfare || refreshGiftCenter) {
            refresh.setRefreshing(true);
        }
        //热门福利
        if(refreshHotWelfare) {
            SheepApp.getInstance().getNetComponent().getApiService().getHotWelfareList()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                        @Override
                        public void onNext(BaseMessage baseMessage) {
                            refreshHotWelfare = false;
                            ArrayList<Release_task> newList = baseMessage.getDataList(Release_task.class);
                            hotWelfareList.clear();
                            ListUtil.addAll(hotWelfareList, newList);
                            if(wcHotWelfareList != null)
                                wcHotWelfareList.getAdapter().notifyDataSetChanged();
                            notifyDataSetChanged();
                        }

                        @Override
                        public void onError(BaseMessage baseMessage) {
                            refreshHotWelfare = false;
                            hotWelfareList.clear();
                            if(wcHotWelfareList != null)
                                wcHotWelfareList.getAdapter().notifyDataSetChanged();
                            notifyDataSetChanged();
                        }
                    });
        }
        //下载福利
        if(refreshDownloadWelfare) {
            SheepApp.getInstance().getNetComponent().getApiService().getDownWelfareList(1,DEFAULT_COUNT)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                        @Override
                        public void onNext(BaseMessage baseMessage) {
                            refreshDownloadWelfare = false;
                            ArrayList<Release_task> newList = baseMessage.getDataList(Release_task.class);
                            downloadWelfareList.clear();
                            ListUtil.addAll(downloadWelfareList, newList);
                            if(wcDownloadWelfareList != null)
                                wcDownloadWelfareList.getAdapter().notifyDataSetChanged();
                            notifyDataSetChanged();
                        }

                        @Override
                        public void onError(BaseMessage baseMessage) {
                            refreshDownloadWelfare = false;
                            downloadWelfareList.clear();
                            if(wcDownloadWelfareList != null)
                                wcDownloadWelfareList.getAdapter().notifyDataSetChanged();
                            notifyDataSetChanged();
                        }
                    });
        }
        //礼包中心
        if(refreshGiftCenter) {
            SheepApp.getInstance().getNetComponent().getApiService().getGiftBagList(1, DEFAULT_COUNT)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                        @Override
                        public void onNext(BaseMessage baseMessage) {
                            refreshGiftCenter = false;
                            ArrayList<GiftBagApp> newList = baseMessage.getDataList(GiftBagApp.class);
                            giftCenterList.clear();
                            ListUtil.addAll(giftCenterList, newList);
                            if(wcGiftCenterList != null)
                                wcGiftCenterList.getAdapter().notifyDataSetChanged();
                            notifyDataSetChanged();
                        }

                        @Override
                        public void onError(BaseMessage baseMessage) {
                            refreshGiftCenter = false;
                            giftCenterList.clear();
                            if(wcGiftCenterList != null)
                                wcGiftCenterList.getAdapter().notifyDataSetChanged();
                            notifyDataSetChanged();
                        }
                    });
        }
    }

    private void notifyDataSetChanged() {
        if(refresh == null || wc_gift_center_title_container == null || wc_gift_center_title_line == null){
            return;
        }
        if(!refreshHotWelfare && !refreshDownloadWelfare && !refreshGiftCenter)
            refresh.setRefreshing(false);
        wc_gift_center_title_container.setVisibility(giftCenterList.isEmpty() ? View.GONE : View.VISIBLE);
        wc_gift_center_title_line.setVisibility(giftCenterList.isEmpty() ? View.GONE : View.VISIBLE);
        ViewUtil.setVisibility(wc_hot_welfare_list_ll, !hotWelfareList.isEmpty());
        ViewUtil.setVisibility(wc_download_welfare_list_ll, !downloadWelfareList.isEmpty());
    }


    @OnClick({R.id.wc_all_welfare, R.id.wc_all_gift})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.wc_all_welfare://全部福利
                Jump2View.getInstance().goWelfareList(activity);
                break;
            case R.id.wc_all_gift://全部礼包
                Jump2View.getInstance().goGiftCenter(activity);
                break;
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Subscribe
    public void onEventMainThread(BigEvent event) {
        CommonUtil.getInstance().setEventResultViewStatus(event, wcDownloadWelfareList);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
