package com.kfzs.duanduan.adp;

import android.app.Activity;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.kfzs.appstore.utils.adapter.recyclerview.ViewHolder;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.R;
import com.kfzs.duanduan.bean.CateGameBean;
import com.kfzs.duanduan.bean.GuessYouLike;
import com.kfzs.duanduan.bean.KFIntentKeys;
import com.kfzs.duanduan.bean.NewGameRecommend;
import com.kfzs.duanduan.bean.RecyleObj;
import com.kfzs.duanduan.bean.RecyleType;
import com.kfzs.duanduan.bean.SpecialRecommend;
import com.kfzs.duanduan.bean.VipStyle;
import com.kfzs.duanduan.proto.IndexBannerOuterClass;
import com.kfzs.duanduan.utils.DiscountUtils;
import com.kfzs.duanduan.utils.InstallButtonUtils;
import com.kfzs.duanduan.utils.NumberFormatUtils;
import com.kfzs.duanduan.utils.dlg.DownBtnUtils;
import com.kfzs.duanduan.utils.dlg.SkipUtils;
import com.kfzs.duanduan.view.ImageGlarry;
import com.kfzs.duanduan.view.KFProgressButton;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ Created by Dlg
 * @ <p>TiTle:  AdpMainPageRecy</p>
 * @ <p>Description: 这是首页推荐栏的RecyleView适配器</p>
 * @ date:  2017/6/15 13:03
 * @ QQ:    315096953
 */

public class AdpMainPageRecy extends AdpCommonRecy<RecyleObj> {

    private final String TAG = this.getClass().getName();
    private Map<String, InstallButtonUtils> mDownLoadItemLogicMgrMap = new HashMap<>();
    //设置Tag，因为默认Tag用于HoldView了 ，所以加个TagKey，ID必须为任意ResId
    private final static int TAG_ID_TEMP = R.id.view_tag_1;
    private final static int TAG_ID_TEMP2 = R.id.view_tag_2;
    private RecyclerView mRecyView;//返回顶层的监听
    private final static String HTML_FORMAT = "<b><font color='#E4B441'>限时福利 </font>%s会员专享</b>";
    private ImageGlarry mImageGlarry;

    public AdpMainPageRecy(Context context, RecyclerView recyclerView) {
        super(context);
        mContext = context;
        mRecyView = recyclerView;
    }


    /**
     * @param viewType
     * @return 失败返回0
     */
    @Override
    public int getViewIdByType(int viewType) {
        int resId = R.layout.empty;
        RecyleType recyleType = RecyleType.values()[viewType];
        switch (recyleType) {
            case BANNER:
                resId = R.layout.fgt_main_banner;
                break;
            case OWN_ZONE:
                resId = R.layout.fgt_main_own_zone;
                break;
            case GUESS_YOU_LIKE:
                resId = R.layout.fgt_main_guess_you_like;
                break;
            case NEW_FIRST:
                resId = R.layout.fgt_main_newrealse;
                break;
            case NEW_GAME_RECOMMEND:
                resId = R.layout.fgt_main_new_game_invite;
                break;
            case SPECIAL_GAME_RECOMMEND:
                resId = R.layout.fgt_main_special_game_invite;
                break;
            case RPG:
            case CARTON:
                resId = R.layout.mainpage_game_list;
                break;
            case SUBJECT:
                resId = R.layout.subject_list;
                break;
            case PALY_WITH_YOU:
                resId = R.layout.fgt_main_playwithyou;
                break;
            case NEW_GAME:
                resId = R.layout.fgt_main_newgame;
                break;
            case CHOICES_GAME:
                resId = R.layout.fgt_main_choosegames;
                break;
            case DEFINE_GAME:
                resId = R.layout.fgt_main_define;
                break;
            case BACK_TOP:
                resId = R.layout.listview_item_load_over;
                break;
        }
        return resId;
    }

    @Override
    public int getItemViewType(int position) {
        return getmListDatas().get(position).getRecyleType().ordinal();
    }

