package com.wasu.cs.ui;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.wasu.authsdk.AuthSDK;
import com.wasu.authsdk.IAuthInterface;
import com.wasu.cs.adapter.ADBannerImageHolderView;
import com.wasu.cs.model.VipStateModel;
import com.wasu.cs.mvp.IView.IVIPMvpView;
import com.wasu.cs.mvp.model.AssetsDataModel;
import com.wasu.cs.mvp.presenter.MainVipPagePresenter;
import com.wasu.cs.utils.FocusAnimUtils;
import com.wasu.cs.utils.JsonUtil;
import com.wasu.cs.widget.viplogin.VipDialogLogin;
import com.wasu.cs.widget.viplogin.WasuVipWebView;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.frescoimagefetchermodule.RecyclerPauseOnScrollListener;
import com.wasu.module.http.HttpRequestModule;
import com.wasu.module.http.RequestParams;
import com.wasu.module.log.WLog;
import com.wasu.statistics.WasuStatistics;
import com.wasu.util.ConfigUtils;
import com.wasu.widgets.adapter.BaseFocusRecyclerViewAdapter;
import com.wasu.widgets.adapter.BaseFocusRecyclerViewHolder;
import com.wasu.widgets.adbanner.ADBanner;
import com.wasu.widgets.adbanner.ADViewHolderCreator;
import com.wasu.widgets.focuswidget.FocusRecyclerView;
import com.wasu.widgets.focuswidget.FocusRelativeLayout;
import com.wasu.widgets.tools.AnimTools;
import com.wasu.widgets.tools.AppUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import basic.BuilderTypeManager.BuildType;
import cn.com.wasu.main.AppUtil;
import cn.com.wasu.main.Common;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;

/**
 * Created by Danxingxi on 2016/6/23.
 * 首页VIP屏
 */
public class MainVipPageView extends FrameLayout implements IVIPMvpView ,View.OnFocusChangeListener ,View.OnClickListener{
    private final static String TAG = "MainVipPageView";
    private final static String PageName = "Vip";

    private final static int MSG_RecycleImageView = 1;
    private final static int MSG_ShowImageView = 2;
    /**是否是第一次加载**/
    private boolean isFirst = false;
    /**imageView是否已经回收**/
    private boolean isRecycled = true;

    private final static int LEFT_PAGE = 2;
    private final static int RIGHT_PAGE = 1;

    private MainVipPagePresenter mainVipPagePresenter;
    private View rootView;
    private Context mContext;
    private FocusRelativeLayout focusRelativeLayout;
    private FocusRecyclerView vipBodyRecyclerView;
    private ImageView   userIcon, iv_zhangdan, function_01, function_02, function_03 , userIconHat;
    private FrameLayout userIconFocus, adBannerFocus;
    private MyAdapater mAdapter;
    private String url;
    private View headerView;
    /**无限轮播广告控件**/
    private ADBanner adBanner;
    private TextView tips,time;
    ActivityMain activityMain;
    private int itemCount = 6;

    private ViewPager parentViewPager;

    /**左边活动数据**/
    private List<AssetsDataModel> leftData = new ArrayList<>();
    /**右边活动数据**/
    private List<AssetsDataModel> rightData = new ArrayList<>();
    /**底部资产**/
    private List<AssetsDataModel> adBannerData = new ArrayList<>();

    public MainVipPageView(Context context, String url, ViewPager viewPager) {
        super(context);
        this.parentViewPager = viewPager;
        this.url = url;
        initView(context);
    }

