package com.cooleshow.student.ui.main;

import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.cooleshow.base.common.WebConstants;
import com.cooleshow.base.constanst.Constants;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.fragment.BaseMVPFragment;
import com.cooleshow.base.utils.SizeUtils;
import com.cooleshow.base.utils.TimeUtils;
import com.cooleshow.base.utils.UiUtils;
import com.cooleshow.base.utils.Utils;
import com.cooleshow.base.utils.helper.WebStartHelper;
import com.cooleshow.base.widgets.CommonItemDecoration;
import com.cooleshow.student.R;
import com.cooleshow.student.adapter.HomeBottomPageAdapter;
import com.cooleshow.student.adapter.HomeHotAlbumAdapter;
import com.cooleshow.student.adapter.HomeHotMusicSheetAdapter;
import com.cooleshow.student.adapter.HomeMenuPagerAdapter;
import com.cooleshow.student.adapter.HomeRecommendTalentAdapter;
import com.cooleshow.student.adapter.HomeTalentStyleAdapter;
import com.cooleshow.student.adapter.HomeVideoCourseAdapter;
import com.cooleshow.student.adapter.NewHomeVideoCourseAdapter;
import com.cooleshow.student.bean.AppHomeBean;
import com.cooleshow.student.bean.CountOfUnreadBean;
import com.cooleshow.student.bean.HelpCenterContentBean;
import com.cooleshow.student.bean.HomeHotMusicSheetBean;
import com.cooleshow.student.bean.HomeHotMusicSheetItemBean;
import com.cooleshow.student.bean.HomeHotNewsBean;
import com.cooleshow.student.bean.HomeLiveAndVideoBean;
import com.cooleshow.student.bean.HomeStyleBean;
import com.cooleshow.student.bean.HotAlbumBean;
import com.cooleshow.student.bean.RecommendTalentListBean;
import com.cooleshow.student.bean.StudentUserInfo;
import com.cooleshow.student.constants.CourseConstants;
import com.cooleshow.student.contract.HomeContract;
import com.cooleshow.student.databinding.FragmentNewHomeLayoutBinding;
import com.cooleshow.student.presenter.main.HomePresenter;
import com.cooleshow.student.widgets.AppBarLayoutStateChangeListener;
import com.cooleshow.student.widgets.HomeHotAlbumDecoration;
import com.cooleshow.student.widgets.HomeHotMusicSheetItemDecoration;
import com.google.android.material.appbar.AppBarLayout;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.config.IndicatorConfig;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.RectangleIndicator;
import com.youth.banner.listener.OnBannerListener;

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

import androidx.annotation.NonNull;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;

import static com.cooleshow.student.constants.CourseConstants.LIVE_COURSE;
import static com.cooleshow.student.constants.CourseConstants.OTHER_COURSE;
import static com.cooleshow.student.constants.CourseConstants.PIANO_ROOM_COURSE;

/**
 * Author by pq, Date on 2022/8/29.
 */
public class NewHomeFragment extends BaseMVPFragment<FragmentNewHomeLayoutBinding, HomePresenter> implements HomeContract.HomeView, View.OnClickListener, TalentStyleFragment.OnEventListener, HotNewsFragment.OnEventListener {
    public static final int MAX_HOT_MUSIC_LIST_PAGE = 3;//热门曲目一页最大条数
    private Banner banner;
    private SmartRefreshLayout refreshLayout;
    private ArrayList<AppHomeBean.ItemBean> itemBeans = new ArrayList<>();
    private BannerImageAdapter mBannerImageAdapter;
    private HomeLiveAndVideoBean.RecentCoursesBean mRecentCourses;
    private List<Fragment> fragments = new ArrayList<>();
    private HomeMenuPagerAdapter mMenuPagerAdapter;
    private String noticeId;
    private HomeHotAlbumAdapter mAlbumAdapter;
    private HomeHotMusicSheetAdapter mHomeHotMusicSheetAdapter;
    private HomeRecommendTalentAdapter mRecommendTalentAdapter;
    private NewHomeVideoCourseAdapter mHomeVideoCourseAdapter;
    private TalentStyleFragment mTalentStyleFragment;
    private HotNewsFragment mHotNewsFragment;
    private ValueAnimator bottomTabValueAnimator;
    private boolean isCollapsed = false;//控制底部tab