    public Map<String, InstallButtonUtils> getmDownLoadItemLogicMgrMap() {
        return mDownLoadItemLogicMgrMap;
    }

    @Override
    public void convert(ViewHolder holder, RecyleObj recyleObj) {
        if (recyleObj.getLoaded()) {//性能优化处理
            return;
        }
        switch (recyleObj.getRecyleType()) {
            case BANNER:
                bindBanner(holder, (List<IndexBannerOuterClass.IndexBanner>) recyleObj.getDataObj());
                break;
            case OWN_ZONE:
                bindOwnZone(holder);
                break;
            case NEW_GAME_RECOMMEND:
                bindNewGameRecommend(holder, (List<NewGameRecommend>) recyleObj.getDataObj());
                break;
            case SPECIAL_GAME_RECOMMEND:
                bindSpecialGameRecommend(holder, (SpecialRecommend) recyleObj.getDataObj());
                break;
            case RPG:
            case CARTON:
                CateGameBean cateGameBean = (CateGameBean) recyleObj.getDataObj();
                bindCarTonAndRPG(holder, cateGameBean, cateGameBean.getType_name());
                break;
            case SUBJECT:
                bindSubject(holder, (CateGameBean) recyleObj.getDataObj());
                break;
            case GUESS_YOU_LIKE:
                bindGuessYouLike(holder, (GuessYouLike) recyleObj.getDataObj());
                break;
            case BACK_TOP:
                TextView textView = holder.getView(R.id.txt_back_top);
                if (!textView.hasOnClickListeners()) {//性能优化
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mRecyView.scrollToPosition(0);
                        }
                    });
                }
                break;
        }
        recyleObj.setLoaded(true);
    }

    /**
     * 绑定猜你喜欢
     *
     * @param holder
     */
    private void bindGuessYouLike(ViewHolder holder, final GuessYouLike guessYouLike) {
        if (guessYouLike == null) {
            return;
        }
        RecyclerView recyclerView = holder.getView(R.id.recy_fgt_main_guess_you_like);
        Glide.with(mContext).load(guessYouLike.getImg())
                .into(holder.getView(R.id.img_fgt_main_guess_you_like, ImageView.class));
        holder.getView(R.id.img_fgt_main_guess_you_like)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SkipUtils.getInstance().goGameType(mContext, guessYouLike.getGametypeid());
                    }
                });
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(3,
                StaggeredGridLayoutManager.HORIZONTAL));
        recyclerView.setAdapter(new RecyclerView.Adapter() {
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                RelativeLayout itemView = (RelativeLayout) LayoutInflater.from(mContext)
                        .inflate(R.layout.item_fgt_main_game_list, parent, false);
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SkipUtils.getInstance().goGameDetails(mContext, (int) v.getTag(TAG_ID_TEMP));
                    }
                });
                ViewGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams((int) (G.WIDTH * 0.92),
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                itemView.setLayoutParams(layoutParams);

                RecyclerView.ViewHolder viewHolder = new RecyclerView.ViewHolder(itemView) {
                };
                return viewHolder;
            }

            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                holder.itemView.setTag(TAG_ID_TEMP, guessYouLike.getGames().get(position).getId());

                DiscountUtils.getInstance().showDiscount(holder.itemView,
                        guessYouLike.getGames().get(position).getIconImage(),
                        guessYouLike.getGames().get(position).getDiscount());

                ((TextView) holder.itemView.findViewById(R.id.txt_item_main_game_list_title)
                ).setText(guessYouLike.getGames().get(position).getGameName());
                ((TextView) holder.itemView.findViewById(R.id.txt_item_main_game_list_type)
                ).setText(guessYouLike.getGames().get(position).getTypeText());

                ((TextView) holder.itemView.findViewById(R.id.txt_item_fgt_main_game_list_down)
                ).setText("(" + guessYouLike.getGames().get(position).getDownloadNum() + ")");

                ((RatingBar) holder.itemView.findViewById(R.id.ratb_item_fgt_main_game_list)
                ).setRating(NumberFormatUtils.getDivideResult(guessYouLike.getGames().get(position).getStar()));
                holder.itemView.findViewById(R.id.line_item_fgt_main_game_list)
                        .setVisibility(position % 3 == 2 ? View.GONE : View.VISIBLE);
                DownBtnUtils.addDownloadBtnListener((KFProgressButton) holder.itemView.findViewById(R.id.btn_item_fgt_main_game_list),
                        mContext, mDownLoadItemLogicMgrMap, guessYouLike.getGames().get(position).getGameV1(),
                        "guess_you_like" + position);
            }

            @Override
            public int getItemCount() {
                return guessYouLike.getGames().size();
            }


        });
    }


    /**
     * 绑定专题
     *
     * @param holder
     * @param gameBean
     */
    private void bindSubject(ViewHolder holder, final CateGameBean gameBean) {
        if (gameBean == null) {
            return;
        }
        RecyclerView recyclerView = holder.getView(R.id.recy_subject_list);
        Glide.with(mContext).load(gameBean.getImg())
                .into(holder.getView(R.id.img_subject_list, ImageView.class));
        holder.getView(R.id.img_subject_list)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SkipUtils.getInstance().goGameType(mContext, gameBean.getGametypeid());
                    }
                });
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(3,
                StaggeredGridLayoutManager.HORIZONTAL));
        recyclerView.setAdapter(new RecyclerView.Adapter() {
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View itemView = LayoutInflater.from(mContext)
                        .inflate(R.layout.item_fgt_main_game_list, parent, false);
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SkipUtils.getInstance().goGameDetails(mContext, (int) v.getTag(TAG_ID_TEMP));
                    }
                });
                ViewGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams((int) (G.WIDTH * 0.92),
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                itemView.setLayoutParams(layoutParams);
                RecyclerView.ViewHolder viewHolder = new RecyclerView.ViewHolder(itemView) {
                };
                return viewHolder;
            }

            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                holder.itemView.setTag(TAG_ID_TEMP, gameBean.getGames().get(position).getId());

                DiscountUtils.getInstance().showDiscount(holder.itemView,
                        gameBean.getGames().get(position).getIconImage(),
                        gameBean.getGames().get(position).getDiscount());

                ((TextView) holder.itemView.findViewById(R.id.txt_item_main_game_list_title)
                ).setText(gameBean.getGames().get(position).getGameName());

                ((TextView) holder.itemView.findViewById(R.id.txt_item_main_game_list_type)
                ).setText(gameBean.getGames().get(position).getTypeText());

                ((TextView) holder.itemView.findViewById(R.id.txt_item_fgt_main_game_list_down)
                ).setText("(" + gameBean.getGames().get(position).getDownloadNum() + ")");

                holder.itemView.findViewById(R.id.line_item_fgt_main_game_list)
                        .setVisibility(position % 3 == 2 ? View.GONE : View.VISIBLE);

                ((RatingBar) holder.itemView.findViewById(R.id.ratb_item_fgt_main_game_list)
                ).setRating(NumberFormatUtils.getDivideResult(gameBean.getGames().get(position).getStar()));
                DownBtnUtils.addDownloadBtnListener((KFProgressButton) holder.itemView.findViewById(R.id.btn_item_fgt_main_game_list),
                        mContext, mDownLoadItemLogicMgrMap, gameBean.getGames().get(position).getGameV1(), "subject_" + position);
            }

            @Override
            public int getItemCount() {
                return gameBean.getGames().size();
            }

        });
    }

    /**
     * 绑定卡通一栏
     *
     * @param holder
     * @param gameBean
     * @param typename 这里以后改为int或枚举吧，很可能会动增的
     */
    private void bindCarTonAndRPG(ViewHolder holder, final CateGameBean gameBean, String typename) {
        if (gameBean == null) {
            return;
        }
        RecyclerView recyclerView = holder.getView(R.id.recy_mainpage_game_list, RecyclerView.class);
        holder.getView(R.id.txt_mainpage_game_list, TextView.class)
                .setText(typename);
        holder.getView(R.id.txt_mainpage_game_list_more)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SkipUtils.getInstance().goGameType(mContext, gameBean.getGametypeid());
                    }
                });