    public MainVipPageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public MainVipPageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context){
        mContext = context;
        activityMain = (ActivityMain) mContext;
        setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
        rootView = LayoutInflater.from(mContext).inflate(R.layout.layout_main_vip_viewpage ,this);
        headerView = LayoutInflater.from(mContext).inflate(R.layout.vip_header_view, null);
        adBannerFocus = (FrameLayout) headerView.findViewById(R.id.adBannerFocus);
        adBanner = (ADBanner) headerView.findViewById(R.id.adBanner);

        vipBodyRecyclerView = (FocusRecyclerView) rootView.findViewById(R.id.vipBodyRecyclerView);
        vipBodyRecyclerView.setHasFixedSize(true);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext,itemCount);
        gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        vipBodyRecyclerView.setLayoutManager(gridLayoutManager);
        gridLayoutManager.setSmoothScrollbarEnabled(true);
        mAdapter = new MyAdapater(vipBodyRecyclerView, mContext);
        mAdapter.setHeaderView(headerView);
        vipBodyRecyclerView.setAdapter(mAdapter);
        findViewById();
        initListeners();
        vipBodyRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.left = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_16dp);
                outRect.top = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_18dp);
                outRect.bottom = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_16dp);

            }
        });
        vipBodyRecyclerView.setClipChildren(false);
        vipBodyRecyclerView.setClipToPadding(false);
        mainVipPagePresenter = new MainVipPagePresenter();
        mainVipPagePresenter.attachView(this);
        /**获取页面数据**/
        mainVipPagePresenter.getVipPageData(url);
    }

    private void findViewById(){
        focusRelativeLayout = (FocusRelativeLayout) headerView.findViewById(R.id.focusLinearLayout);
        userIcon = (ImageView) headerView.findViewById(R.id.userIcon); // 用户头像
        userIconFocus = (FrameLayout) headerView.findViewById(R.id.userIconFocus);// 头像焦点
        iv_zhangdan = (ImageView) headerView.findViewById(R.id.zhangdan); // 账单
        userIconHat = (ImageView) headerView.findViewById(R.id.userIconHat);// vip皇冠
        tips = (TextView) headerView.findViewById(R.id.tips);// 立即开通vip
        time = (TextView) headerView.findViewById(R.id.time);

        function_01 = (ImageView) headerView.findViewById(R.id.function_01); // 右边位1
        function_02 = (ImageView) headerView.findViewById(R.id.function_02); // 右边位2
        function_03 = (ImageView) headerView.findViewById(R.id.function_03); // 右边位3
        /**多次创建webView可能造成内存溢出**/
//        webPage = new WasuCompFactory()
//                .createUniLogin(mContext, Common.loginurl);
        WasuVipWebView wasuWebView = new WasuVipWebView(mContext);
        webPage = new VipDialogLogin(mContext, wasuWebView, Common.loginurl);
    }

    private void initListeners(){
        adBannerFocus.setOnClickListener(this);
        userIconFocus.setOnFocusChangeListener(this);
        userIconFocus.setOnClickListener(this);
        function_01.setOnClickListener(this);
        function_02.setOnClickListener(this);
        function_03.setOnClickListener(this);

        iv_zhangdan.setOnClickListener(this);

        mAdapter.setOnItemListener(new BaseFocusRecyclerViewAdapter.OnItemListener() {
            @Override
            public void onItemClick(int position) {
                if(mAdapter.getHeaderView()!=null)
                    position = position-1;
                WasuStatistics.getInstance().click(mAdapter.getItemData(position).getId()+"");
                int hang = (position)/itemCount+1;
                int lie = (position)%itemCount+1;
                AppUtil.playEnter = PageName+"_2_"+(position+1);
                WasuStatistics.getInstance().homeItemClick(1,"VIP",hang+1+"_"+lie,mAdapter.getItemData(position).getId()+"",mAdapter.getItemData(position).getTitle());
                IntentMap.startIntent(mContext,null,mAdapter.getItemData(position).getLayout(),mAdapter.getItemData(position).getJsonUrl(),null);
            }

            @Override
            public void onItemLongClick(int position) {

            }

            @Override
            public void onItemFocusChange(View itemView, int position, boolean hasFocus) {
                View maskView = itemView.findViewById(R.id.maskView);
                View item = itemView.findViewById(R.id.tvName);
                if(item != null) {
                    if (hasFocus) {
                        if(maskView != null){
                            maskView.setVisibility(INVISIBLE);

                        }
//                        item.setVisibility(VISIBLE);
                        item.setSelected(true);
                    } else {
                        if(maskView != null){
                            maskView.setVisibility(VISIBLE);
                        }
//                        item.setVisibility(GONE);
                        item.setSelected(false);
                    }
                }
            }
        });
        userIconFocus.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                    return true;
                }
                return false;
            }
        });
        userIconFocus.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    function_01.setFocusable(false);
                }else{
                    function_01.setFocusable(true);
                }
            }
        });

        focusRelativeLayout.setItemViewFocusSearchListener(new FocusRelativeLayout.ItemViewFocusSearchListener() {
            @Override
            public boolean onItemViewFocusSearch(FocusRelativeLayout parent, View itemView, int itemCount, int position, KeyEvent event) {
                /**在android4.2以下的版本中需要对父控件重绘，不然会有残影**/
                if (Build.VERSION.SDK_INT <= 17) {
                    vipBodyRecyclerView.postInvalidate();
                }
                if (position == 0 && event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT && event.getAction() != KeyEvent.ACTION_UP){
                    /**取消晃动**/
//                    animator = parent.shockAnim(itemView);
                    return true;
                }
                if (position == 2 && event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() != KeyEvent.ACTION_UP){
                    /**取消晃动**/
//                    animator = parent.shockAnim(itemView);
                    changeViewPager(RIGHT_PAGE);
                    return true;
                }

                return false;
            }
        });
        vipBodyRecyclerView.setItemViewFocusSearchListener(new FocusRecyclerView.ItemViewFocusSearchListener() {
            @Override
            public boolean onItemViewFocusSearch(FocusRecyclerView parent, View itemView, int itemCount, int position, KeyEvent event) {
                if(((position%6) == 1) && event.getKeyCode() == KeyEvent.KEYCODE_DPAD_LEFT && event.getAction() != KeyEvent.ACTION_UP){
                    parent.shockAnim(itemView);
                    return true;
                }

                if(((position%6) == 0) && event.getKeyCode() == KeyEvent.KEYCODE_DPAD_RIGHT && event.getAction() != KeyEvent.ACTION_UP){
//                    animator = parent.shockAnim(itemView);
                    changeViewPager(RIGHT_PAGE);
                    return true;
                }

                return false;
            }
        });
        /**RecyclerView滚动时停止Fresco图片加载**/
        vipBodyRecyclerView.addOnScrollListener(new RecyclerPauseOnScrollListener(true, true));
        bindUserData();
    }

    /**
     * 主动使ViewPager翻页
     * @param viewPagerPosition
     */
    @Override
    public void changeViewPager(int viewPagerPosition){
        if(parentViewPager != null){
            parentViewPager.setCurrentItem(viewPagerPosition, true);
        }
    }

    @Override
    public void scrollToTop() {
        if(vipBodyRecyclerView!=null)
            vipBodyRecyclerView.smoothScrollToPosition(0);
    }

    @Override
    public void getBannerLeftSuccess(List<AssetsDataModel> blData) {
        leftData = blData;
        if(leftData.size()>1)
        FrescoImageFetcherModule.getInstance().attachImage(leftData.get(1).getPicUrl(),iv_zhangdan);
    }

    @Override
    public void getBannerMiddleSuccess(List<AssetsDataModel> bmData) {
        adBannerData = bmData;
        if(adBannerData == null){
            return;
        }
        if(adBannerData.size() < 1){
            return;
        }
        ArrayList<String> adData = new ArrayList<String>();
        for(AssetsDataModel mData : bmData){
            adData.add(mData.getPicUrl());
        }
        adBanner.setPages(new ADViewHolderCreator<ADBannerImageHolderView>() {
            @Override
            public ADBannerImageHolderView createHolder() {
                return new ADBannerImageHolderView();
            }
        },adData).setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused});
        adBanner.startTurning(5000);
    }

    @Override
    public void getBannerRightSuccess(List<AssetsDataModel> brData) {
        rightData = brData;
        if(rightData == null){
            return;
        }
        if(rightData.size()<1){
            return;
        }
        if(rightData.size()>2){
            FrescoImageFetcherModule.getInstance().attachImage(rightData.get(0).getPicUrl(),function_01);
            FrescoImageFetcherModule.getInstance().attachImage(rightData.get(1).getPicUrl(),function_02);
            FrescoImageFetcherModule.getInstance().attachImage(rightData.get(2).getPicUrl(),function_03);
        }
    }

    @Override
    public void getBodySuccess(List<AssetsDataModel> brData) {
        if(mAdapter!=null && brData!=null && brData.size()>0){
            mAdapter.setData(brData);
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 获取数据失败
     *
     * @param e
     */
    @Override
    public void getDataError(Throwable e) {
        e.printStackTrace();
        WLog.e(TAG ,e.getMessage());
    }

    /**
     * 显示loading
     */
    @Override
    public void showProgress() {

    }

    /**
     * 传递给子View应获得焦点
     * 拦截焦点分发，强制在首页Viewpager翻页时候设置固定焦点
     * @param direction
     * @param previouslyFocusedRect
     * @return
     */
    @Override
    protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
        if(previouslyFocusedRect == null){
            if(direction == View.FOCUS_DOWN){
                userIconFocus.requestFocus();
                return true;
            }
            if(function_01!=null && vipBodyRecyclerView!=null){
                vipBodyRecyclerView.smoothScrollToPosition(0);
                function_01.requestFocus();
                return true;
            }
        }
        return super.onRequestFocusInDescendants(direction, previouslyFocusedRect);
    }

    /**
     * 第一次请求焦点
     * @param direction
     */
    @Override
    public void firstRequestFocus(int direction ){
        onRequestFocusInDescendants(direction ,null);
    }
    /**
     * 处理方向键在没有任何View可以获得焦点情况
     * @param focused
     * @param direction
     * @return
     */
    @Override
    public boolean dispatchUnhandledMove(View focused, int direction) {
        if(vipBodyRecyclerView!=null) {
            View view = vipBodyRecyclerView.focusSearch(focused, direction);
            if(view!=null){
                view.requestFocus();
            }
        }
        headerView.postInvalidate();
        vipBodyRecyclerView.postInvalidate();
        return super.dispatchUnhandledMove(focused, direction);
    }
    /**
     * 隐藏loading
     */
    @Override
    public void hideProgress() {
    }

    /**
     * 绑定用户信息
     */
    public void bindUserData(){
        String headUrl = ConfigUtils.getString(mContext, "usercenter", "headUrl");
        // 判断用户是否登录
        if (!TextUtils.isEmpty(headUrl) && AuthSDK.getInstance().getValue(IAuthInterface.KEY_ENCRYPTV) != null && AuthSDK.getInstance().getValue(IAuthInterface.KEY_PUBLICKEY) != null) {
            if(checkIsVip()){
                userIconHat.setImageDrawable(getResources().getDrawable(R.drawable.vip_hat_gold));
                String strTime = AuthSDK.getInstance().getValue("vipExpireTime");
                if(!TextUtils.isEmpty(strTime)){
                    long longTime = Long.parseLong(strTime.trim());
                    time.setText(calTime(longTime));
                }
                time.setVisibility(VISIBLE);
                tips.setText("立即续订");
            }else {
                userIconHat.setImageDrawable(getResources().getDrawable(R.drawable.vip_hat_gray));
                time.setVisibility(INVISIBLE);
                tips.setText("立即开通VIP");
            }
            userIconHat.setVisibility(VISIBLE);
            FrescoImageFetcherModule.getInstance().setRouteDisplayImager(userIcon,headUrl);
        }else{
            userIconHat.setVisibility(INVISIBLE);
            time.setVisibility(INVISIBLE);
            tips.setText("立即开通VIP");
            userIcon.setImageDrawable(getResources().getDrawable(R.drawable.not_login));
        }

    }

    /**
     * long to time string
     * @param time
     * @return
     */
    private String calTime(long time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE);
        return "VIP到期时间:"+format.format(new Date(time));
    }

    /**
     * 检查是否为VIP用户
     * @return
     */
    private boolean checkIsVip() {
        String isvip=AuthSDK.getInstance().getValue("vipState");
        if(!TextUtils.isEmpty(isvip)){
            if("0".equalsIgnoreCase(isvip)){
                return false;
            }else{
                return true;
            }
        }else{
            return false;
        }
    }

    /**
     * 请求获取用户的VIP情况
     */
    private void getUserVipState(){
        /**请求header**/

        StringBuilder requestSB  = new StringBuilder();

        requestSB.append("http://vip.wasu.tv/business/product/productHistory.do?version=");

        requestSB.append("1");
        requestSB.append("&userKey="+AuthSDK.getInstance().getValue(IAuthInterface.KEY_USERKEY));
        requestSB.append("&token="+AuthSDK.getInstance().getValue(IAuthInterface.KEY_TOKEN));
        requestSB.append("&siteId="+BuildType.SITE_ID);
        requestSB.append("&encryptV="+AuthSDK.getInstance().getValue(IAuthInterface.KEY_ENCRYPTV));

        String publicKey = AppUtils.toURLEncoded(AuthSDK.getInstance().getValue(IAuthInterface.KEY_PUBLICKEY));
        requestSB.append("&publicKey="+publicKey);

        String vipUrl = requestSB.toString();
        RequestParams requestParams = new RequestParams(vipUrl, null, new RequestParams.RequestListener() {
            @Override
            public boolean onResponse(int i, String s, int i1, Object o) {
                if(!TextUtils.isEmpty(s)){
                    VipStateModel vipStateModel = JsonUtil.fromJson(s, VipStateModel.class);
                    if(vipStateModel != null){
                        for(VipStateModel.UpmInfoEntity.PlanAndCategoryBOsEntity data: vipStateModel.getUpmInfo().getPlanAndCategoryBOs()){
                            if(data != null && "40814315811460000001283".equalsIgnoreCase(data.getObjectBizId())){
                                //说明订购的是华数VIP包
                                AuthSDK.getInstance().saveValue("vipState", data.getAdFree()+"");
                                WLog.i("danxx", "vipState: "+data.getAdFree());
                                AuthSDK.getInstance().saveValue("vipExpireTime", data.getExpireTime()+"");
                                WLog.i("danxx", "vipExpireTime: "+data.getExpireTime());
                            }
                        }
                    }
                }else{
                    WLog.e("danxx", "getUserVipState return String--->null");
                }
                bindUserData();
                return false;
            }
        });
        HttpRequestModule.getInstance().addTask(requestParams);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mainVipPagePresenter.detachView();
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(v.getId() == R.id.userIconFocus){
            FocusAnimUtils.animItem(v , hasFocus ,1.02f);
            return;
        }
        FocusAnimUtils.animItem(v , hasFocus ,1.1f);
    }
    /**
     * 統一登录页面
     */
    private VipDialogLogin webPage;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.userIcon:
                break;
            case R.id.userIconFocus:
                String headUrl = ConfigUtils.getString(mContext, "usercenter", "headUrl");
                if (!TextUtils.isEmpty(headUrl) && AuthSDK.getInstance().getValue(IAuthInterface.KEY_ENCRYPTV) != null && AuthSDK.getInstance().getValue(IAuthInterface.KEY_PUBLICKEY) != null) {
                    //跳转营业厅
                    if(leftData.size()>0)
                    IntentMap.startIntent(mContext, null, "Wasu_UserCenter", leftData.get(0).getJsonUrl(), null);
                    WasuStatistics.getInstance().homeItemClick(AppUtil.MAIN_PAGERVIEW_POSITION, "vip","1_1","","");
                }else{
                    /**
                     * 用户登录窗口回调监听
                     */
                    webPage.setLoginStatusListener(new VipDialogLogin.LoginStatusListener() {

                        @Override
                        public void onLogStatus(boolean arg0) {

                            if (arg0) {
                                //登录成功重新绑定数据刷新UI
                                getUserVipState();
                            } else {
                                Toast.makeText(mContext, "登录失败", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                    if(!webPage.isShowing()){
                        webPage.show();
                    }
                }
                break;
            case R.id.zhangdan:
                //跳转账单
                if(leftData.size()>0)
                IntentMap.startIntent(mContext, null, "Wasu_UserCenter", leftData.get(1).getJsonUrl(), null);
                AppUtil.playEnter = PageName+"_1_1";
                WasuStatistics.getInstance().homeItemClick(AppUtil.MAIN_PAGERVIEW_POSITION, "vip","1_2","","");
                break;
            case R.id.adBannerFocus:
                AppUtil.playEnter = PageName+"_1_2";
                WasuStatistics.getInstance().homeItemClick(AppUtil.MAIN_PAGERVIEW_POSITION, "vip","1_3","","");
                int adPosition  = adBanner.getCurrentItem();
                if(adBannerData!=null && adBannerData.size()>0) {
                    String adcsjsonurl = adBannerData.get(adPosition).getJsonUrl();
                    String adcslayout = adBannerData.get(adPosition).getLayout();
                    IntentMap.startIntent(mContext, null, adcslayout, adcsjsonurl, null);
                }
                break;
            case R.id.function_01:
                if(rightData!=null && rightData.size()>0){
                    AppUtil.playEnter = PageName+"_1_3";
                    WasuStatistics.getInstance().homeItemClick(AppUtil.MAIN_PAGERVIEW_POSITION, "vip","1_4","","");
                    IntentMap.startIntent(mContext,null,"Wasu_UserCenter" ,rightData.get(0).getJsonUrl(),null);
                }
                break;
            case R.id.function_02:
                if(rightData!=null && rightData.size()>0){
                    AppUtil.playEnter = PageName+"_1_4";
                    WasuStatistics.getInstance().homeItemClick(AppUtil.MAIN_PAGERVIEW_POSITION, "vip","1_5","","");
                    IntentMap.startIntent(mContext,null,"Wasu_UserCenter" ,rightData.get(1).getJsonUrl(),null);
                }
                break;
            case R.id.function_03:
                if(rightData!=null && rightData.size()>0){
                    AppUtil.playEnter = PageName+"_1_5";
                    WasuStatistics.getInstance().homeItemClick(AppUtil.MAIN_PAGERVIEW_POSITION, "vip","1_6","","");
                    IntentMap.startIntent(mContext,null,"Wasu_UserCenter" ,rightData.get(2).getJsonUrl(),null);
                }
                break;
            default:

        }
    }

    public FocusRecyclerView getBodyRecyclerView(){
        return vipBodyRecyclerView;
    }

    class MyAdapater extends BaseFocusRecyclerViewAdapter<AssetsDataModel>{

        Context context;
        public MyAdapater(FocusRecyclerView recyclerView, Context context) {
            super(recyclerView);
            this.context = context;
        }

        /**
         * 创建item view
         *
         * @param parent
         * @param viewType
         * @return
         */
        @Override
        protected BaseFocusRecyclerViewHolder createItem(ViewGroup parent, int viewType) {
            View view  = LayoutInflater.from(context).inflate(R.layout.item_home_vip, null);
            MyViewHolder viewHolder = new MyViewHolder(view, getItemParent(), getItemListener());
            return viewHolder;
        }

        /**
         * 绑定数据
         *
         * @param holder
         * @param position
         */
        @Override
        protected void bindData(BaseFocusRecyclerViewHolder holder, int position) {
            ((MyViewHolder)holder).name.setText(getItemData(position).getTitle());
//            ((MyViewHolder)holder).pic.setImageResource(R.drawable.default_wasu_bg);
            holder.itemView.setTag(getItemData(position).getPicUrl());
            if(!isFirst)
                FrescoImageFetcherModule.getInstance().attachImage(getItemData(position).getPicUrl(), ((MyViewHolder)holder).pic);
        }

        public class MyViewHolder extends BaseFocusRecyclerViewHolder{

            View view;
            ImageView pic;
            TextView name;

            /**
             * 创建FocusRecyclerView的itemView
             *
             * @param itemView          item View
             * @param focusRecyclerView item parent ViewGroup(Parent must instanceof FocusRecyclerView)
             * @param mOnItemListener   item click、longClick、focusChange listener
             */
            public MyViewHolder(View itemView, FocusRecyclerView focusRecyclerView, OnItemListener mOnItemListener) {
                super(itemView, focusRecyclerView, mOnItemListener);
                view = itemView;
                pic = (ImageView) itemView.findViewById(R.id.ivPic);
                name = (TextView) itemView.findViewById(R.id.tvName);
            }

            @Override
            protected View getView() {
                return view;
            }
        }
    }

    /**
     * itemView晃动动画
     * @param view
     * @return
     */
    public ObjectAnimator shockAnim(View view){
        ObjectAnimator animator= AnimTools.shock(view);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                postInvalidate();
            }
        });
        animator.start();
        return animator;
    }
    /***********************************************************************************************/
    /**
     * 回收和显示页面上的图片资源，减少内存占用
     */
    final Handler imageViewHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            int what = msg.what;
            if(MSG_RecycleImageView == what){
                recycleImageViewTask();
            }else if(MSG_ShowImageView == what){
                showImageViewTask();
            }
            return false;
        }
    });

    public void recycleImageView(){
//        imageViewHandler.removeMessages(MSG_ShowImageView);
//        imageViewHandler.removeMessages(MSG_RecycleImageView);
//        imageViewHandler.sendEmptyMessageDelayed(MSG_RecycleImageView, 600);
    }

    public void showImageView(){
//        imageViewHandler.removeMessages(MSG_ShowImageView);
//        imageViewHandler.removeMessages(MSG_RecycleImageView);
//        imageViewHandler.sendEmptyMessageDelayed(MSG_ShowImageView, 600);
    }

    private void recycleImageViewTask(){
        if(vipBodyRecyclerView!=null){
            vipBodyRecyclerView.scrollToPosition(0);
        }
        if(iv_zhangdan!=null){
            iv_zhangdan.setImageBitmap(null);
        }
        if(function_01!=null){
            function_01.setImageBitmap(null);
        }
        if(function_02!=null){
            function_02.setImageBitmap(null);
        }
        if(function_03!=null){
            function_03.setImageBitmap(null);
        }
        if(vipBodyRecyclerView != null && vipBodyRecyclerView.getChildCount()>0){
            int itemCount = vipBodyRecyclerView.getChildCount();
            for(int i=0;i<itemCount;i++){
                View itemView = vipBodyRecyclerView.getChildAt(i);
                if(itemView != null){
                    ImageView imageView = (ImageView) itemView.findViewById(R.id.ivPic);
                    if(imageView != null){
                        imageView.setImageBitmap(null);
                    }
                }
            }
        }
        isRecycled = true;
    }

    private void showImageViewTask(){
        isFirst = false;
        if(vipBodyRecyclerView!=null){
            vipBodyRecyclerView.scrollToPosition(0);
        }
        if(iv_zhangdan!=null && iv_zhangdan.getTag()!=null){
            FrescoImageFetcherModule.getInstance().attachImage(iv_zhangdan.getTag().toString(),iv_zhangdan);
        }
        if(function_01!=null && function_01.getTag()!=null){
            FrescoImageFetcherModule.getInstance().attachImage(function_01.getTag().toString(),function_01);
        }
        if(function_02!=null && function_02.getTag()!=null){
            FrescoImageFetcherModule.getInstance().attachImage(function_02.getTag().toString(),function_02);
        }
        if(function_03!=null && function_03.getTag()!=null){
            FrescoImageFetcherModule.getInstance().attachImage(function_03.getTag().toString(),function_03);
        }
        if(vipBodyRecyclerView != null && vipBodyRecyclerView.getChildCount()>0){
            int itemCount = vipBodyRecyclerView.getChildCount();
            for(int i=0;i<itemCount;i++){
                View itemView = vipBodyRecyclerView.getChildAt(i);
                if(itemView == null ||itemView.getTag() == null)
                    continue;
                String url = itemView.getTag().toString();
                if(itemView != null && url != null && !TextUtils.isEmpty(url)){
                    ImageView imageView = (ImageView) itemView.findViewById(R.id.ivPic);
                    FrescoImageFetcherModule.getInstance().attachImage(url, imageView);
                }
            }
        }
        isRecycled = false;
    }
}
