package com.wasu.cs.ui;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wasu.authsdk.AuthListener;
import com.wasu.authsdk.AuthSDK;
import com.wasu.authsdk.IAuthInterface;
import com.wasu.authsdk.entity.OrderPlanList;
import com.wasu.authsdk.entity.UserOrderPlan;
import com.wasu.comp.userlogin.DialogLogin;
import com.wasu.compfactory.WasuCompFactory;
import com.wasu.cs.adapter.BlockPageAdapter;
import com.wasu.cs.model.CatData;
import com.wasu.cs.model.CatData.BaseElement;
import com.wasu.cs.model.VipStateModel;
import com.wasu.cs.utils.JsonUtil;
import com.wasu.cs.widget.FocusGridViewEx;
import com.wasu.cs.widget.mediacontrol.DialogCommonPlanBuy;
import com.wasu.cs.widget.mediacontrol.DialogPlanBuy;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
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.morphingbutton.MorphingButton;
import com.wasu.widgets.tools.AppUtils;

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

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;

/**
 * 4.0二级列表的Header部分，包含搜索筛选按钮和cat的item
 * Created by LiuYang on 6/23/15.
 */
public class FragmentBlockHeader extends FragmentChannelBase {

	private RelativeLayout mTopLayout;
	private MorphingButton btnDingbao, mSearchBtn, mFilterBtn;
	private TextView mTitleView,mtabname,friendlytext;
	private LinearLayout mTabLayout,tabNameLayout;
	private ImageView userIconLayout;
	private LinearLayout userCenterLayout;

	private ViewPager mViewPager;
	private BlockPageAdapter mTabAdapter;
	private DialogLogin loginDialog;
	private DialogCommonPlanBuy paydialog;
	private boolean isTabAdded = false;
	private int mCurrentIndex = -1;
	private boolean mTopLayoutHide = false;
	private boolean isLastTabFocused = false;
	private boolean isFirstTabFocused = false;

	private ImageView ivUserIcon;
	private int mTopLayoutHeight;
	private VipStateModel vipStateModel;
	private ViewWrapper mTopViewWrapper;
	private static final int SetCurrentItemMSG = 1;
	private static final int UpdateDingbaoUI = 2;
	private SparseArray<Map> planparams = new SparseArray<>();
	private CatData catData; // 保存栏目的所有信息
	private int preSize = 0; // 是否包含筛选和搜索

	/*标识是什么栏目,例如搜狐资产列表的catProp为5*/
	private int catProp = -1;
	/**/
	private String infoText;
	private String assetFrom = "";
	private boolean isVip = false;
	private boolean isLoaded = false;
	private BaseElement mSearchElement;
	private BaseElement mFilterElement;
	public static boolean headerFocused = false;
	public static boolean viewpagerRightSlide = false;
	private final static String TAG = FragmentBlockHeader.class.getSimpleName();
	private static final String XDYYH = " 续订有优惠";
	private static final String KDVIP = " 开通VIP";
	private static final String QDL = " 请登录";
	private static final int AnimaDrration = 200;

	private View.OnFocusChangeListener mTabFocusListener = new View.OnFocusChangeListener() {
		@Override
		public void onFocusChange(View view, boolean b) {
			if (b) {
				headerFocused = true;
				mTitleView.setText(((TextView) view).getText());
				mCurrentIndex = Integer.parseInt((String) view.getTag());
				mTitleView.setTag(mCurrentIndex);

				/**监听最后一个tabItem的焦点**/
				isLastTabFocused = (mCurrentIndex == mTabAdapter.getCount() - 1);

				if (mCurrentIndex == 0) {
					isFirstTabFocused = true;
				}
				mHandler2.removeMessages(SetCurrentItemMSG);
				mHandler2.sendEmptyMessageDelayed(SetCurrentItemMSG, 100);
			} else {
				headerFocused = false;
				if (isLastTabFocused) {
					isLastTabFocused = false;
				}
				if (isFirstTabFocused) {
					isFirstTabFocused = false;
				}
			}

			animTab(view, b);
		}
	};
	private final Handler mHandler2 = new Handler(new Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
				case SetCurrentItemMSG:
					if (getActivity() != null) {
						mViewPager.setCurrentItem(mCurrentIndex, false);
					}
					break;
				case UpdateDingbaoUI:
					if (isLoaded) {
						if (isVip) {
							infoText = XDYYH;
							//btnDingbao.setText("立即续订");
							vipInfoMorphTotext(infoText);
						} else {
							infoText = KDVIP;
							vipInfoMorphTotext(infoText);
							//btnDingbao.setText("立即订包");
						}
					}else {

					}
					break;
				default:
					break;
			}
			return false;
		}
	});
