package com.gh.gamecenter.game;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NoConnectionError;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.common.constant.Config;
import com.gh.common.constant.Constants;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.DownloadItemUtils;
import com.gh.common.util.GameViewUtils;
import com.gh.common.util.ImageUtils;
import com.gh.common.util.NewsUtils;
import com.gh.common.util.PlatformUtils;
import com.gh.common.util.TimestampUtils;
import com.gh.common.view.AutoScrollViewPager;
import com.gh.common.view.CardLinearLayout;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.GameDetailActivity;
import com.gh.gamecenter.NewsDetailActivity;
import com.gh.gamecenter.PluginActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.SubjectActivity;
import com.gh.gamecenter.adapter.ImagePagerAdapter;
import com.gh.gamecenter.adapter.viewholder.FooterViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameHeadViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameImageViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameNormalViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameTestViewHolder;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.entity.GameUpdateEntity;
import com.gh.gamecenter.entity.SlideEntity;
import com.gh.gamecenter.entity.SubjectEntity;
import com.gh.gamecenter.listener.OnCallBackListener;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.GameManager;
import com.gh.gamecenter.manager.PackageManager;
import com.gh.gamecenter.volley.extended.JsonArrayExtendedRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by LGT on 2016/7/1.
 */
public class Game1FragmentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private class ITEM_TYPE {
        public static final int slide = 0;              // 滚动图
        public static final int head = 1;               // 专题头部
        public static final int game_normal_type = 2;   // 游戏布局1
        public static final int game_test_type = 3;     // 游戏布局2
        public static final int image = 4;              // 大图布局
        public static final int footer_view = 5;        // 加载布局
    }

    private Game1Fragment fragment;
    private Context context;
    private OnCallBackListener listener;

    private SwipeRefreshLayout game_swipe_refresh;

    private List<SlideEntity> slideList;
    private List<GameEntity> pluginList;
    private List<SubjectEntity> subjectList;

    private ArrayMap<String, ArrayList<Integer>> locationMap;
    private ArrayMap<String, String> nameMap;
    private ArrayMap<String, String> pluginNameMap;

    private int pluginSize;

    private boolean isNetworkError;
    private boolean isSlideError;
    private boolean isListError;
    private boolean isRemove;
    private boolean isInitPlugin;

    public Game1FragmentAdapter(Game1Fragment fragment,
                                SwipeRefreshLayout refreshLayout,
                                boolean isLoad) {

        this.fragment = fragment;
        this.context = fragment.getActivity();
        this.listener = fragment;

        game_swipe_refresh = refreshLayout;

        slideList = new ArrayList<>();
        pluginList = new ArrayList<>();
        subjectList = new ArrayList<>();

        locationMap = new ArrayMap<>();
        nameMap = new ArrayMap<>();
        pluginNameMap = new ArrayMap<>();

        pluginSize = 0;

        isNetworkError = false;
        isSlideError = false;
        isListError = false;
        isRemove = false;
        isInitPlugin = false;

        if (isLoad) {
            load();
        }
    }

    public ArrayMap<String, ArrayList<Integer>> getLocationMap() {
        return locationMap;
    }

    public ArrayMap<String, String> getNameMap() {
        return nameMap;
    }

    public ArrayMap<String, String> getPluginNameMap() {
        return pluginNameMap;
    }

    public void load() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                initSlide(true);
            }
        }){}.start();
    }

    private void initSlide(final boolean isFirst) {
        JsonArrayExtendedRequest slideRequest = new JsonArrayExtendedRequest(
                TimestampUtils.addTimestamp(Config.HOST + "v1d50/index/slides",
                        Constants.GAME_CD),
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Type listType = new TypeToken<ArrayList<SlideEntity>>() {}.getType();
                        Gson gson = new Gson();
                        slideList = gson.fromJson(response.toString(), listType);
                        if (slideList != null && !slideList.isEmpty()) {
                            notifyItemChanged(0);
                        }
                        if (isFirst) {
                            initSubjectList();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // 无网络连接
                        if (error.getClass().equals(NoConnectionError.class)
                                || error.getClass().equals(TimeoutError.class)) {
                            isSlideError = true;
                            showView();
                        }
                        if (isFirst) {
                            initSubjectList();
                        }
                    }
                });
        AppController.addToRequestQueue(slideRequest, Game1Fragment.TAG);
    }

    private void initSubjectList() {
        JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(
                TimestampUtils.addTimestamp(Config.HOST + "v1d50/game/chajian",
                        Constants.GAME_CD),
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Type listType = new TypeToken<ArrayList<SubjectEntity>>() {}.getType();
                        Gson gson = new Gson();
                        List<SubjectEntity> list = gson.fromJson(response.toString(), listType);
                        if (list != null && !list.isEmpty()) {
                            GameManager manager = new GameManager(context);
                            SubjectEntity subjectEntity;
                            GameEntity gameEntity;
                            for (int j = 0; j < list.size(); j++) {
                                subjectEntity = list.get(j);
                                if (subjectEntity.getData().size() == 1
                                        && !TextUtils.isEmpty(subjectEntity.getData().get(0).getImage())){
                                    list.remove(j);
                                    continue;
                                }
                                for (int i = 0; i < subjectEntity.getData().size(); i++) {
                                    gameEntity = subjectEntity.getData().get(i);
                                    if (gameEntity.getApk() != null && !gameEntity.getApk().isEmpty()) {
                                        gameEntity.setEntryMap(DownloadManager.getInstance(context).getEntryMap(gameEntity.getName()));
                                        manager.addOrUpdate(gameEntity.getApk(), gameEntity.getId(), gameEntity.getName());
                                    } else if (TextUtils.isEmpty(gameEntity.getId())) {
                                        if (TextUtils.isEmpty(gameEntity.getType())
                                                || TextUtils.isEmpty(gameEntity.getLink())
                                                || TextUtils.isEmpty(gameEntity.getName())
                                                || TextUtils.isEmpty(gameEntity.getImage())) {
                                            subjectEntity.getData().remove(i);
                                            i--;
                                        }
                                    }
                                }
                            }
                            subjectList = list;
                        }

                        if (subjectList.size() != 0) {
                            if (!fragment.isHidden() && !fragment.isEverpause()) {
                                if (pluginList.isEmpty()) {
                                    notifyItemRangeInserted(1, getItemCount() - 2);
                                } else {
                                    int start = 2 + pluginList.size();
                                    notifyItemRangeInserted(start, getItemCount() - start - 1);
                                }
                            } else {
                                notifyDataSetChanged();
                            }
                            initLocationMap();
                        }

                        listener.loadDone();

                        isRemove = true;
                        notifyItemChanged(getItemCount() - 1);

                        initPlugin();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // 无网络连接和访问超时
                        if (error.getClass().equals(NoConnectionError.class)
                                || error.getClass().equals(TimeoutError.class)) {
                            listener.loadDone();
                            isListError = true;
                            isNetworkError = true;
                            showView();
                        }
                    }
                });
        AppController.addToRequestQueue(request, Game1Fragment.TAG);
    }

    public void initPlugin() {
        ArrayList<GameUpdateEntity> updateList = PackageManager.getUpdateList();
        if (updateList.isEmpty()) {
            if (!isInitPlugin) {
                isInitPlugin = true;
            }
            return;
        }
        GameUpdateEntity gameUpdateEntity;
        for (int i = 0, size= updateList.size(); i < size; i++) {
            gameUpdateEntity = updateList.get(i);
            if (gameUpdateEntity.isPluggable()) {
                pluginSize++;
                if (pluginList.size() < 3) {
                    GameEntity gameEntity = new GameEntity();
                    gameEntity.setId(gameUpdateEntity.getId());
                    gameEntity.setName(gameUpdateEntity.getName());
                    gameEntity.setIcon(gameUpdateEntity.getIcon());
                    gameEntity.setTag(gameUpdateEntity.getTag());
                    gameEntity.setBrief(gameUpdateEntity.getBrief());
                    gameEntity.setPluggable(true);

                    ApkEntity apkEntity = new ApkEntity();
                    apkEntity.setUrl(gameUpdateEntity.getUrl());
                    apkEntity.setPackageName(gameUpdateEntity.getPackageName());
                    apkEntity.setSize(gameUpdateEntity.getSize());
                    apkEntity.setVersion(gameUpdateEntity.getVersion());
                    apkEntity.setGhVersion(gameUpdateEntity.getGhVersion());
                    apkEntity.setPlatform(gameUpdateEntity.getPlatform());
                    apkEntity.setEtag(gameUpdateEntity.getEtag());

                    ArrayList<ApkEntity> apk = new ArrayList<>();
                    apk.add(apkEntity);
                    gameEntity.setApk(apk);

                    pluginList.add(gameEntity);
                }
            }
        }
        if (!pluginList.isEmpty()) {
            for (GameEntity gEntity : pluginList) {
                gEntity.setEntryMap(DownloadManager.getInstance(context).
                        getEntryMap(gEntity.getName()));
            }
            notifyItemRangeInserted(1, pluginList.size() + 1);
            if (getItemCount() > pluginList.size() + 2) {
                notifyItemChanged(pluginList.size() + 2);
            }
            initLocationMap();
        }
        if (!isInitPlugin) {
            isInitPlugin = true;
        }
    }

    private void showView() {
        if (isSlideError && isListError) {
            Toast.makeText(context, "加载失败，请检查网络状态", Toast.LENGTH_SHORT).show();
            listener.loadError();
        } else if (isSlideError) {
            Toast.makeText(context, "加载失败，请检查网络状态", Toast.LENGTH_SHORT).show();
            notifyItemChanged(0);
        } else if (isListError) {
            Toast.makeText(context, "加载失败，请检查网络状态", Toast.LENGTH_SHORT).show();
            notifyItemChanged(getItemCount() - 1);
        }
    }

    private void initLocationMap() {
        locationMap.clear();

        int count = getItemCount();
        if (!pluginList.isEmpty()) {
            GameEntity gameEntity;
            String name;
            ArrayList<Integer> list;
            for (int position = 0; position < count; position++) {
                if (position > 1 && position <= 1 + pluginList.size()) {
                    gameEntity = pluginList.get(position - 2);
                    name = gameEntity.getName() + " - " + gameEntity.getApk().get(0).getPlatform();
                    list = locationMap.get(name);
                    if (list == null) {
                        list = new ArrayList<>();
                        locationMap.put(name, list);
                    }
                    list.add(position);
                    for (ApkEntity apkEntity : gameEntity.getApk()) {
                        pluginNameMap.put(apkEntity.getPackageName(),
                                gameEntity.getName() + " - " + apkEntity.getPlatform());
                    }
                }
            }
        }

        if (!subjectList.isEmpty()) {
            int offset;
            GameEntity gameEntity;
            String name;
            ArrayList<Integer> locationList;
            for (int position = 0; position < count; position++) {
                offset = 1;
                if (!pluginList.isEmpty()) {
                    offset += 1 + pluginList.size();
                }
                for (int i = 0, size = subjectList.size(); i < size; i++) {
                    if (position > offset && position <= subjectList.get(i).getData().size() + offset) {
                        gameEntity = subjectList.get(i).getData().get(position - offset - 1);
                        if (gameEntity.getApk() != null && !gameEntity.getApk().isEmpty()) {
                            name = gameEntity.getName();
                            locationList = locationMap.get(name);
                            if (locationList == null) {
                                locationList = new ArrayList<>();
                                locationMap.put(name, locationList);
                            }
                            locationList.add(position);
                            for (ApkEntity apkEntity : gameEntity.getApk()) {
                                nameMap.put(apkEntity.getPackageName(), name);
                            }
                        }
                        break;
                    }
                    offset = subjectList.get(i).getData().size() + offset + 1;
                }
            }
        }
    }

    @Override
    public int getItemCount() {
        int pluginSize = 0;
        if (!pluginList.isEmpty()) {
            pluginSize += 1 + pluginList.size();
        }
        int subjectSize = 0;
        if (!subjectList.isEmpty()) {
            SubjectEntity subjectEntity;
            for (int i = 0, size = subjectList.size(); i < size; i++) {
                subjectEntity = subjectList.get(i);
                subjectSize += 1 + subjectEntity.getData().size();
            }
        }
        return 1 + pluginSize + subjectSize + 1;
    }

    @Override
    public int getItemViewType(int position) {

        if (position == 0) {
            return ITEM_TYPE.slide;
        }

        if (!pluginList.isEmpty()) {
            if (position == 1) {
                return ITEM_TYPE.head;
            }
            if (position > 1 && position <= 1 + pluginList.size()) {
                return ITEM_TYPE.game_normal_type;
            }
        }

        int offset = 1;
        if (!pluginList.isEmpty()) {
            offset += 1 + pluginList.size();
        }
        GameEntity gameEntity;
        for (int i = 0, size = subjectList.size(); i < size; i++) {
            if (position >= offset && position <= subjectList.get(i).getData().size() + offset) {
                int index = position -offset-1;
                if (index<0){
                    index = 0;
                }
                gameEntity = subjectList.get(i).getData().get(index);
                if (position == offset && !TextUtils.isEmpty(gameEntity.getImage())){
                    return ITEM_TYPE.image;
                }else if (position == offset){
                    return ITEM_TYPE.head;
                }
                if (position == offset+1&&!TextUtils.isEmpty(subjectList.get(i).getData().get(0).getImage())){
                    return ITEM_TYPE.head;
                }
                if (!TextUtils.isEmpty(gameEntity.getImage())) {
                    return ITEM_TYPE.image;
                }
                if (gameEntity.getTest() != null) {
                    return ITEM_TYPE.game_test_type;
                }
                return ITEM_TYPE.game_normal_type;
            }
            offset = subjectList.get(i).getData().size() + offset + 1;
        }
        return ITEM_TYPE.footer_view;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == ITEM_TYPE.slide) {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.plugin1_autoscrollviewpager_viewholder, parent, false);
            DisplayMetrics outMetrics = new DisplayMetrics();
            fragment.getActivity().getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, (int) (outMetrics.widthPixels / 16f * 7f));
            view.setLayoutParams(params);
            return new AutoScrollViewpagerViewHolder(view);
        } else if (viewType == ITEM_TYPE.head) {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.home_game_head_item, parent, false);
            return new GameHeadViewHolder(view);
        } else if (viewType == ITEM_TYPE.game_normal_type) {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.game_normal_item, parent, false);
            return new GameNormalViewHolder(view);
        } else if (viewType == ITEM_TYPE.game_test_type) {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.game_test_item, parent, false);
            return new GameTestViewHolder(view);
        } else if (viewType == ITEM_TYPE.image) {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.home_game_image_item, parent, false);
            return new GameImageViewHolder(view);
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.refresh_footerview, parent, false);
            return new FooterViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof AutoScrollViewpagerViewHolder) {
            AutoScrollViewpagerViewHolder viewHolder = (AutoScrollViewpagerViewHolder) holder;
            if (isSlideError) {
                viewHolder.viewpager_tv_failure.setVisibility(View.VISIBLE);
                viewHolder.viewPager.setVisibility(View.GONE);
                viewHolder.viewpager_ll_hint.setVisibility(View.GONE);
            } else {
                viewHolder.viewpager_tv_failure.setVisibility(View.GONE);
                viewHolder.viewPager.setVisibility(View.VISIBLE);
                viewHolder.viewpager_ll_hint.setVisibility(View.VISIBLE);
            }
            if (slideList.size() > 0) {
                int currentItem = 0;
                if (viewHolder.viewPager.getAdapter() != null) {
                    currentItem = viewHolder.viewPager.getCurrentItem();
                }
                viewHolder.viewpager_ll_hint.removeAllViews();
                for (int i = 0, size = slideList.size(); i < size; i++) {
                    ImageView imageView = new ImageView(context);
                    LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                            DisplayUtils.dip2px(context, 6),
                            DisplayUtils.dip2px(context, 6));
                    lparams.bottomMargin = DisplayUtils.dip2px(context, 6);
                    if (i == currentItem) {
                        imageView.setImageResource(R.drawable.oval_hint_up);
                    } else {
                        imageView.setImageResource(R.drawable.oval_hint_dn);
                    }
                    if (i != 0) {
                        lparams.leftMargin = DisplayUtils.dip2px(context, 6);
                    }
                    imageView.setLayoutParams(lparams);
                    viewHolder.viewpager_ll_hint.addView(imageView);
                }
                viewHolder.viewPager.setAdapter(new ImagePagerAdapter(context, slideList, true));
                viewHolder.viewPager.setCurrentItem(currentItem);
                viewHolder.viewPager.setInterval(3000);
                viewHolder.viewPager.startAutoScroll();
            }
        } else if (holder instanceof GameHeadViewHolder) {
            initGameHeadViewHolder((GameHeadViewHolder) holder, position);
        } else if (holder instanceof GameImageViewHolder) {
            initGameImageViewHolder((GameImageViewHolder) holder, position);
        } else if (holder instanceof GameNormalViewHolder){
            initGameNormalViewHolder((GameNormalViewHolder) holder, position);
        } else if (holder instanceof GameTestViewHolder) {
            initGameTestViewHolder((GameTestViewHolder) holder, position);
        } else if (holder instanceof FooterViewHolder) {
            initFooterViewHolder((FooterViewHolder) holder);
        }
    }

    private void initGameTestViewHolder(GameTestViewHolder holder, int position) {
        int offset = 1;
        if (!pluginList.isEmpty()) {
            offset += 1 + pluginList.size();
        }
        GameEntity gameEntity;
        for (int i = 0, size = subjectList.size(); i < size; i++) {
            if (position > offset && position <= subjectList.get(i).getData().size() + offset) {
                gameEntity = subjectList.get(i).getData().get(position - offset - 1);
                if (gameEntity.getTest() != null) {
                    int order = position - offset - 1;
                    if (subjectList.get(i).getData().get(0).getImage() != null) {
                        order--;
                    }
                    initGameTest(holder, gameEntity, order, subjectList.get(i), i + 1 == size);
                    break;
                }
            }
            offset = subjectList.get(i).getData().size() + offset + 1;
        }
    }

    private void initGameTest(GameTestViewHolder holder, final GameEntity gameEntity,
                              final int i, final SubjectEntity subjectEntity, boolean isBottom) {

        // 最后一个
        ((CardLinearLayout) holder.itemView).setBottom(isBottom);
        if (TextUtils.isEmpty(subjectEntity.getData().get(0).getImage())) {
            if (i + 1 == subjectEntity.getData().size()) {
                ((CardLinearLayout) holder.itemView).setmBottom(DisplayUtils.dip2px(context, 8));
            } else {
                ((CardLinearLayout) holder.itemView).setmBottom(0);
            }
        } else {
            if (i + 2 == subjectEntity.getData().size()) {
                ((CardLinearLayout) holder.itemView).setmBottom(DisplayUtils.dip2px(context, 8));
            } else {
                ((CardLinearLayout) holder.itemView).setmBottom(0);
            }
        }

        if (subjectEntity.getOrder()) {
            holder.home2_game_order.setVisibility(View.VISIBLE);
            holder.home2_game_order.setText(String.valueOf(i + 1));
        } else {
            holder.home2_game_order.setVisibility(View.GONE);
        }
        ImageUtils.getInstance(context).display(gameEntity.getIcon(), holder.gameThumb);
        holder.gameNameAndSize.setText(gameEntity.getName());
        if (gameEntity.getApk() == null || gameEntity.getApk().isEmpty()) {
            holder.gameDes.setText(gameEntity.getBrief());
        } else {
            holder.gameDes.setText(String.format("%s  %s", gameEntity.getApk().get(0).getSize(), gameEntity.getBrief()));
        }
        holder.gameTestType.setText(gameEntity.getTest().getType());
        if (gameEntity.getTest().getStart() == 0) {
            holder.gameTestTime.setVisibility(View.GONE);
        } else {
            holder.gameTestTime.setText(GameViewUtils.getGameTestDate(gameEntity.getTest().getStart()));
        }

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, Object> kv = new HashMap<>();
                kv.put("名字", gameEntity.getName());
                kv.put("位置", String.valueOf(i + 1));
                DataUtils.onEvent(context, "点击", "游戏-插件-" + subjectEntity.getName(), kv);

                Map<String, Object> map = new HashMap<>();
                map.put("location", subjectEntity.getName() + "-列表");
                map.put("page", "游戏-插件");
                map.put("game", gameEntity.getName());
                map.put("game_id", gameEntity.getId());
                DataCollectionManager.onEvent(context, "click-item", map);

                AppController.put("GameEntity", gameEntity);
                Intent intent = new Intent(context, GameDetailActivity.class);
                intent.putExtra("entrance", "(游戏-插件:" + subjectEntity.getName() + "-列表)");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        });

        if (gameEntity.getApk() == null || gameEntity.getApk().isEmpty()) {
            holder.downloadBtn.setVisibility(View.GONE);
        } else {
            if (gameEntity.getTest().getEnd() == 0) {
                holder.downloadBtn.setVisibility(View.VISIBLE);
                DownloadItemUtils.setOnClickListener(context,
                        holder.downloadBtn, gameEntity, i,
                        Game1FragmentAdapter.this, "(游戏-插件:" + subjectEntity.getName() + "-列表)",
                        "游戏-插件-" + subjectEntity.getName() + ":" + gameEntity.getName());
            } else {
                long endTime = Long.valueOf(gameEntity.getTest().getEnd()
                        + "000");
                long todayTime = new Date().getTime();
                if (todayTime > endTime) {
                    // 测试时间已过
                    holder.downloadBtn.setVisibility(View.GONE);
                } else {
                    // 测试时间未过
                    holder.downloadBtn.setVisibility(View.VISIBLE);
                    DownloadItemUtils.setOnClickListener(context,
                            holder.downloadBtn, gameEntity, i,
                            Game1FragmentAdapter.this,
                            "(游戏-插件:" + subjectEntity.getName() + "-列表)",
                            "游戏-插件-" + subjectEntity.getName() + ":" + gameEntity.getName());
                }
            }
        }

        DownloadItemUtils.updateItem(context, holder.gameDes,
                holder.game_progressbar, holder.game_ll_info, holder.download_speed,
                holder.download_percentage, holder.downloadBtn, gameEntity);
    }

    private void initGameNormalViewHolder(GameNormalViewHolder holder, int position) {
        GameEntity gameEntity;

        if (!pluginList.isEmpty() && position > 1 && position <= 1 + pluginList.size()) {
            gameEntity = pluginList.get(position - 2);
            SubjectEntity subjectEntity = new SubjectEntity();
            subjectEntity.setOrder(false);
            subjectEntity.setName("插件化");
            subjectEntity.setData(pluginList);
            initGameNormal(holder, gameEntity, position - 2, subjectEntity, false);
            return;
        }

        int offset = 1;
        if (!pluginList.isEmpty()) {
            offset += 1 + pluginList.size();
        }
        for (int i = 0, size = subjectList.size(); i < size; i++) {
            if (position > offset && position <= subjectList.get(i).getData().size() + offset) {
                int index = position -offset-1;
                if (index<0){
                    index = 0;
                }
                gameEntity = subjectList.get(i).getData().get(index);
                if (TextUtils.isEmpty(gameEntity.getImage()) && gameEntity.getTest() == null) {
                    int order = position - offset - 1;
                    if (subjectList.get(i).getData().get(0).getImage() != null) {
                        order--;
                    }
                    initGameNormal(holder, gameEntity, order, subjectList.get(i), i + 1 == size);
                    break;
                }
            }
            offset = subjectList.get(i).getData().size() + offset + 1;
        }
    }

    private void initGameNormal(GameNormalViewHolder holder, final GameEntity gameEntity,
                                final int i, final SubjectEntity subjectEntity, boolean isBottom) {

        // 最后一个
        ((CardLinearLayout) holder.itemView).setBottom(isBottom);
        if (TextUtils.isEmpty(subjectEntity.getData().get(0).getImage())) {
            if (i + 1 == subjectEntity.getData().size()) {
                ((CardLinearLayout) holder.itemView).setmBottom(DisplayUtils.dip2px(context, 8));
            } else {
                ((CardLinearLayout) holder.itemView).setmBottom(0);
            }
        } else {
            if (i + 2 == subjectEntity.getData().size()) {
                ((CardLinearLayout) holder.itemView).setmBottom(DisplayUtils.dip2px(context, 8));
            } else {
                ((CardLinearLayout) holder.itemView).setmBottom(0);
            }
        }

        if (subjectEntity.getOrder()) {
            holder.home1_game_order.setVisibility(View.VISIBLE);
            holder.home1_game_order.setText(String.valueOf(i + 1));
        } else {
            holder.home1_game_order.setVisibility(View.GONE);
        }
        ImageUtils.getInstance(context).display(gameEntity.getIcon(), holder.gameThumb);
        if (gameEntity.isPluggable()) {
            holder.gameNameAndSize.setText(String.format("%s - %s", gameEntity.getName(),
                    PlatformUtils.getInstance(context).getPlatformName(
                            gameEntity.getApk().get(0).getPlatform())));
        } else {
            holder.gameNameAndSize.setText(gameEntity.getName());
        }
        if (gameEntity.getApk() == null || gameEntity.getApk().isEmpty()) {
            holder.gameDes.setText(gameEntity.getBrief());
        } else {
            holder.gameDes.setText(String.format("%s  %s", gameEntity.getApk().get(0).getSize(), gameEntity.getBrief()));
        }
        GameViewUtils.setLabelList(context,  holder.labelList, gameEntity.getTag());

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Map<String, Object> kv = new HashMap<>();
                kv.put("名字", gameEntity.getName());
                kv.put("位置", String.valueOf(i + 1));
                DataUtils.onEvent(context, "点击", "游戏-插件-" + subjectEntity.getName(), kv);

                Map<String, Object> map = new HashMap<>();
                map.put("location", subjectEntity.getName() + "-列表");
                map.put("page", "游戏-插件");
                map.put("game", gameEntity.getName());
                map.put("game_id", gameEntity.getId());
                DataCollectionManager.onEvent(context, "click-item", map);

                if (gameEntity.isPluggable()) {
                    Intent intent = new Intent(context, GameDetailActivity.class);
                    intent.putExtra("gameId", gameEntity.getId());
                    intent.putExtra("entrance", "(游戏-插件:" + subjectEntity.getName() + "-列表)");
                    context.startActivity(intent);
                } else {
                    AppController.put("GameEntity", gameEntity);
                    Intent intent = new Intent(context, GameDetailActivity.class);
                    intent.putExtra("entrance", "(游戏-插件:" + subjectEntity.getName() + "-列表)");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                }
            }
        });

        DownloadItemUtils.setOnClickListener(context,  holder.downloadBtn, gameEntity, i,
                Game1FragmentAdapter.this, "(游戏-插件:" + subjectEntity.getName() + "-列表)",
                "游戏-插件-" + subjectEntity.getName() + ":" + gameEntity.getName());

        DownloadItemUtils.updateItem(context,  holder.gameDes,
                holder.game_progressbar,  holder.game_ll_info,  holder.download_speed,
                holder.download_percentage,  holder.downloadBtn, gameEntity, !gameEntity.isPluggable());
    }

    public void initGameImageViewHolder(GameImageViewHolder holder, int position) {
        int offset = 1;
        if (!pluginList.isEmpty()) {
            offset += 1 + pluginList.size();
        }
        GameEntity gameEntity;
        for (int i = 0, size = subjectList.size(); i < size; i++) {
            if (position >= offset && position <= subjectList.get(i).getData().size() + offset) {
                int index = position - offset - 1;
                if (index<0){
                    index = 0;
                }
                gameEntity = subjectList.get(i).getData().get(index);
                if (position == offset && !TextUtils.isEmpty(gameEntity.getImage())) {

                    if (i == 0) {
                        ((CardLinearLayout) holder.itemView).setmTop(DisplayUtils.dip2px(context, 8));
                    } else {
                        ((CardLinearLayout) holder.itemView).setmTop(0);
                    }

                    final GameEntity entity = gameEntity;
                    final String name = subjectList.get(i).getName();
                    String tag = entity.getImage();
                    holder.image.setTag(tag);
                    ImageUtils.getInstance(context).display(entity.getImage(), holder.image, R.drawable.preload, context, 16);//默认应该设置占位符，防止图片混乱
                    holder.image.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Map<String, Object> kv = new HashMap<>();
                            kv.put("名字", entity.getName());
                            kv.put("位置", "大图");
                            DataUtils.onEvent(context, "点击", "游戏-插件-" + name, kv);

                            Map<String, Object> map = new HashMap<>();
                            map.put("location", name + "-大图");
                            map.put("page", "游戏-插件");
                            DataCollectionManager.onEvent(context, "click-item", map);

                            if ("game".equals(entity.getType())) {
                                Intent intent = new Intent(context, GameDetailActivity.class);
                                intent.putExtra("gameId", entity.getLink());
                                intent.putExtra("entrance", "(游戏-插件:" + name + "-大图)");
                                context.startActivity(intent);
                            } else if ("news".equals(entity.getType())) {
                                // 统计阅读量
                                NewsUtils.statNewsViews(entity.getLink());

                                Intent intent = new Intent(context, NewsDetailActivity.class);
                                intent.putExtra("newsId", entity.getLink());
                                intent.putExtra("entrance", "(游戏-插件:" + name + "-大图)");
                                context.startActivity(intent);
                            } else if ("column".equals(entity.getType())) {
                                Intent intent = new Intent(context, SubjectActivity.class);
                                intent.putExtra("id", entity.getLink());
                                intent.putExtra("name", entity.getName());
                                intent.putExtra("entrance", "(游戏-插件:" + name + "-大图)");
                                context.startActivity(intent);
                            }
                        }
                    });
                    break;
                }
            }
            offset = subjectList.get(i).getData().size() + offset + 1;
        }
    }

    public void initGameHeadViewHolder(GameHeadViewHolder holder, int position) {
        if (!pluginList.isEmpty() && position == 1) {
            ((CardLinearLayout) holder.itemView).setmTop(DisplayUtils.dip2px(context, 8));
            holder.title.setTextColor(Color.parseColor("#00b7fa"));
            holder.thumb.setVisibility(View.VISIBLE);
            holder.thumb.setImageResource(R.drawable.home_plug_upgrade);
            holder.title.setText("你有" + pluginSize + "个游戏可以升级插件版");
            if (pluginSize <= 3) {
                holder.link.setVisibility(View.GONE);
            } else {
                holder.link.setVisibility(View.VISIBLE);
                holder.link.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, PluginActivity.class);
                        intent.putExtra("entrance", "(游戏-插件:插件化-全部)");
                        context.startActivity(intent);
                    }
                });
            }
            return;
        }

        int offset = 1;
        GameEntity gameEntity;
        if (!pluginList.isEmpty()) {
            offset += 1 + pluginList.size();
        }
        for (int i = 0, size = subjectList.size(); i < size; i++) {
            if (position >= offset && position <= subjectList.get(i).getData().size() + offset){
                int index = position - offset - 1;
                if (index < 0){
                    index = 0;
                }
                gameEntity = subjectList.get(i).getData().get(index);
                if (position == offset && TextUtils.isEmpty(gameEntity.getImage()) || position == offset+1&&!TextUtils.isEmpty(subjectList.get(i).getData().get(0).getImage())) {
                    if (TextUtils.isEmpty(subjectList.get(i).getData().get(0).getImage())
                            && pluginList.isEmpty() && i == 0) {
                        ((CardLinearLayout) holder.itemView).setmTop(DisplayUtils.dip2px(context, 8));
                    } else {
                        ((CardLinearLayout) holder.itemView).setmTop(0);
                    }
                    holder.thumb.setVisibility(View.GONE);
                    holder.title.setText(subjectList.get(i).getName());
                    holder.title.setTextColor(Color.BLACK);
                    final int ii = i;
                    if (subjectList.get(i).getData().size()>= Integer.parseInt(subjectList.get(i).getMore())){
                        holder.link.setVisibility(View.GONE);
                    }else {
                        holder.link.setVisibility(View.VISIBLE);
                    }
                    holder.link.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            SubjectEntity subjectEntity = subjectList.get(ii);
                            Intent intent = new Intent(context, SubjectActivity.class);
                            intent.putExtra("id", subjectEntity.getId());
                            intent.putExtra("name", subjectEntity.getName());
                            intent.putExtra("order",subjectEntity.getOrder());
                            intent.putExtra("entrance", "(游戏-插件:" + subjectEntity.getName() + "-全部)");
                            context.startActivity(intent);
                        }
                    });
                }
            }
            offset = subjectList.get(i).getData().size() + offset + 1;
        }
    }

    private AutoScrollViewPager autoScrollViewPager;

    public class AutoScrollViewpagerViewHolder extends RecyclerView.ViewHolder {

        private AutoScrollViewPager viewPager;
        private LinearLayout viewpager_ll_hint;
        private TextView viewpager_tv_failure;

        public AutoScrollViewpagerViewHolder(View v) {
            super(v);
            viewpager_tv_failure = (TextView) v.findViewById(R.id.viewpager_tv_failure);
            viewpager_tv_failure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isSlideError = false;
                    notifyItemChanged(0);
                    initSlide(false);
                }
            });
            viewpager_ll_hint = (LinearLayout) v.findViewById(R.id.viewpager_ll_hint);
            viewPager = (AutoScrollViewPager) v.findViewById(R.id.view_pager);
            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

                        @Override
                        public void onPageSelected(int position) {
                            for (int i = 0, size = viewpager_ll_hint
                                    .getChildCount(); i < size; i++) {
                                if (i == position % size) {
                                    ((ImageView) viewpager_ll_hint.getChildAt(i))
                                            .setImageResource(R.drawable.oval_hint_up);
                                } else {
                                    ((ImageView) viewpager_ll_hint.getChildAt(i))
                                            .setImageResource(R.drawable.oval_hint_dn);
                                }
                            }
                        }

                        @Override
                        public void onPageScrolled(int position,
                                                   float positionOffset, int positionOffsetPixels) {

                        }

                        @Override
                        public void onPageScrollStateChanged(int state) {
                            // 解决viewpager和SwipeRefreshLayout滑动冲突
                            if (state == ViewPager.SCROLL_STATE_DRAGGING) {
                                game_swipe_refresh.setEnabled(false);
                            } else {
                                game_swipe_refresh.setEnabled(true);
                            }
                        }
                    });
            autoScrollViewPager = viewPager;
        }

    }

    private void initFooterViewHolder(FooterViewHolder holder) {
        if (isNetworkError) {
            holder.footerview_line1.setVisibility(View.GONE);
            holder.footerview_line2.setVisibility(View.GONE);
            holder.footerview_progressbar.setVisibility(View.GONE);
            holder.footerview_tv_loading.setText("加载失败，点击重试");
            holder.itemView.setClickable(true);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    isNetworkError = false;
                    notifyItemChanged(getItemCount() - 1);
                    initSubjectList();
                }
            });
        } else if (isRemove) {
            holder.footerview_line1.setVisibility(View.VISIBLE);
            holder.footerview_line2.setVisibility(View.VISIBLE);
            holder.footerview_progressbar.setVisibility(View.GONE);
            holder.footerview_tv_loading.setText("到底了哦~");
            holder.itemView.setClickable(false);
        } else {
            holder.footerview_line1.setVisibility(View.GONE);
            holder.footerview_line2.setVisibility(View.GONE);
            holder.footerview_progressbar.setVisibility(View.VISIBLE);
            holder.footerview_tv_loading.setText("加载中...");
            holder.itemView.setClickable(false);
        }
    }

    public void startAutoScroll() {
        if (autoScrollViewPager != null) {
            autoScrollViewPager.startAutoScroll();
        }
    }

    public void stopAutoScroll() {
        if (autoScrollViewPager != null) {
            autoScrollViewPager.stopAutoScroll();
        }
    }

    public List<GameEntity> getPluginList() {
        return pluginList;
    }

    public List<SubjectEntity> getSubjectList() {
        return subjectList;
    }

    public boolean isNetworkError() {
        return isNetworkError;
    }

    public void setNetworkError(boolean networkError) {
        isNetworkError = networkError;
    }

    public boolean isInitPlugin() {
        return isInitPlugin;
    }
}