    private ViewPager2.OnPageChangeCallback onPageChangeCallback = new ViewPager2.OnPageChangeCallback() {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            switchTabStyle(position);
        }
    };

    @Override
    protected FragmentNewHomeLayoutBinding getLayoutView() {
        return FragmentNewHomeLayoutBinding.inflate(getLayoutInflater());
    }

    @Override
    protected HomePresenter createPresenter() {
        return new HomePresenter();
    }

    @Override
    protected void initView(View rootView) {
        Utils.setHeadView(mViewBinding.viewStatusBar, requireContext(), SizeUtils.dp2px(3.5f));
        banner = mViewBinding.banner;
        refreshLayout = mViewBinding.refreshLayout;
        mViewBinding.bgAnnouncement.setOnClickListener(this);
        mViewBinding.bgAnnouncement2.setOnClickListener(this);
        mViewBinding.ivScan.setOnClickListener(this);
        mViewBinding.imMessage.setOnClickListener(this);
        mViewBinding.flCourseEnter.setOnClickListener(this);
        mViewBinding.tvRecommendTeacherMore.setOnClickListener(this);
        mViewBinding.tvHotAlbumMore.setOnClickListener(this);
        mViewBinding.tvHotTrackMore.setOnClickListener(this);
        mViewBinding.tvVideoCourseMore.setOnClickListener(this);
        mViewBinding.viewTalentStyleClick.setOnClickListener(this);
        mViewBinding.viewHotNewsClick.setOnClickListener(this);
        mViewBinding.viewSearchBg.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        //热门专辑
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mViewBinding.rvHotAlbum.setLayoutManager(manager);
        mAlbumAdapter = new HomeHotAlbumAdapter();
        HomeHotAlbumDecoration hotAlbumItemDecoration = new HomeHotAlbumDecoration(0, 0, 0, SizeUtils.dp2px(14), 0);
        mViewBinding.rvHotAlbum.addItemDecoration(hotAlbumItemDecoration);
        mViewBinding.rvHotAlbum.setAdapter(mAlbumAdapter);

        //热门曲目
        LinearLayoutManager musicSheetManager = new LinearLayoutManager(getContext());
        musicSheetManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mHomeHotMusicSheetAdapter = new HomeHotMusicSheetAdapter();
        HomeHotMusicSheetItemDecoration itemDecoration = new HomeHotMusicSheetItemDecoration(0, 0, 0, SizeUtils.dp2px(12), 0);
        mViewBinding.rvHotTrack.addItemDecoration(itemDecoration);
        mViewBinding.rvHotTrack.setLayoutManager(musicSheetManager);
        mViewBinding.rvHotTrack.setAdapter(mHomeHotMusicSheetAdapter);


        //推荐达人
        mRecommendTalentAdapter = new HomeRecommendTalentAdapter();
        CommonItemDecoration commonItemDecoration = new CommonItemDecoration(0, 0, 0, SizeUtils.dp2px(12), 0);
        LinearLayoutManager recommendTalentManager = new LinearLayoutManager(getContext());
        recommendTalentManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mViewBinding.recyclerviewRecommendTalent.setLayoutManager(recommendTalentManager);
        mViewBinding.recyclerviewRecommendTalent.addItemDecoration(commonItemDecoration);
        mViewBinding.recyclerviewRecommendTalent.setAdapter(mRecommendTalentAdapter);

        LinearLayoutManager videoCourseManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        mViewBinding.rvVideoCourse.setLayoutManager(videoCourseManager);
        mHomeVideoCourseAdapter = new NewHomeVideoCourseAdapter();
        CommonItemDecoration videoListItemDecoration = new CommonItemDecoration(SizeUtils.dp2px(12), 0, 0, SizeUtils.dp2px(10), 0);
        mViewBinding.rvVideoCourse.addItemDecoration(videoListItemDecoration);
        mViewBinding.rvVideoCourse.setAdapter(mHomeVideoCourseAdapter);


        ArrayList<Fragment> bottomFragments = new ArrayList<>();
        mTalentStyleFragment = new TalentStyleFragment();
        mTalentStyleFragment.setOnEventListener(NewHomeFragment.this);
        mHotNewsFragment = new HotNewsFragment();
        mHotNewsFragment.setOnEventListener(NewHomeFragment.this);
        bottomFragments.add(mTalentStyleFragment);
        bottomFragments.add(mHotNewsFragment);
        HomeBottomPageAdapter homeBottomPageAdapter = new HomeBottomPageAdapter(this.getChildFragmentManager(), bottomFragments);
//        getChildFragmentManager().beginTransaction()
//                .add(R.id.fl_talent_style_container, mTalentStyleFragment)
//                .add(R.id.fl_hot_news_container, mHotNewsFragment).commit();
        mViewBinding.viewPagerBottom.setOffscreenPageLimit(bottomFragments.size());
        mViewBinding.viewPagerBottom.setAdapter(homeBottomPageAdapter);

        mMenuPagerAdapter = new HomeMenuPagerAdapter(getChildFragmentManager(), fragments);
        mViewBinding.viewpagerMenu.setAdapter(mMenuPagerAdapter);
        mBannerImageAdapter = new BannerImageAdapter<AppHomeBean.ItemBean>(itemBeans) {
            @Override
            public void onBindView(BannerImageHolder holder, AppHomeBean.ItemBean data, int position, int size) {
                Glide.with(holder.imageView)
                        .load(data.coverImage)
                        .thumbnail(Glide.with(holder.itemView).load(com.cooleshow.base.R.drawable.bg_video_placeholder))//加载成功前显示一个loading的加载
//                        .apply(RequestOptions.bitmapTransform(new RoundedCorners(30)))  //设置图片圆角
                        .into(holder.imageView);

            }
        };
        banner.setAdapter(mBannerImageAdapter, true).addBannerLifecycleObserver(this)//添加生命周期观察者
                .isAutoLoop(true)
                .setIndicatorGravity(IndicatorConfig.Direction.RIGHT)
//                .removeIndicator()
                .setIndicator(new RectangleIndicator(getContext())) //圆形指示器 还支持条形指示器等
                .setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(Object data, int position) {
                        AppHomeBean.ItemBean item = (AppHomeBean.ItemBean) data;
                        if (!TextUtils.isEmpty(item.linkUrl)) {
                            ARouter.getInstance()
                                    .build(RouterPath.WebCenter.ACTIVITY_HTML)
                                    .withString(WebConstants.WEB_URL, item.linkUrl)
                                    .navigation();
                        }
                    }
                });
        initListener();
        //获取热门专辑
        presenter.userAccountPage();
        //获取热门曲目
        presenter.getHotMusicSheetList();
    }

    private void initListener() {
        mRecommendTalentAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (view.getId() == R.id.tv_focus) {
                    //关注
                    if (position < mRecommendTalentAdapter.getData().size()) {
                        RecommendTalentListBean data = mRecommendTalentAdapter.getData().get(position);
                        if (presenter != null) {
                            presenter.followTeacher(data.isFocus ? Constants.STUDENT_FOCUS_TEACHER_STATUS_NORMAL : Constants.STUDENT_FOCUS_TEACHER_STATUS_FOLLOW, String.valueOf(data.userId));
                        }
                    }
                }
            }
        });


        mViewBinding.viewPagerBottom.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

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

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mViewBinding.refreshLayout.setOnRefreshListener(refreshLayout -> {
            refreshLayout.finishRefresh();
            presenter.queryCountOfUnread();
            presenter.queryLiveAndVideo();
            presenter.appHome();
            presenter.userAccountPage();
            presenter.getHotMusicSheetList();
            presenter.getRecommendTalentList();
            refreshBottomData();
        });

        mHomeVideoCourseAdapter.setOnItemClickListener((adapter, view, position) -> {
            HomeLiveAndVideoBean.VideoCourseBean item = (HomeLiveAndVideoBean.VideoCourseBean) adapter.getItem(position);
            ARouter.getInstance()
                    .build(RouterPath.WebCenter.ACTIVITY_HTML)
                    .withString(WebConstants.WEB_URL, WebConstants.TEACHER_VIDEO_DETAIL + "?groupId=" + item.videoGroupId)
                    .navigation();
        });

        mRecommendTalentAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (position < mRecommendTalentAdapter.getData().size()) {
                    //跳转达人风采
                    RecommendTalentListBean item = mRecommendTalentAdapter.getItem(position);
                    ARouter.getInstance()
                            .build(RouterPath.WebCenter.ACTIVITY_HTML)
                            .withString(WebConstants.WEB_URL, WebConstants.STUDENT_TEACHER_HOME + item.userId)
                            .navigation();
                }
            }
        });

        mAlbumAdapter.setOnItemClickListener((adapter, view, position) -> {
            HotAlbumBean.RowsBean item = (HotAlbumBean.RowsBean) adapter.getItem(position);
            ARouter.getInstance()
                    .build(RouterPath.WebCenter.ACTIVITY_HTML)
                    .withString(WebConstants.WEB_URL, WebConstants.STUDENT_MUSIC_ALBUM_DETAIL + item.id)
                    .navigation();
        });


        mViewBinding.viewpagerMenu.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                position = position % fragments.size();// 需要对position的值进行重新赋值，否则会造成数组越界
                // 更新小圆点的显示