//    private Runnable mDelayPageSwitchRunable = new Runnable() {
//		@Override
//		public void run() {
//            if(mViewPager != null) {
//                mViewPager.setCurrentItem(mCurrentIndex);
//            }
//		}
//	};

	/**
	 * header的tabItem响应遥控器的ok键隐藏header
	 **/
	private View.OnClickListener mTabOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View view) {
			if (view.hasFocus()) {
				hideTopLayout();
				mViewPager.requestFocus();
			}
		}
	};

	private View.OnClickListener mSearchBtnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View view) {
			if (mSearchElement != null) {
				AppUtil.playEnter = mSearchElement.getName();
				IntentMap.startIntent(getActivity(), null, mSearchElement.getLayout(), mSearchElement.getJsonUrl(), null);
			}
		}
	};

	private View.OnClickListener mFilterBtnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View view) {
			if (mFilterElement != null) {
				AppUtil.playEnter = mFilterElement.getName();
				IntentMap.startIntent(getActivity(), null, mFilterElement.getLayout(), mFilterElement.getJsonUrl(), null);
			}
		}
	};

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_block_header, null);
		mTopLayout = (RelativeLayout) rootView.findViewById(R.id.topLayout);
		btnDingbao = (MorphingButton) rootView.findViewById(R.id.btnVipInfo);
		//btnDingbao.setTextSize(getResources().getDimensionPixelSize(R.dimen.s_10sp));
		mSearchBtn = (MorphingButton) rootView.findViewById(R.id.btnSearch);
		mFilterBtn = (MorphingButton) rootView.findViewById(R.id.btnFilter);
		btnDingbao.setOnFocusChangeListener(focuschangelistener);

		mSearchBtn.setOnClickListener(mSearchBtnClickListener);
		mFilterBtn.setOnClickListener(mFilterBtnClickListener);
		friendlytext = (TextView) rootView.findViewById(R.id.friendlytext);
		mTitleView = (TextView) rootView.findViewById(R.id.titleView);
		mtabname = (TextView) rootView.findViewById(R.id.tvtabname);
		mTabLayout = (LinearLayout) rootView.findViewById(R.id.tabLayout);
		tabNameLayout = (LinearLayout) rootView.findViewById(R.id.tabnamelayout);
		mTopViewWrapper = new ViewWrapper(mTopLayout);
		userIconLayout = (ImageView) rootView.findViewById(R.id.userIconLayout);
		userCenterLayout = (LinearLayout) rootView.findViewById(R.id.userCenterLayout);
		ivUserIcon = (ImageView) rootView.findViewById(R.id.ivUserIcon);
		loginDialog = new WasuCompFactory().createUniLogin(getContext(), Common.loginurl);
		return rootView;
	}

	@Override
	protected boolean onBackPressed() {
		if (mTopLayoutHide) {
			showTopLayout();
			View tab = getTab(mCurrentIndex);
			if (tab != null) {
				tab.requestFocus();
			}
		}

		return false;
	}
	public void setViewPager(ViewPager viewPager) {
		this.mViewPager = viewPager;
		this.mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
			}

			@Override
			public void onPageSelected(int position) {

				if (position < mTabLayout.getChildCount()) {

					if (catData != null && catData.getCat() != null && position + preSize < catData.getChildCats().size()) {
						WasuStatistics.getInstance().columnClick(catData.getCat().getName(),
								catData.getChildCats().get(position + preSize).getName(), catData.getChildCats().get(position + preSize).getCatId() + "");

						if (getActivity() instanceof ActivityChannel) { //强行转换设置需要上传的值
							((ActivityChannel) getActivity()).setViewName(catData.getChildCats().get(position + preSize).getName());
						}

//                    WLog.e("tag", "first = "+catData.getCat().getName()+
//                            " second = "+catData.getChildCats().get(position+preSize).getName()+
//                            " third = "+ catData.getChildCats().get(position+preSize).getCatId()+" preSize = "+preSize );
					}

					mCurrentIndex = position;
					if (mTitleView.getVisibility() == View.VISIBLE) {
						TextView curTextView = (TextView) mTabLayout.getChildAt(mCurrentIndex);
						mTitleView.setText(curTextView.getText());
						/**在ViewPager向右滑动切换时保证左边一屏第一排最后一个item被选中**/
						if (Integer.parseInt(mTitleView.getTag().toString()) > position) {
							viewpagerRightSlide = true;
							FocusGridViewEx mGridView = (FocusGridViewEx) mViewPager.findViewWithTag("tag" + position);
							if (null != mGridView) {
								if (mGridView.getChildCount() >= 6) {
									mGridView.setSelectedViewIndex(5);
								} else if (mGridView.getChildCount() > 0) {
									mGridView.setSelectedViewIndex(mGridView.getChildCount() - 1);
								} else {

								}
							} else {

							}
						} else {
							viewpagerRightSlide = false;
						}
					}
				}
				mTitleView.setTag(position);
			}

			@Override
			public void onPageScrollStateChanged(int state) {

			}
		});
	}


	/*设置栏目标识*/
	public void setCatProp(int catProp) {
		this.catProp = catProp;
		/*订包用户信息*/
		bindUserData();
	}

	public void setSearchElement(BaseElement element) {
		this.mSearchElement = element;
		mSearchBtn.setVisibility(View.VISIBLE);
		//mSearchBtn.setTextSize(getResources().getDimensionPixelSize(R.dimen.s_10sp));
		mSearchBtn.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus){
					searchBtnFocused(AnimaDrration);
				}
				searchBtnunFocused(AnimaDrration);

			}
		});
		mSearchBtn.setVisibility(View.VISIBLE);
		searchBtnunFocused(AnimaDrration);
	}

	public void setFilterElement(BaseElement element) {
		this.mFilterElement = element;
		mFilterBtn.setVisibility(View.VISIBLE);
		//mFilterBtn.setTextSize(getResources().getDimensionPixelSize(R.dimen.s_10sp));
		mFilterBtn.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus){
					filterBtnFocused(AnimaDrration);
				}
				filterBtnUnfocused(AnimaDrration);
			}
		});
		mFilterBtn.setVisibility(View.VISIBLE);
		filterBtnUnfocused(AnimaDrration);
	}
	private View.OnFocusChangeListener focuschangelistener = new View.OnFocusChangeListener() {
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			if (hasFocus) {
				vipInfounfocused(infoText);
			} else {
				vipInfoMorphTotext(infoText);
			}
		}
	};
	/**
	 * search button change to circle state
	 * @param duration
	 */
	private void searchBtnunFocused(int duration) {
		MorphingButton.Params circle = MorphingButton.Params.create()
				.duration(duration)
				.cornerRadius(getDimenPixel(R.dimen.d_36dp))
				.width(getDimenPixel(R.dimen.d_36dp))
				.height(getDimenPixel(R.dimen.d_36dp))
				.icon(R.drawable.channel_search)
				.color(getResources().getColor(R.color.channel_icon_bg));
		mSearchBtn.morph(circle);
	}
	private void searchBtnFocused(int duration){
		filterBtnUnfocused(duration);
		MorphingButton.Params circle = MorphingButton.Params.create()
				.duration(duration)
				.cornerRadius(getDimenPixel(R.dimen.d_36dp))
				.width(getDimenPixel(R.dimen.d_88dp))
				.height(getDimenPixel(R.dimen.d_36dp))
				.icon(R.drawable.channel_search_focused)
				.strokeColor(getResources().getColor(R.color.yellow))
				.strokeWidth(getDimenPixel(R.dimen.d_2dp))
				.color(getResources().getColor(R.color.channel_icon_bg))
				.text(getResources().getString(R.string.search_text));
		mSearchBtn.morph(circle);
	}
	/**
	 * filter button change to circle state
	 * @param duration
	 */
	private void filterBtnUnfocused(int duration) {
		MorphingButton.Params oval = MorphingButton.Params.create()
				.duration(duration)
				.cornerRadius(getDimenPixel(R.dimen.d_36dp))
				.width(getDimenPixel(R.dimen.d_36dp))
				.height(getDimenPixel(R.dimen.d_36dp))
				.icon(R.drawable.channel_filter)
				.color(getResources().getColor(R.color.channel_icon_bg));
		mFilterBtn.morph(oval);
	}
	private void filterBtnFocused(int duration) {
		searchBtnunFocused(duration);
		MorphingButton.Params oval = MorphingButton.Params.create()
				.duration(duration)
				.cornerRadius(getDimenPixel(R.dimen.d_36dp))
				.width(getDimenPixel(R.dimen.d_88dp))
				.height(getDimenPixel(R.dimen.d_36dp))
				.icon(R.drawable.channel_filter_focused)
				.strokeColor(getResources().getColor(R.color.yellow))
				.strokeWidth(getDimenPixel(R.dimen.d_2dp))
				.color(getResources().getColor(R.color.channel_icon_bg))
				.text(getResources().getString(R.string.filter_text));
		mFilterBtn.morph(oval);
	}
	private void vipInfounfocused(String text){
		//searchBtnunFocused(AnimaDrration);
		//filterBtnUnfocused(AnimaDrration);
		MorphingButton.Params oval = MorphingButton.Params.create()
				.cornerRadius(getDimenPixel(R.dimen.d_36dp))
				.width(getDimenPixel(R.dimen.d_130dp))
				.height(getDimenPixel(R.dimen.d_36dp))
				.text(text)
				.colorPressed(getResources().getColor(R.color.channel_icon_bg))
				.color(getResources().getColor(R.color.channel_icon_bg));
		btnDingbao.morph(oval);

	}
	private void vipInfoMorphTotext(String text){
		MorphingButton.Params oval = MorphingButton.Params.create()
				.cornerRadius(getDimenPixel(R.dimen.d_36dp))
				.width(getDimenPixel(R.dimen.d_130dp))
				.height(getDimenPixel(R.dimen.d_36dp))
				.text(text)
				.colorPressed(getResources().getColor(R.color.channel_icon_bg))
				.color(getResources().getColor(R.color.channel_icon_bg));
		btnDingbao.morph(oval);
	}

	/**
	 * 对header部分的焦点处理
	 *
	 * @param focused
	 * @param direction
	 * @return
	 */
	public View focusSearch(View focused, int direction) {
		View res = null;

		switch (direction) {
			case View.FOCUS_UP:
				if (mTabLayout.hasFocus()) {
					res = userIconLayout;
				} else if (hasTopFocus()) {
					res = focused;
				} else if (btnDingbao.hasFocus()) {
					res = btnDingbao;
				} else {
					/**防止焦点丢失**/
					showTopLayout();
					if (mCurrentIndex >= 0 && mCurrentIndex < mTabLayout.getChildCount()) {
						res = mTabLayout.getChildAt(mCurrentIndex);
					} else {
						res = mTabLayout;
					}
				}

				break;
			case View.FOCUS_DOWN:
				if (hasTopFocus() || userCenterLayout.hasFocus() || btnDingbao.hasFocus()) {
					if (mCurrentIndex > 0 && mCurrentIndex < mTabLayout.getChildCount()) {
						res = mTabLayout.getChildAt(mCurrentIndex);
					} else {
						res = mTabLayout;
					}
				} else if (mTabLayout.hasFocus()) {
					hideTopLayout();
				}
				break;
			case View.FOCUS_LEFT:
				if (mSearchBtn.hasFocus()) {
//                    res = focused;
					if (View.VISIBLE == btnDingbao.getVisibility()) {
						res = btnDingbao;
					} else {
						res = userIconLayout;
					}
				} else if (mFilterBtn.hasFocus()) {
					res = mSearchBtn;
				} else if (isFirstTabFocused) {
					res = focused;
				} else if (btnDingbao.hasFocus()) {
					res = userIconLayout;
				} else if (userIconLayout.hasFocus()) {
					res = focused;
				}
				break;
			case View.FOCUS_RIGHT:
				if (mFilterBtn.hasFocus()) {
					res = focused;
				} else if (mSearchBtn.hasFocus()) {
					res = mFilterBtn;
				} else if (userIconLayout.hasFocus()) {
					if (btnDingbao.getVisibility() == View.VISIBLE) {
						res = btnDingbao;
					} else {
						res = mSearchBtn;
					}
				} else if (btnDingbao.hasFocus()) {
					res = mSearchBtn;
				}

//                else if (isLastTabFocused) {
//					res = focused;
//				}
				break;
		}

		return res;
	}

	private void hideTopLayout() {
		mTopLayoutHeight = mTopLayout.getMeasuredHeight();
		ObjectAnimator animator = ObjectAnimator.ofInt(mTopViewWrapper, "value", -mTopLayoutHeight);
		animator.setInterpolator(new DecelerateInterpolator());
		animator.addListener(new Animator.AnimatorListener() {
			@Override
			public void onAnimationStart(Animator animator) {
				userCenterLayout.setVisibility(View.INVISIBLE);
			}

			@Override
			public void onAnimationEnd(Animator animator) {
				mTopLayoutHide = true;
				mTopLayout.setVisibility(View.GONE);
				mTabLayout.setVisibility(View.INVISIBLE);
				mTitleView.setVisibility(View.VISIBLE);
				friendlytext.setVisibility(View.VISIBLE);
				tabNameLayout.setVisibility(View.VISIBLE);

			}

			@Override
			public void onAnimationCancel(Animator animator) {

			}

			@Override
			public void onAnimationRepeat(Animator animator) {

			}
		});
		animator.setDuration(AnimaDrration).start();
	}

	//Todo need animation here
	private void showTopLayout() {

		ObjectAnimator animator = ObjectAnimator.ofInt(mTopViewWrapper, "value", 0);
		animator.setInterpolator(new DecelerateInterpolator());
		animator.addListener(new Animator.AnimatorListener() {
			@Override
			public void onAnimationStart(Animator animator) {
				isVip();//考虑到用户可能进入详情页后登陆了账号，
			}

			@Override
			public void onAnimationEnd(Animator animator) {
				mTopLayoutHide = false;
				mTopLayout.setVisibility(View.VISIBLE);
				mTitleView.setVisibility(View.INVISIBLE);
				mTabLayout.setVisibility(View.VISIBLE);
				friendlytext.setVisibility(View.INVISIBLE);
				userCenterLayout.setVisibility(View.VISIBLE);
				tabNameLayout.setVisibility(View.INVISIBLE);
			}

			@Override
			public void onAnimationCancel(Animator animator) {

			}

			@Override
			public void onAnimationRepeat(Animator animator) {

			}
		});
		animator.setDuration(AnimaDrration).start();
	}

	public boolean hasTopFocus() {
		return mSearchBtn.hasFocus() || mFilterBtn.hasFocus();
	}

	public void setTabAdapter(BlockPageAdapter adapter) {
		this.mTabAdapter = adapter;

		this.mTabAdapter.registerDataSetObserver(new DataSetObserver() {
			@Override
			public void onChanged() {
				if (!isTabAdded) {
					setupTabs();
					isTabAdded = true;
				}
			}
		});
	}

	/**
	 * 初始化tabItem,填充数据
	 */
	private void setupTabs() {
		mtabname.setText(catData.getCat().getName());
		mTabLayout.removeAllViews();
		int count = this.mTabAdapter.getCount();
		/*哪一个tab item默认被选中*/
		int tabSelected = this.mTabAdapter.getTabSelected();
		/**
		 * 记录第一个选中焦点的name
		 * */
		if (getActivity() instanceof ActivityChannel && tabSelected < count) { //强行转换设置需要上传的值
			((ActivityChannel) getActivity()).setViewName(mTabAdapter.getPageTitle(tabSelected) + "");
		}
		for (int i = 0; i < count; i++) {
			TextView tabItem = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.item_video_tab, null);
			tabItem.setText(mTabAdapter.getPageTitle(i));
			tabItem.setOnFocusChangeListener(mTabFocusListener);
			tabItem.setClickable(true);
			tabItem.setOnClickListener(mTabOnClickListener);
			tabItem.setFocusableInTouchMode(true);
			tabItem.setTag("" + i);
			mTabLayout.addView(tabItem);
			if (tabSelected != 0) {
				if (tabSelected < count && tabSelected == i) {
					tabItem.requestFocus();
				} else {
					if (i == 0) {
						/**进入二级列表页，默认焦点在第一个tabItem**/
						tabItem.requestFocus();
						tabItem.setId(R.id.firstTabId);
					}
				}
			} else {
				if (i == 0) {
					/**进入二级列表页，默认焦点在第一个tabItem**/
					tabItem.requestFocus();
					tabItem.setId(R.id.firstTabId);
				}
			}

			if (i == (count - 1)) {
				tabItem.setId(R.id.lastTabId);
				tabItem.setNextFocusRightId(R.id.firstTabId);
			}
		}
	}

	private View getTab(int index) {
		return mTabLayout.getChildAt(index);
	}

	private void animTab(View view, boolean scale) {
		float toValue = 1.0f;
		if (scale) {
			toValue = 1.3f;
		}
		ObjectAnimator animatorX = ObjectAnimator.ofFloat(view, "scaleX", toValue);
		ObjectAnimator animatorY = ObjectAnimator.ofFloat(view, "scaleY", toValue);
		AnimatorSet animatorSet = new AnimatorSet();
		animatorSet.setDuration(AnimaDrration);
		animatorSet.playTogether(animatorX, animatorY);
		animatorSet.start();
	}

	class ViewWrapper {

		private View mTargetView;

		public ViewWrapper(View target) {
			mTargetView = target;
		}

		public int getValue() {
			RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mTargetView.getLayoutParams();
			return layoutParams.topMargin;
		}

		public void setValue(int value) {
			RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mTargetView.getLayoutParams();
			layoutParams.topMargin = value;
			mTargetView.setLayoutParams(layoutParams);
//            mTargetView.requestLayout();
		}
	}

	/**
	 * 绑定用户信息
	 */
	private void bindUserData() {
		final String headUrl = ConfigUtils.getString(getActivity(), "usercenter", "headUrl");
		if (catProp == 5) { //说明是sohu资产
			assetFrom = "SOHU";
			WLog.d("TAG", "assetFrom == SOHU");
			btnDingbao.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					DialogPlanBuy dialogPlanBuy = new DialogPlanBuy(getActivity(), Common.OtherOrderUrl, assetFrom, new DialogPlanBuy.PayStatusListener() {
						@Override
						public void onPay(int status, int code) {
							WLog.d(TAG, "status:" + status + "--cade:" + code);
							if (status == 0) {
								Toast.makeText(getActivity(), "订购成功", Toast.LENGTH_SHORT).show();
							} else {
								Toast.makeText(getActivity(), "订购失败", Toast.LENGTH_SHORT).show();
							}
						}
					});
					dialogPlanBuy.show();
				}
			});
			btnDingbao.setVisibility(View.VISIBLE);
		} else {  //说明是华数资产
			assetFrom = "WASU";
			WLog.d("TAG", "assetFrom == WASU");
			btnDingbao.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (!TextUtils.isEmpty(headUrl) && AuthSDK.getInstance().getValue(IAuthInterface.KEY_USERKEY) != null
							&& AuthSDK.getInstance().getValue(IAuthInterface.KEY_TOKEN) != null) {
						if (!isVip) {//跳转订包
							IntentMap.startIntent(getActivity(), null,
									"Wasu_UserCenter",
									"http://vip.wasu.tv/business/2002/jsp/business/allProducts.jsp", null);
						} else {//跳转续订
							//getUserVipState();
							AuthSDK.getInstance().queryOrderPlanByUser(new AuthListener() {
								@Override
								public void result(int i, String s, Object o) {
									UserOrderPlan userOrderPlan = (UserOrderPlan) o;
									orderMonthPlan(userOrderPlan.getList().get(0).objectBizId);
								}
							});

						}
					}else {
						showLoadingDialog();
					}
				}
			});
		}

		userIconLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!TextUtils.isEmpty(headUrl) && AuthSDK.getInstance().getValue(IAuthInterface.KEY_USERKEY) != null
						&& AuthSDK.getInstance().getValue(IAuthInterface.KEY_TOKEN) != null) {
					IntentMap.startIntent(getActivity(), null, "Wasu_UserCenter", Common.UserCenterUrl, null);
				} else {
					showLoadingDialog();
				}
			}
		});

		// 判断用户是否登录
		if (isUserLoaded()) {
			// 如果已经登陆
			//isLoaded = true;
			WLog.d(TAG, "user login--headUrl-->" + headUrl);
			if (TextUtils.isEmpty(headUrl)) {
				//tvChannelUserCenter.showName(AuthSDK.getInstance().getValue(IAuthInterface.KEY_PHONE));
				LayoutParams params = ivUserIcon.getLayoutParams();
				params.height = getDimenPixel(R.dimen.d_30dp);
				params.width = getDimenPixel(R.dimen.d_30dp);
				ivUserIcon.setImageDrawable(getResources().getDrawable(R.drawable.channel_logo));
				ivUserIcon.setLayoutParams(params);
				getUserVipState();
			} else {
				//tvChannelUserCenter.showName(AuthSDK.getInstance().getValue(IAuthInterface.KEY_PHONE));
				LayoutParams params = ivUserIcon.getLayoutParams();
				params.height = getDimenPixel(R.dimen.d_46dp);
				params.width = getDimenPixel(R.dimen.d_46dp);
				FrescoImageFetcherModule.setRouteDisplayImager(ivUserIcon, headUrl);
				ivUserIcon.setLayoutParams(params);
				btnDingbao.setVisibility(View.VISIBLE);
			}
			if (isVip()) {
				infoText = XDYYH;
				vipInfoMorphTotext(infoText);
				//btnDingbao.setText("立即续订");
			} else {
				infoText = KDVIP;
				vipInfoMorphTotext(infoText);
				//btnDingbao.setText("立即订包");
			}
			btnDingbao.setVisibility(View.VISIBLE);
		} else {
			//WLog.d(TAG, "user didn't login");
			//btnDingbao.setVisibility(View.GONE);
			//tvChannelUserCenter.showDefault();
			LayoutParams params = ivUserIcon.getLayoutParams();
			params.height = getDimenPixel(R.dimen.d_30dp);
			params.width = getDimenPixel(R.dimen.d_30dp);
			ivUserIcon.setImageDrawable(getResources().getDrawable(R.drawable.default_user_icon));//default user icon
			ivUserIcon.setLayoutParams(params);
			infoText = QDL;
			vipInfoMorphTotext(infoText);//显示请登录
			/*if (catProp == 5) {
				btnDingbao.setVisibility(View.VISIBLE);
			} else {
				btnDingbao.setVisibility(View.GONE);
			}*/
		}
    }

	/**
	 * 判断用户是否登陆
	 */
	private boolean isUserLoaded(){
		final String headUrl = ConfigUtils.getString(getActivity(), "usercenter", "headUrl");
		if(!TextUtils.isEmpty(headUrl) && AuthSDK.getInstance().getValue(IAuthInterface.KEY_USERKEY) != null
				&& AuthSDK.getInstance().getValue(IAuthInterface.KEY_TOKEN) != null){
			isLoaded = true;
		}else {
			isLoaded = false;
		}
		return isLoaded;
	}

	/**
	 * show user loading dialog
	 */
    private void showLoadingDialog(){
	    loginDialog.setLoginStatusListener(new DialogLogin.LoginStatusListener() {
		    @Override
		    public void onLogStatus(boolean b) {
			    if (b) {
				    getUserVipState();
			    } else {
				    Toast.makeText(getActivity(), "登陆失败", Toast.LENGTH_LONG).show();
			    }
		    }
	    });
	    if (!loginDialog.isShowing()) {
		    loginDialog.show();
	    }
    }
    @Override
    public void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    	/*需要catProp设置后才能绑定用户信息*/
    	if(-1 != catProp){
    		bindUserData();
    	}
    }
	/**
	 * 请求获取用户的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 = JsonUtil.fromJson(s, VipStateModel.class);
					if (vipStateModel != null) {
						for (VipStateModel.UpmInfoEntity.PlanAndCategoryBOsEntity data : vipStateModel.getUpmInfo().getPlanAndCategoryBOs()) {
							if (data != null && "40814315811460000001283".equalsIgnoreCase(data.getObjectBizId())) {
								WLog.d("cm", data.getObjectName() + data.getObjectBizId() + data.getExpireTime() + data.getType());
								//说明订购的是华数VIP包
								AuthSDK.getInstance().saveValue("vipState", data.getAdFree() + "");
								AuthSDK.getInstance().saveValue("vipExpireTime", data.getExpireTime() + "");
							}
						}
					}
				} else {
					WLog.e("danxx", "getUserVipState return String--->null");
				}
				bindUserData();
				return false;
			}
		});
		HttpRequestModule.getInstance().addTask(requestParams);
	}

	private void orderMonthPlan(String CategoryBizId) {
		if (Common.WASU_PACKAGE_ID.equals(CategoryBizId)) {//我司月包
			queryMonthPlanInfo(CategoryBizId, Common.WASU_MONTH_PLAN_BUY);
		} else if (Common.SOHU_CATAGORYBIZ.equals(CategoryBizId)) {//搜狐月包
			queryMonthPlanInfo(CategoryBizId, Common.SOHU_MONTH_PLAN_BUY);
		}
	}

	private void queryMonthPlanInfo(String CategoryBizId, final String planBizId){
		Map<String, Object> categoryBizId = new HashMap<>();
		categoryBizId.put("categoryBizId", CategoryBizId);
		AuthSDK.getInstance().queryOrderPlanByCategoryBizId(categoryBizId, new AuthListener() {
			@Override
			public void result(int i, String s, Object o) {
				if (i == 0){
					List<OrderPlanList.OrderPlan> list = ((OrderPlanList) o).getList();
					if (list == null || list.size() <= 0) {
						return;
					}
					double price = 0;
					String name = "";
					for (int j = 0; j < list.size(); j++) {
						if (list.get(j).planBizId.equals(planBizId)) {//默认续订月包
							price = list.get(j).price;
							name = list.get(j).name;
							break;
						}
					}
					if (price == 0) return;
					Map<String, Object> params = new HashMap<>();
					params.put("planBizId", planBizId);
					params.put("resourceName", name);
					params.put("price", price);

					paydialog = new DialogCommonPlanBuy(getActivity(), BuildType.payTypeUrl, params, new DialogCommonPlanBuy.PayStatusListener() {
						@Override
						public void onPay(int status, int code) {
							if (status == 0) {
								Toast.makeText(getActivity(), "续订成功!", Toast.LENGTH_LONG).show();
							} else {
								if (code == 12) {
									Toast.makeText(getActivity(), "支付失败，请重新登录后再支付！", Toast.LENGTH_LONG).show();
								} else {
									Toast.makeText(getActivity(), "支付失败!", Toast.LENGTH_LONG).show();
								}
							}
						}
					});
					if (!paydialog.isShowing()) {
						paydialog.show();
					}

				}
			}
		});
	}


	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		cleanResource();
	}

	/**
	 * 判断用户是不是VIP
	 *
	 * @return
	 */
	private boolean isVip() {
		String isvip = AuthSDK.getInstance().getValue("vipState");
		if (!TextUtils.isEmpty(isvip)) {
			if ("0".equalsIgnoreCase(isvip)) {
				isVip = false;
				mHandler2.sendEmptyMessage(UpdateDingbaoUI);

			} else {
				isVip = true;
				mHandler2.sendEmptyMessage(UpdateDingbaoUI);

			}
		} else {
			isVip = false;
			mHandler2.sendEmptyMessage(UpdateDingbaoUI);

		}

		return isVip;

	}

	public void cleanResource() {

		if (btnDingbao != null) {
			btnDingbao = null;
		}
		if (mSearchBtn != null) {
			mSearchBtn = null;
		}
		if (mFilterBtn != null) {
			mFilterBtn = null;
		}
		if (mTitleView != null) {
			mTitleView = null;
		}
		if (mTopViewWrapper != null) {
			mTopViewWrapper = null;
		}
		if (mViewPager != null) {
			mViewPager.removeAllViews();
			mViewPager = null;
		}
		if (mTabAdapter != null) {
			mTabAdapter.clearData();
			mTabAdapter = null;
		}
		if (mTabLayout != null) {
			mTabLayout.removeAllViews();
			mTabLayout = null;
		}
		if (mTopLayout != null) {
			mTopLayout.removeAllViews();
			mTopLayout = null;
		}
		if (mHandler2 != null) {
			mHandler2.removeMessages(SetCurrentItemMSG);
			mHandler2.removeCallbacksAndMessages(null);
		}
	}

	public void saveData(CatData catData) {
		this.catData = catData;

		for (int i = 0; i < catData.getChildCats().size(); i++) {
			if ("children_search".equals(catData.getChildCats().get(i).getName()) || "筛选".equals(catData.getChildCats().get(i).getName())) {
				preSize++;
			}
		}
	}
}
