package com.yunbao.main.views;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.yunbao.common.CommonAppConfig;
import com.yunbao.common.Constants;
import com.yunbao.common.activity.AbsActivity;
import com.yunbao.common.adapter.ViewPagerAdapter;
import com.yunbao.common.bean.UserBean;
import com.yunbao.common.event.FollowEvent;
import com.yunbao.common.event.HomeHeadClickEvent;
import com.yunbao.common.event.VideoEvent;
import com.yunbao.common.event.VoiceEvent;
import com.yunbao.common.utils.CommonIconUtil;
import com.yunbao.common.utils.DpUtil;
import com.yunbao.common.utils.StringUtil;
import com.yunbao.common.utils.WordUtil;
import com.yunbao.main.R;
import com.yunbao.main.activity.UserHomeNewActivity;
import com.yunbao.main.dialog.ShowHomeDialogFragment;
import com.yunbao.one.views.AbsUserHomeViewHolder;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 个人主页
 */
// +———————————————————————————————————
// | Created by Yunbao
// +———————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +———————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +———————————————————————————————————
// | Date: 2022-03-22
// +———————————————————————————————————
public class UserHomeViewHolder extends AbsMainViewHolder implements AppBarLayout.OnOffsetChangedListener {

    private static final int PAGE_COUNT = 2;
    private AppBarLayout mAppBarLayout;
    private MagicIndicator mIndicator;
    private ViewPager mViewPager;
    private UserBean mUserBean;
    private List<FrameLayout> mViewList;
    private String mToUid;
    private AbsUserHomeViewHolder[] mViewHolders;
    private FrameLayout mUserHead;

    private UserHomeDetailViewHolder mDetailViewHolder;
    private UserHomeAlbumViewHolder mAlumbViewHolder;

    private UserHomeFirstViewHolder homeFirstViewHolder;

    private TextView mTitleView;
    private View mTopTitle;
    private ImageView mBtnFollow;
    private Drawable mUnFollowDrawable;
    private Drawable mFollowDrawable;

    private TextView mName;
    private TextView mID;
    private TextView mVideoPrice;
    private ImageView mOnLine;
    private ImageView mBtnChat;

    private ImageView mSex;
    private TextView mFans;


    public UserHomeViewHolder(Context context, ViewGroup parentView, String toUid, UserBean userBean) {
        super(context, parentView, toUid, userBean);
    }

    @Override
    protected void processArguments(Object... args) {
        super.processArguments(args);
        mToUid = (String) args[0];
        mUserBean = (UserBean) args[1];
    }


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