//        Glide.with(mContext).load(VipStyle.getInstance().getMore())
//                .into(holder.getView(R.id.txt_mainpage_game_list_more, ImageView.class));
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(new RecyclerView.Adapter() {
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View itemView = LayoutInflater.from(mContext)
                        .inflate(R.layout.item_fgt_main_game_list, parent, false);
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SkipUtils.getInstance().goGameDetails(mContext, (int) v.getTag(TAG_ID_TEMP));
                    }
                });
                RecyclerView.ViewHolder viewHolder = new RecyclerView.ViewHolder(itemView) {
                };
                return viewHolder;
            }

            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                holder.itemView.setTag(TAG_ID_TEMP, gameBean.getGames().get(position).getId());

                DiscountUtils.getInstance().showDiscount(holder.itemView,
                        gameBean.getGames().get(position).getIconImage(),
                        gameBean.getGames().get(position).getDiscount());

                ((TextView) holder.itemView.findViewById(R.id.txt_item_main_game_list_title)
                ).setText(gameBean.getGames().get(position).getGameName());

                ((TextView) holder.itemView.findViewById(R.id.txt_item_main_game_list_type)
                ).setText(gameBean.getGames().get(position).getTypeText());

                ((TextView) holder.itemView.findViewById(R.id.txt_item_fgt_main_game_list_down)
                ).setText("(" + gameBean.getGames().get(position).getDownloadNum() + ")");

                holder.itemView.findViewById(R.id.line_item_fgt_main_game_list)
                        .setVisibility(position == getItemCount() - 1 ? View.GONE : View.VISIBLE);
                ((RatingBar) holder.itemView.findViewById(R.id.ratb_item_fgt_main_game_list)
                ).setRating(NumberFormatUtils.getDivideResult(gameBean.getGames().get(position).getStar()));
                DownBtnUtils.addDownloadBtnListener((KFProgressButton) holder.itemView.findViewById(R.id.btn_item_fgt_main_game_list),
                        mContext, mDownLoadItemLogicMgrMap, gameBean.getGames().get(position).getGameV1(), "carton_" + position);
            }

            @Override
            public int getItemCount() {
                return gameBean.getGames().size();
            }
        });
    }


    /**
     * 绑定特别推荐栏
     *
     * @param holder
     */
    private void bindSpecialGameRecommend(ViewHolder holder, final SpecialRecommend specialRecommend) {
        if (specialRecommend == null) {
            return;
        }
        Glide.with(mContext).load(specialRecommend.getImg())
                .into(holder.getView(R.id.img_main_special_recommend_banner, ImageView.class));
        DiscountUtils.getInstance().showDiscount(holder.itemView,
                specialRecommend.getGame().getIconImage(),
                specialRecommend.getGame().getDiscount());

        holder.getView(R.id.txt_main_special_recommend_main_title, TextView.class)
                .setText(specialRecommend.getName());
        holder.getView(R.id.txt_main_special_recommend_title, TextView.class)
                .setText(specialRecommend.getGame().getGameName());
        holder.getView(R.id.txt_main_special_recommend_type, TextView.class)
                .setText(specialRecommend.getGame().getSize());
        holder.getView(R.id.lay_fgt_main_special_recommend)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        SkipUtils.getInstance().goGameDetails(mContext, specialRecommend.getGame().getId());
                    }
                });
        holder.getView(R.id.img_main_special_recommend_banner)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        SkipUtils.getInstance().goGameDetails(mContext, specialRecommend.getGame().getId());
                    }
                });
        DownBtnUtils.addDownloadBtnListener(holder.getView(R.id.btn_fgt_main_special_recommend, KFProgressButton.class),
                mContext, mDownLoadItemLogicMgrMap, specialRecommend.getGame().getGameV1(), "specail_recommend");
    }

    /**
     * 新游推荐
     *
     * @param holder
     */
    private void bindNewGameRecommend(ViewHolder holder, final List<NewGameRecommend> recommendList) {
        if (recommendList == null || recommendList.size() < 1) {
            return;
        }
        RecyclerView recyclerView = holder.getView(R.id.recy_fgt_main_new_game_invite);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new StaggeredGridLayoutManager(1,
                StaggeredGridLayoutManager.HORIZONTAL));
        recyclerView.setAdapter(new RecyclerView.Adapter() {
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View itemView = LayoutInflater.from(mContext)
                        .inflate(R.layout.item_fgt_main_new_game_invite, parent, false);
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SkipUtils.getInstance().goGameDetails(mContext, (int) v.getTag(TAG_ID_TEMP));
                    }
                });
                RecyclerView.ViewHolder viewHolder = new RecyclerView.ViewHolder(itemView) {
                };
                return viewHolder;
            }

            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                holder.itemView.setTag(TAG_ID_TEMP, recommendList.get(position).getGameid());
                ((TextView) holder.itemView.findViewById(R.id.txt_item_fgt_main_new_game_invite)
                ).setText(recommendList.get(position).getGamename());

                DiscountUtils.getInstance().showDiscount(holder.itemView,
                        recommendList.get(position).getIcon(), recommendList.get(position).getDiscount());
            }

            @Override
            public int getItemCount() {
                return recommendList.size();
            }
        });
    }

    /**
     * 绑定专区
     *
     * @param holder
     */
    private void bindOwnZone(ViewHolder holder) {
        Glide.with(mContext).load(VipStyle.getInstance().getIndexbanner())
                .into(holder.getView(R.id.img_fgt_main_own_zone, ImageView.class));
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                G.showToast(R.string.coming_soon);
            }
        });
    }


    /**
     * 绑定Banner的操作过程
     *
     * @param holder
     * @param topBannerList
     */
    private void bindBanner(ViewHolder holder, final List<IndexBannerOuterClass.IndexBanner> topBannerList) {
        ViewPager viewPager = holder.getView(R.id.viewpager_fgt_main_banner);
        RadioGroup radioGroup = holder.getView(R.id.group_fgt_main_banner);
        ArrayList<String> imgURL = new ArrayList<>();
        for (IndexBannerOuterClass.IndexBanner indexBanner : topBannerList) {
            imgURL.add(indexBanner.getImageUrl());
        }
        if (mImageGlarry != null) {
            mImageGlarry.init(imgURL.toArray(new String[]{}), ImageView.ScaleType.CENTER_CROP);
            return;
        }
        mImageGlarry = new ImageGlarry((Activity) mContext, viewPager, radioGroup);
        mImageGlarry.init(imgURL.toArray(new String[]{}), ImageView.ScaleType.CENTER_CROP);
        mImageGlarry.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                IndexBannerOuterClass.IndexBanner clickedGameObj = topBannerList.get(position);
                Map<String, String> map = new HashMap<>();
                map.put("BANNER_TYPE", clickedGameObj.getType() == KFIntentKeys.BANNER_TYPE_GAME ? "游戏Banner" : "广告Banner");
                //TODO 小刁，这些事件分析以后要专门弄个静态类来统一管理
                MobclickAgent.onEvent(mContext, UMConfigUtils.Event.BANNER_CLICK_HORIZONTAL.getKey(), map);
                switch (clickedGameObj.getType()) {
                    case KFIntentKeys.BANNER_TYPE_GAME:
                        SkipUtils.getInstance().goGameDetails(mContext, clickedGameObj.getGameId());
                        break;
                    case KFIntentKeys.BANNER_TYPE_AD:
                        SkipUtils.getInstance().goWebView(mContext, clickedGameObj.getHtmlUrl(),
                                clickedGameObj.getTitle(), mContext.getPackageName(), clickedGameObj.getGameId());
                        break;
                }
            }
        });
    }


}
