package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.os.Handler;
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.TextView;

import com.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.XiaomiGameEntity;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DeviceIDUtil;
import com.sheep.gamegroup.util.GlideImageLoader;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.ViewHolder;
import com.sheep.gamegroup.view.adapter.AdbCommonRecycler;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
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.List;

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

import static com.sheep.gamegroup.view.adapter.TryMakeMoneyAdp.PUBLIC_TAG_PREFIX_TEXTVIEW_LIST;


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

public class ActXiaomiGame extends BaseActivity {

    @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 view_list;

    private Activity activity;
    private List<XiaomiGameEntity> list = ListUtil.emptyList();
    private boolean isRefresh;
    private int page;
    private int per_page = 20;

    @Override
    protected int getLayoutId() {
        return R.layout.net_empty_fresh_list_more;
    }

    @Override
    public void initView() {
        activity = this;
        EventBus.getDefault().register(this);
        TitleBarUtils.getInstance()
                .setTitleFinish(activity)
                .setShowOrHide(this, true)
                .setTitle(activity, "小米游戏中心")
                .setRightImgBotton(activity,
                        R.mipmap.search_black_img,
                        new View.OnClickListener() {//搜索
                            @Override
                            public void onClick(View v) {
                                Jump2View.getInstance().goGameSearch(activity, 1);
                            }
                        });
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                initData();
                refresh.setRefreshing(false);
            }
        });

        view_list.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        view_list.setAdapter(new AdbCommonRecycler<XiaomiGameEntity>(SheepApp.getInstance(), list){

            @Override
            public int getItemViewType(int position) {
                return position;
            }
            @Override
            public int getViewIdByType(int type) {//type来源于 getItemViewType 返回的值
//                if(type == -1 + list.size()){
//                    return R.layout.find_item_bottom;
//                }
                return R.layout.try_makemoney_item_recommend;
            }

            @Override
            public void convert(ViewHolder holder, final XiaomiGameEntity item) {
                if(item == null){
                    return;
                }
                View rootConvertView = holder.itemView;
                View task_top = rootConvertView.findViewById(R.id.task_top);
                task_top.setVisibility(View.GONE);
                TextView item_money = (TextView)rootConvertView.findViewById(R.id.item_money);
                TextView item_name_tv = (TextView)rootConvertView.findViewById(R.id.item_name_tv);
                TextView item_num_tv = (TextView)rootConvertView.findViewById(R.id.item_num_tv);
                TextView item_date_tv = (TextView)rootConvertView.findViewById(R.id.item_date_tv);
                TextView detail_task_tv_center = (TextView)rootConvertView.findViewById(R.id.detail_task_tv_center);
                item_money.setVisibility(View.GONE);
                View line_tv = rootConvertView.findViewById(R.id.line_tv);
                View detail_task_layout = rootConvertView.findViewById(R.id.detail_task_layout);
                detail_task_layout.setVisibility(View.GONE);

                GlideImageLoader.setGameImage((ImageView) rootConvertView.findViewById(R.id.item_icon_iv), item.getIcon());
                item_name_tv.setText(item.getName()+"");
                item_num_tv.setText(item.getType()+"");
                item_date_tv.setText(DeviceIDUtil.newInstance().numberCnvert(item.getDownload_count_increment())+"人在玩");
                detail_task_tv_center.setTag(PUBLIC_TAG_PREFIX_TEXTVIEW_LIST + item.getDownload_url());
                detail_task_tv_center.setVisibility(View.VISIBLE);

                if(item.getAvailable_receive() == 0 && item.getReceive_account() == 0){//未领取账号

                    CommonUtil.getInstance()
                            .xiaomiRevieceAcctoun(detail_task_tv_center, item, activity);
                }else {
                    item.getDownloadHelper().updateDownloadTaskView((Activity) activity, item, detail_task_tv_center);
                    detail_task_tv_center.setTag(PUBLIC_TAG_PREFIX_TEXTVIEW_LIST + item.getDownload_url());
                }
                rootConvertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Jump2View.getInstance().goFindGame(activity, item.getId());
                    }
                });
            }
        });
        isRefresh = false;
    }

    @Override
    public void initListener() {

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

                }
            }
        });
    }

    @Override
    public void initData() {
        SysAppUtil.checkNet(new AbsObserver<Integer>() {
            @Override
            public void onNext(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 loadData(boolean isLoadMore, final boolean isRefresh){
        /**
         * 异步获取普通任务，回调是在主线程，可以直接更新UI，加载更多的逻辑只需更新pageNo和pageSize即可。
         */
        if (isLoadMore)
            page++;
        else
            page = 1;

        CommonUtil.getInstance()
                .xiaomiGame(activity,page, per_page, "", new Action1<BaseMessage>() {
                    @Override
                    public void call(BaseMessage baseMessage) {
                        try {
                            if(baseMessage == null){

                                CommonUtil.getInstance().updateEmptyView(empty_view, true);
                                G.showToast("暂无游戏");
                            }else {
                                List<XiaomiGameEntity> newList = baseMessage.getDatas(XiaomiGameEntity.class);

                                if (page == 1)
                                    list.clear();
                                CommonUtil.getInstance().updateEmptyView(empty_view, ListUtil.addAll(list, newList) == 0);
                                view_list.getAdapter().notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            CommonUtil.getInstance().updateEmptyView(empty_view, true);
                            e.printStackTrace();
                        }
                    }
                });


    }

    @Subscribe
    public void onEventMainThread(BigEvent event) {
        switch (event.getEventTypes()){
            case REFRESH_XIAOMI_GAME_LIST:
                initData();
                break;
        }
        CommonUtil.getInstance().setEventResultViewStatus(event, view_list);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