//                for (int i = 0; i < fragments.size(); i++) {
//                    ImageView iv = (ImageView) llIndicator.getChildAt(i);
//                    // 当前滑到的是那一页就让第几个小圆点处于选中状态
//                    if (position == i) {
//                        iv.setImageResource(R.drawable.bg_2dc7aa_indicator);
//                    } else {
//                        iv.setImageResource(R.drawable.bg_f2f2f2_indicator);
//                    }
//                }
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        mViewBinding.appBarLayout.addOnOffsetChangedListener(new AppBarLayoutStateChangeListener() {
            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                switch (state) {
                    case EXPANDED:    //展开
                        Log.i("pq", "展开");
                        break;
                    case COLLAPSED:    //折叠
                        Log.i("pq", "折叠");
                        if (!isCollapsed) {
                            isCollapsed = true;
                            mViewBinding.viewDivideLine2.setVisibility(View.VISIBLE);
                            handleTabAnim(1);
                        }
                        break;
                    case INTERMEDIATE: //中间状态
                        Log.i("pq", "中间状态");
                        if (isCollapsed) {
                            handleTabAnim(0);
                            isCollapsed = false;
                            mViewBinding.viewDivideLine2.setVisibility(View.GONE);
                        }
                        break;
                }
            }
        });
    }


    private void resetBannerAuto() {
        boolean localVisibleRect = UiUtils.getLocalVisibleRect(getActivity(), banner, 10);
        //banner可见的时候就自动循环，否则就停止，解决问题：在scrollview到最底部时候，由于banner自动到第一个时候就往上顶一段距离
        if (localVisibleRect) {
            if (null != banner) {
                banner.isAutoLoop(true);
            }
        } else {
            if (null != banner) {
                banner.isAutoLoop(false);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (presenter != null) {
            presenter.appHome();
            //获取课程信息
            presenter.queryLiveAndVideo();
            refreshBottomData();
            //获取推荐达人列表
            presenter.getRecommendTalentList();
        }
    }

    private void refreshBottomData() {
        if (mTalentStyleFragment != null) {
            mTalentStyleFragment.refresh();
        }
        if (mHotNewsFragment != null) {
            mHotNewsFragment.refresh();
        }
    }

    @Override
    public void appHomeSuccess(AppHomeBean appHomeBean) {
        if (isDetached()) {
            return;
        }
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
        }
        //banner
        bindBanner(appHomeBean.banner);
        //后台配置menu
        initMenu(appHomeBean.appMenu);
    }

    /**
     * 处理banner数据
     *
     * @param bannerList
     */
    private void bindBanner(List<AppHomeBean.ItemBean> bannerList) {
        if (mBannerImageAdapter == null) {
            return;
        }
        if (bannerList != null && bannerList.size() > 0) {
            banner.setVisibility(View.VISIBLE);
            itemBeans.clear();
            itemBeans.addAll(bannerList);
            mBannerImageAdapter.notifyDataSetChanged();
        } else {
            itemBeans.clear();
            banner.setVisibility(View.GONE);
        }
    }

    private void initMenu(List<AppHomeBean.ItemBean> menuList) {
        if (mMenuPagerAdapter == null || mViewBinding.viewpagerMenu == null) {
            return;
        }
        fragments.clear();
        int count = menuList.size() / 5;
        if (menuList.size() % 5 > 0) {
            count++;
        }
        for (int i = 0; i < count; i++) {
            List<AppHomeBean.ItemBean> dataList = new ArrayList<>();
            for (int j = i * 5; j < menuList.size() && j < (i + 1) * 5; j++) {
                dataList.add(menuList.get(j));
            }
            fragments.add(HomeMenuFragment.newInstance(dataList));
        }
        if (fragments.size() == 0) {
            mViewBinding.viewpagerMenu.setVisibility(View.GONE);
            return;
        }
        mMenuPagerAdapter.setFragments(fragments);
        mViewBinding.viewpagerMenu.setVisibility(View.VISIBLE);
        mMenuPagerAdapter.notifyDataSetChanged();
    }

    @Override
    public void hotAlbumListSuccess(HotAlbumBean homeHotAlbumListBean) {
        if (isDetached() || homeHotAlbumListBean == null || homeHotAlbumListBean.rows == null) {
            return;
        }
        if (mAlbumAdapter != null) {
            mAlbumAdapter.setNewInstance(homeHotAlbumListBean.rows);
        }
    }

    @Override
    public void queryLiveAndVideoSuccess(HomeLiveAndVideoBean bean) {
        //是否有进入课程
        if (bean == null) {
            return;
        }
        bindVideoCourse(bean.videoList);
        bindRecentCourse(bean.recentCourses);
    }

    private void bindRecentCourse(HomeLiveAndVideoBean.RecentCoursesBean recentCoursesBean) {
        this.mRecentCourses = recentCoursesBean;
        presenter.helpCenterContentList();
        mViewBinding.ivCourseEnterAnim.clearAnimation();
        mViewBinding.flCourseEnter.setVisibility(mRecentCourses != null ? View.VISIBLE : View.GONE);
        handleEnterAnim();
        if (mRecentCourses != null) {
            String currentTime = TimeUtils.date2String(new Date(System.currentTimeMillis()), "yyyy-MM-dd");
            String startTime = TimeUtils.date2String(
                    TimeUtils.getDate(mRecentCourses.courseStartTime),
                    "yyyy-MM-dd"
            );
            if (TextUtils.equals(currentTime, startTime)) {
                String timeText =
                        TimeUtils.date2String(TimeUtils.getDate(mRecentCourses.courseStartTime), "HH:mm");
                mViewBinding.tvLiveTime.setText(String.format("今日 %s", timeText));
            } else {
                mViewBinding.tvLiveTime.setText(TimeUtils.date2String(
                        TimeUtils.getDate(mRecentCourses.courseStartTime),
                        "yyyy-MM-dd HH:mm"
                ));
            }
        }
    }

    private void bindVideoCourse(List<HomeLiveAndVideoBean.VideoCourseBean> videoList) {
        if (null == videoList || videoList.size() == 0) {
            mViewBinding.clVideoCourse.setVisibility(View.GONE);
            return;
        }
        mViewBinding.clVideoCourse.setVisibility(View.VISIBLE);
        if (mHomeVideoCourseAdapter != null) {
            mHomeVideoCourseAdapter.setNewInstance(videoList);
        }
    }

    private void handleEnterAnim() {
        if (mRecentCourses == null) {
            mViewBinding.ivCourseEnterAnim.setVisibility(View.GONE);
            return;
        }
        mViewBinding.ivCourseEnterAnim.setVisibility(View.VISIBLE);
        String assetFolder = "lottie/home/sparring_course/images/";
        int rawRes = R.raw.home_sparring_course_enter;
        if (TextUtils.equals(mRecentCourses.courseType, CourseConstants.LIVE_COURSE)) {
            assetFolder = "lottie/home/live_course/images/";
            rawRes = R.raw.home_live_course_enter;
        }
        if (TextUtils.equals(mRecentCourses.courseType, CourseConstants.OTHER_COURSE)) {
            //陪练课
            assetFolder = "lottie/home/sparring_course/images/";
            rawRes = R.raw.home_sparring_course_enter;
        }
        if (TextUtils.equals(mRecentCourses.courseType, CourseConstants.PIANO_ROOM_COURSE)) {
            //琴房课
            assetFolder = "lottie/home/piano_course/images/";
            rawRes = R.raw.home_piano_course_enter;
        }
        mViewBinding.ivCourseEnterAnim.setImageAssetsFolder(assetFolder);
        mViewBinding.ivCourseEnterAnim.setAnimation(rawRes);
        mViewBinding.ivCourseEnterAnim.playAnimation();

    }

    @Override
    public void getStylePageSuccess(int page, HomeStyleBean data) {
        if (mTalentStyleFragment != null) {
            mTalentStyleFragment.setData(page, data);
        }
    }

    @Override
    public void queryUserInfoSuccess(StudentUserInfo data) {

    }

    @Override
    public void helpCenterContentListSuccess(HelpCenterContentBean data) {
        if (data != null && data.rows != null && data.rows.size() > 0) {
            mViewBinding.tvNoticeContent.setText(data.rows.get(0).title);
            mViewBinding.tvNoticeContent2.setText(data.rows.get(0).title);
            noticeId = data.rows.get(0).id;
            if (mRecentCourses != null) {
                //有进入课程提示
                mViewBinding.bgAnnouncement.setVisibility(View.VISIBLE);
                mViewBinding.bgAnnouncement2.setVisibility(View.GONE);
            } else {
                mViewBinding.bgAnnouncement2.setVisibility(View.VISIBLE);
                mViewBinding.bgAnnouncement.setVisibility(View.GONE);
            }
        } else {
            mViewBinding.bgAnnouncement.setVisibility(View.GONE);
            mViewBinding.bgAnnouncement2.setVisibility(View.GONE);
        }
    }

    @Override
    public void queryCountOfUnreadSuccess(List<CountOfUnreadBean> data) {
        if (isDetached()) {
            return;
        }
        if (null == data || data.size() == 0) {
            mViewBinding.viewUnreadMessage.setVisibility(View.GONE);
            return;
        }
        int totalCount = 0;
        for (CountOfUnreadBean datum : data) {
            totalCount += datum.value;
        }
        if (totalCount > 0) {
            mViewBinding.viewUnreadMessage.setVisibility(View.VISIBLE);
        } else {
            mViewBinding.viewUnreadMessage.setVisibility(View.GONE);
        }
    }

    @Override
    public void getHotMusicSheetListSuccess(HomeHotMusicSheetBean homeHotMusicSheetBean) {
        if (isDetached() || homeHotMusicSheetBean == null || homeHotMusicSheetBean.rows == null) {
            return;
        }
        ArrayList<HomeHotMusicSheetItemBean> itemBeans = new ArrayList<>();
        List<HomeHotMusicSheetBean.RowsBean> rows = homeHotMusicSheetBean.rows;
        if (rows != null && rows.size() > 0) {
            int pageCount = 0;
            int pageResult = rows.size() % MAX_HOT_MUSIC_LIST_PAGE;
            if (pageResult == 0) {
                pageCount = rows.size() / MAX_HOT_MUSIC_LIST_PAGE;
            } else {
                pageCount = (rows.size() / MAX_HOT_MUSIC_LIST_PAGE) + 1;
            }
            for (int i = 0; i < pageCount; i++) {
                HomeHotMusicSheetItemBean hotMusicSheetItemBean = new HomeHotMusicSheetItemBean();
                for (int k = i * MAX_HOT_MUSIC_LIST_PAGE; k < rows.size() && k < (i + 1) * MAX_HOT_MUSIC_LIST_PAGE; k++) {
                    hotMusicSheetItemBean.sheetBeans.add(rows.get(k));
                }
                itemBeans.add(hotMusicSheetItemBean);
            }
            if (mHomeHotMusicSheetAdapter != null) {
                mHomeHotMusicSheetAdapter.setNewInstance(itemBeans);
            }
        }
    }

    @Override
    public void getRecommendTalentSuccess(ArrayList<RecommendTalentListBean> talentListBeans) {
        if (isDetached()) {
            return;
        }
        if (talentListBeans != null && talentListBeans.size() > 0) {
            mViewBinding.csRecommendTalent.setVisibility(View.VISIBLE);
            if (mRecommendTalentAdapter != null) {
                mRecommendTalentAdapter.setNewInstance(talentListBeans);
            }
        } else {
            mViewBinding.csRecommendTalent.setVisibility(View.GONE);
        }
    }

    @Override
    public void getHotNewsSuccess(int page, HomeHotNewsBean homeHotNewsBean) {
        //获取热门资讯Success
        bindHotNews(page, homeHotNewsBean);
    }

    private void bindHotNews(int page, HomeHotNewsBean information) {
        if (mHotNewsFragment != null) {
            mHotNewsFragment.setData(page, information);
        }
    }

    @Override
    public void getHotNewsError(int page) {
        //获取热门资讯Error
        if (mHotNewsFragment != null) {
            mHotNewsFragment.getHotNewsError(page);
        }
    }

    @Override
    public void followTeacherSuccess() {
        //关注老师成功
        if (isDetached()) {
            return;
        }
        //获取推荐达人列表
        if (presenter != null) {
            presenter.getRecommendTalentList();
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.view_search_bg) {
            //搜索
            WebStartHelper.startSearch();
            return;
        }
        if (id == R.id.iv_scan) {
            if (UiUtils.isFastClick()) {
                return;
            }
            //二维码扫描
            ARouter.getInstance()
                    .build(RouterPath.BaseCenter.SCAN_QR_CODE)
                    .navigation();
            return;
        }
        if (id == R.id.im_message) {
            //消息列表页面
            if (UiUtils.isFastClick()) {
                return;
            }
            ARouter.getInstance().build(RouterPath.MessageCenter.TEACHER_MESSAGE_MESSAGEBOX)
                    .navigation();
            return;
        }
        if (id == R.id.fl_course_enter) {
            //进入教室
            if (UiUtils.isFastClick()) {
                return;
            }
            if (mRecentCourses != null) {
                gotoCourseDetail(mRecentCourses);
            }
            return;
        }
        if (id == R.id.bg_announcement || id == R.id.bg_announcement2) {
            if (UiUtils.isFastClick()) {
                return;
            }
            if (TextUtils.isEmpty(noticeId)) {
                return;
            }
            //点击单条公告
            ARouter.getInstance()
                    .build(RouterPath.WebCenter.ACTIVITY_HTML)
                    .withString(WebConstants.WEB_URL, WebConstants.HELP_CENTER_DETAIL + noticeId)
                    .navigation();
            return;
        }

        if (id == R.id.tv_recommend_teacher_more) {
            if (UiUtils.isFastClick()) {
                return;
            }
            //老师风采
            ARouter.getInstance()
                    .build(RouterPath.WebCenter.ACTIVITY_HTML)
                    .withString(WebConstants.WEB_URL, WebConstants.STUDENT_TEACHER_ELEGANT)
                    .navigation();
            return;
        }
        if (id == R.id.tv_hot_album_more) {
            if (UiUtils.isFastClick()) {
                return;
            }
            //热门专辑
            ARouter.getInstance()
                    .build(RouterPath.WebCenter.ACTIVITY_HTML)
                    .withString(WebConstants.WEB_URL, WebConstants.STUDENT_MUSIC_ALBUM)
                    .navigation();
            return;
        }
        if (id == R.id.tv_hot_track_more) {
            if (UiUtils.isFastClick()) {
                return;
            }
            //热门曲目更多
            WebStartHelper.startHotMusicSheetList();
            return;
        }

        if (id == R.id.tv_video_course_more) {
            if (UiUtils.isFastClick()) {
                return;
            }
            //视频课更多
            ARouter.getInstance()
                    .build(RouterPath.WebCenter.ACTIVITY_HTML)
                    .withString(WebConstants.WEB_URL, WebConstants.STUDENT_VIDEO_CLASS)
                    .navigation();
            return;
        }
        if (id == R.id.view_talent_style_click) {
            //达人风采tab点击
            mViewBinding.viewPagerBottom.setCurrentItem(0);
            return;
        }

        if (id == R.id.view_hot_news_click) {
            //热门资讯tab点击
            mViewBinding.viewPagerBottom.setCurrentItem(1);
            return;
        }
    }

    /**
     * 切换tab样式
     *
     * @param position
     */
    private void switchTabStyle(int position) {
        //view_talent_style_news
        boolean isSelectFirst = position == 0;
        mViewBinding.viewTalentStyleNews.setVisibility(isSelectFirst ? View.VISIBLE : View.GONE);
        mViewBinding.tvTalentStyleTitle.setTextColor(getResources().getColor(isSelectFirst ? com.cooleshow.base.R.color.color_333333 : com.cooleshow.base.R.color.color_999999));
        mViewBinding.viewTabHotNews.setVisibility(isSelectFirst ? View.GONE : View.VISIBLE);
        mViewBinding.tvHotNewsTitle.setTextColor(getResources().getColor(isSelectFirst ? com.cooleshow.base.R.color.color_999999 : com.cooleshow.base.R.color.color_333333));
    }


    private void handleTabAnim(int animationMode) {
        int colorFrom = getResources().getColor(animationMode == 0 ? com.cooleshow.base.R.color.white : com.cooleshow.base.R.color.color_f6f8f9);
        int colorTo = getResources().getColor(animationMode == 0 ? com.cooleshow.base.R.color.color_f6f8f9 : com.cooleshow.base.R.color.white);
        if (bottomTabValueAnimator == null) {
            bottomTabValueAnimator = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
            bottomTabValueAnimator.setDuration(150);
            bottomTabValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    if (mViewBinding != null) {
                        int colorValue = (int) animation.getAnimatedValue();
                        mViewBinding.csBottomTab.setBackgroundColor(colorValue);
                    }
                }
            });
        }
        if (bottomTabValueAnimator.isRunning()) {
            bottomTabValueAnimator.cancel();
        }
        bottomTabValueAnimator.setObjectValues(colorFrom, colorTo);
        bottomTabValueAnimator.start();
    }

    /**
     * 跳转直播课详情页面
     *
     * @param bean
     */
    private void gotoCourseDetail(HomeLiveAndVideoBean.RecentCoursesBean bean) {
        switch (bean.courseType) {
            case LIVE_COURSE:
                ARouter.getInstance()
                        .build(RouterPath.WebCenter.ACTIVITY_HTML)
                        .withString(WebConstants.WEB_URL, String.format(WebConstants.TEACHER_LIVE_DETAIL_NORMAL_COURSE, bean.courseGroupId, bean.courseId))
                        .navigation();
                break;
            case OTHER_COURSE:
                //陪练课
                ARouter.getInstance().build(RouterPath.CourseCenter.SPARRING_COURSE_DETAIL)
                        .withString(CourseConstants.COURSE_ID, String.valueOf(bean.courseId))
                        .withString(CourseConstants.COURSE_GROUP_ID, String.valueOf(bean.courseGroupId))
                        .navigation();
                break;
            case PIANO_ROOM_COURSE:
                //琴房课 跳转详情页
                ARouter.getInstance().build(RouterPath.CourseCenter.PIANO_ROOM_COURSE_DETAIL)
                        .withString(CourseConstants.COURSE_ID, String.valueOf(bean.courseId))
                        .navigation();
                break;
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (bottomTabValueAnimator != null) {
            bottomTabValueAnimator.cancel();
            bottomTabValueAnimator = null;
        }
    }

    //获取达人风采列表
    @Override
    public void getStyleData(int page) {
        if (presenter != null) {
            presenter.getTalentStyle(page);
        }
    }

    @Override
    public void getNewsData(int page) {
        if (presenter != null) {
            presenter.getHotNewsPage(page);
        }
    }
}