    @Override
    public void init() {
        setStatusHeight();
        mUnFollowDrawable = ContextCompat.getDrawable(mContext, R.mipmap.o_user_btn_follow_2_0);
        mFollowDrawable = ContextCompat.getDrawable(mContext, R.mipmap.o_user_btn_follow_2_1);
        mBtnFollow = (ImageView) findViewById(R.id.btn_follow);
        mName = (TextView) findViewById(R.id.name);
        mID = (TextView) findViewById(R.id.id_val);
        mFans = (TextView) findViewById(R.id.fans);
        mSex = (ImageView) findViewById(R.id.sex);
        mVideoPrice = (TextView) findViewById(R.id.price_video);
        mOnLine = (ImageView) findViewById(R.id.on_line);
        mBtnChat = (ImageView) findViewById(R.id.btn_chat);
        mAppBarLayout = (AppBarLayout) findViewById(R.id.appBarLayout);
        mAppBarLayout.addOnOffsetChangedListener(this);
        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        mUserHead = (FrameLayout) findViewById(R.id.fl_head);
        mTitleView = (TextView) findViewById(R.id.titleView);
        mTopTitle = findViewById(R.id.fl_top);
        mTopTitle.post(new Runnable() {
            @Override
            public void run() {
                if (mTopTitle != null) {
                    int height = mTopTitle.getHeight();
                    if (height > 0) {
                        View appBarChild = findViewById(R.id.app_bar_child_view);
                        if (appBarChild != null) {
                            appBarChild.setMinimumHeight(height);
                        }
                    }
                }
            }
        });
        if (homeFirstViewHolder == null) {
            homeFirstViewHolder = new UserHomeFirstViewHolder(mContext, mUserHead, mToUid);
            homeFirstViewHolder.addToParent();
            homeFirstViewHolder.subscribeActivityLifeCycle();
            homeFirstViewHolder.loadData();
        }
        if (PAGE_COUNT > 1) {
            mViewPager.setOffscreenPageLimit(PAGE_COUNT - 1);
        }
        mViewHolders = new AbsUserHomeViewHolder[PAGE_COUNT];
        mViewList = new ArrayList<>();
        for (int i = 0; i < PAGE_COUNT; i++) {
            FrameLayout frameLayout = new FrameLayout(mContext);
            frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            mViewList.add(frameLayout);
        }
        mViewPager.setAdapter(new ViewPagerAdapter(mViewList));
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                loadPageData(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mIndicator = (MagicIndicator) findViewById(R.id.indicator);
        final String[] titles = new String[]{
                WordUtil.getString(R.string.user_detail),
                WordUtil.getString(R.string.alumb),
        };
        CommonNavigator commonNavigator = new CommonNavigator(mContext);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {

            @Override
            public int getCount() {
                return titles.length;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorTransitionPagerTitleView(context);
                simplePagerTitleView.setNormalColor(ContextCompat.getColor(mContext, R.color.gray1));
                simplePagerTitleView.setSelectedColor(ContextCompat.getColor(mContext, R.color.textColor));
                simplePagerTitleView.setText(titles[index]);
                simplePagerTitleView.setTextSize(14);
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mViewPager != null) {
                            mViewPager.setCurrentItem(index);
                        }
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                linePagerIndicator.setLineWidth(DpUtil.dp2px(14));
                linePagerIndicator.setLineHeight(DpUtil.dp2px(2));
                linePagerIndicator.setRoundRadius(DpUtil.dp2px(1));
                linePagerIndicator.setColors(ContextCompat.getColor(mContext, R.color.global));
                return linePagerIndicator;
            }
        });
        commonNavigator.setAdjustMode(true);
        mIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mIndicator, mViewPager);
        EventBus.getDefault().register(this);
    }


    private void loadPageData(int position) {
        if (mViewHolders == null) {
            return;
        }
        AbsUserHomeViewHolder vh = mViewHolders[position];
        if (vh == null) {
            if (mViewList != null && position < mViewList.size()) {
                FrameLayout parent = mViewList.get(position);
                if (parent == null) {
                    return;
                }
                if (position == 0) {
                    mDetailViewHolder = new UserHomeDetailViewHolder(mContext, parent, mToUid);
                    vh = mDetailViewHolder;
                } else if (position == 1) {
                    mAlumbViewHolder = new UserHomeAlbumViewHolder(mContext, parent, mToUid);
                    vh = mAlumbViewHolder;
                }
                if (vh == null) {
                    return;
                }
                mViewHolders[position] = vh;
                vh.addToParent();
                vh.subscribeActivityLifeCycle();
            }
        }
        if (vh != null) {
            vh.loadData();
        }
    }

    @Override
    public void loadData() {
        JSONObject obj = ((UserHomeNewActivity) mContext).getUserObj();
        if (obj == null) {
            return;
        }
        if (TextUtils.isEmpty(mToUid)) {
            return;
        }
        if (mViewPager != null) {
            loadPageData(mViewPager.getCurrentItem());
        }
        if (mUserBean != null) {
            if (mName != null) {
                mName.setText(mUserBean.getUserNiceName());
            }
            if (mTitleView != null) {
                mTitleView.setText(mUserBean.getUserNiceName());
            }
            if (mID != null) {
                mID.setText(StringUtil.contact("ID:", mUserBean.getId()));
            }

            if (mFans != null) {
                mFans.setText(String.format(WordUtil.getString(R.string.user_home_fans), mUserBean.getFans()));
            }
            CommonAppConfig appConfig = CommonAppConfig.getInstance();
            String coinName = appConfig.getCoinName();
            boolean openVideo = mUserBean.getIsvideo() == 1;

            if (mVideoPrice != null) {
                if (openVideo) {
                    mVideoPrice.setText(String.format(WordUtil.getString(R.string.user_home_video_price)
                            , StringUtil.contact(mUserBean.getVideoPrice(), coinName)));
                } else {
                    mVideoPrice.setText(R.string.user_home_price_close_video);
                }
            }

            if (mSex != null) {
                mSex.setImageResource(CommonIconUtil.getSexIcon(mUserBean.getSex()));
            }

            if (mOnLine != null) {
                mOnLine.setImageResource(CommonIconUtil.getOnLineIcon2(mUserBean.getOnLineStatus()));
            }

            setFollow(mUserBean.getAttent2() == 1);
        }
    }

    public void setToUid(String toUid) {
        mToUid = toUid;
    }


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

    @Override
    public void release() {
        if (homeFirstViewHolder != null) {
            homeFirstViewHolder.removeFromParent();
        }
        homeFirstViewHolder = null;
    }

    private float mRate;
    private boolean isPlay;
    private boolean isStop;

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        float totalScrollRange = appBarLayout.getTotalScrollRange();
        float rate = -1 * verticalOffset / totalScrollRange * 2;
        if (rate >= 1) {
            rate = 1;
        }
        if (mRate != rate) {
            mRate = rate;
            mTopTitle.setAlpha(rate);
        }

        if (mRate == 1 && !isStop) {
            if (homeFirstViewHolder != null) {
                homeFirstViewHolder.setVideoPause(true);
            }
            isPlay = false;
            isStop = true;
        } else if (mRate == 0 && !isPlay) {
            if (homeFirstViewHolder != null && homeFirstViewHolder.mCurrentPos == 0) {
                homeFirstViewHolder.setVideoPause(false);
            }
            isPlay = true;
            isStop = false;

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFollowEvent(FollowEvent e) {
        setFollow(e.getIsAttention() == 1);
        if (mUserBean != null) {
            mUserBean.setAttent(e.getIsAttention());
        }
    }

    private boolean isShowDialog;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onHomeHeadClickEvent(HomeHeadClickEvent e) {
        if (!isShowDialog) {
            if (homeFirstViewHolder != null) {
                homeFirstViewHolder.setVideoPause(true);
            }
            ShowHomeDialogFragment fragment = new ShowHomeDialogFragment();
            fragment.setOnDialogDismissListener(new ShowHomeDialogFragment.IOnDialogDismissListener() {
                @Override
                public void onDismiss() {
                    if (homeFirstViewHolder != null) {
                        homeFirstViewHolder.setVideoPause(homeFirstViewHolder.mCurrentPos != 0);
                    }
                    isShowDialog = false;
                    if (homeFirstViewHolder != null) {
                        homeFirstViewHolder.setVideoMute(false);
                    }
                }
            });
            Bundle bundle = new Bundle();
            bundle.putString(Constants.TO_UID, mToUid);
            if (homeFirstViewHolder != null) {
                bundle.putInt(Constants.POSITION, homeFirstViewHolder.mCurrentPos);
            }
            fragment.setArguments(bundle);
            fragment.show(((AbsActivity) mContext).getSupportFragmentManager(), "ShowHomeDialogFragment");
            isShowDialog = true;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVoiceEvent(VoiceEvent e) {
        if (e.isPlaying()) {
            if (homeFirstViewHolder != null) {
                homeFirstViewHolder.setVideoMute(true);
            }

        } else {
            if (homeFirstViewHolder != null) {
                homeFirstViewHolder.setVideoMute(false);
            }

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideoEvent(VideoEvent e) {
        if (e.isPlaying()) {
            if (homeFirstViewHolder != null) {
                homeFirstViewHolder.setVideoMute(false);
            }
        }
    }

    public void setFollow(boolean follow) {
        if (mBtnFollow != null) {
            mBtnFollow.setImageDrawable(follow ? mFollowDrawable : mUnFollowDrawable);
        }
    }


}
