package com.cooleshow.teacher.ui.homepage;

import android.graphics.Color;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.GlideUtils;
import com.cooleshow.base.utils.SizeUtils;
import com.cooleshow.base.utils.UiUtils;
import com.cooleshow.base.utils.Utils;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.HomePagerAdapter;
import com.cooleshow.teacher.bean.TeacherUserInfo;
import com.cooleshow.teacher.constants.TeacherInfoConstants;
import com.cooleshow.teacher.contract.HomePageContract;
import com.cooleshow.teacher.databinding.ActivityHomePageLayoutBinding;
import com.cooleshow.teacher.presenter.homePage.HomePagePresenter;
import com.cooleshow.teacher.widgets.AppBarLayoutStateChangeListener;
import com.cooleshow.teacher.widgets.dialog.BadgeDesDialog;
import com.cooleshow.usercenter.helper.UserHelper;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

/**
 * Author by pq, Date on 2022/5/9.
 * 个人主页
 */
@Route(path = RouterPath.MineCenter.HOME_PAGE)
public class HomePageActivity extends BaseMVPActivity<ActivityHomePageLayoutBinding, HomePagePresenter> implements HomePageContract.HomePageView, View.OnClickListener {
    public static final String[] titles = new String[]{"个人风采", "陪练课", "直播课", "视频课", "乐谱"};
    public static final int EXPAND_MODE = 1;
    public static final int COLLAP_MODE = 2;

    private ArrayList<Fragment> fragments = new ArrayList<>();
    private SheetMusicPageFragment mMusicPageFragment;
    private int titleStyleMode = 1;//根据折叠展开状态控制title样式

    @Override
    protected void initView() {
//        Utils.setHeadView(viewBinding.viewStatusBar, this, 0);
        viewBinding.toolbar.setNavigationIcon(com.cooleshow.base.R.drawable.icon_back_arrow_white);
        viewBinding.ivBack.setOnClickListener(this);
        viewBinding.llBadge.setOnClickListener(this);
        viewBinding.tvEdit.setOnClickListener(this);
        viewBinding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        viewBinding.appBarLayout.addOnOffsetChangedListener(new AppBarLayoutStateChangeListener() {

            @Override
            public void onStateChanged(AppBarLayout appBarLayout, State state) {
                switch (state) {
                    case EXPANDED:    //展开
                        break;
                    case COLLAPSED:    //折叠
                        switchTitleStyle(COLLAP_MODE);
                        break;
                    case INTERMEDIATE: //中间状态
                        switchTitleStyle(EXPAND_MODE);
                        break;

                }
            }
        });
    }

    private void switchTitleStyle(int mode) {
        if (titleStyleMode == mode) {
            return;
        }
        titleStyleMode = mode;
        if (mode == 1) {
            viewBinding.toolbar.setNavigationIcon(com.cooleshow.base.R.drawable.icon_back_arrow_white);
            viewBinding.tvTitle.setTextColor(getResources().getColor(R.color.white));
            QMUIStatusBarHelper.setStatusBarDarkMode(HomePageActivity.this);
        } else {
            QMUIStatusBarHelper.setStatusBarLightMode(HomePageActivity.this);
            viewBinding.toolbar.setNavigationIcon(com.cooleshow.base.R.drawable.icon_back_black);
            viewBinding.tvTitle.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_333333));
        }
    }

    @Override
    public void initData() {
        super.initData();
        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(viewBinding.tabLayout, viewBinding.viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                createTab(tab, titles[position]);
            }
        });
        viewBinding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab != null && tab.getCustomView() != null) {
                    View customView = tab.getCustomView();
                    TextView tv_text = customView.findViewById(R.id.tv_text);
                    tv_text.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_333333));
                    tv_text.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    tv_text.setTextSize(17);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab != null && tab.getCustomView() != null) {
                    View customView = tab.getCustomView();
                    TextView tv_text = customView.findViewById(R.id.tv_text);
                    tv_text.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_666666));
                    tv_text.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    tv_text.setTextSize(15);
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        MineStyleFragment mineStyleFragment = new MineStyleFragment();
        SparringCoursePageFragment sparringCoursePageFragment = new SparringCoursePageFragment();
        LiveCoursePageFragment liveCoursePageFragment = new LiveCoursePageFragment();
        VideoCoursePageFragment videoCoursePageFragment = new VideoCoursePageFragment();
        mMusicPageFragment = new SheetMusicPageFragment();
        fragments.add(mineStyleFragment);
        fragments.add(sparringCoursePageFragment);
        fragments.add(liveCoursePageFragment);
        fragments.add(videoCoursePageFragment);
        fragments.add(mMusicPageFragment);
        HomePagerAdapter homePagerAdapter = new HomePagerAdapter(this);
        homePagerAdapter.setData(fragments);
        viewBinding.viewPager.setOffscreenPageLimit(fragments.size());
        viewBinding.viewPager.setAdapter(homePagerAdapter);
        tabLayoutMediator.attach();
    }

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

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

    @Override
    protected void onResume() {
        super.onResume();
        presenter.getTeacherUserInfo();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
            return;
        }
        if (id == R.id.ll_badge) {
            //显示徽章说明
            showBadgeDialog();
            return;
        }
        if (id == R.id.tv_edit) {
            //跳转个人风采
            ARouter.getInstance().build(RouterPath.MineCenter.MINE_STYLE_PAGE)
                    .navigation();
        }
    }

    private void showBadgeDialog() {
        BadgeDesDialog badgeDesDialog = new BadgeDesDialog(this);
        badgeDesDialog.show();
    }

    private TabLayout.Tab createTab(TabLayout.Tab tab, String text) {
        tab.setCustomView(R.layout.view_homepage_tab_layout);
        View customView = tab.getCustomView();
        if (customView != null) {
            TextView tv_text = customView.findViewById(R.id.tv_text);
            tv_text.setText(text);
        }
        return tab;
    }

    /**
     * 获取老师信息成功
     *
     * @param info
     */
    @Override
    public void getTeacherInfoSuccess(TeacherUserInfo info) {
        if (isFinishing() || isDestroyed()) {
            return;
        }
        //save达人认证状态和开通直播状态
        UserHelper.saveTeacherCertificationStatus(info.entryStatus);
        UserHelper.saveTeacherOpenLiveFlag(info.liveFlag);
        if (mMusicPageFragment != null) {
            mMusicPageFragment.setMusicPersonCertStatus(info.entryStatus);
        }
        viewBinding.tvTitle.setText(String.format("%s的主页", info.username));
        //星级
        if (info.starGrade > 0) {
            viewBinding.ratingBar.setVisibility(View.VISIBLE);
            viewBinding.ratingBar.setRating(info.starGrade);
            viewBinding.tvNoScore.setVisibility(View.GONE);
        } else {
            viewBinding.ratingBar.setVisibility(View.VISIBLE);
            viewBinding.tvNoScore.setVisibility(View.GONE);
        }
        //徽章信息
        viewBinding.llBadge.setVipIcon(info.isVip == 1);
        viewBinding.llBadge.setData(info.tag);
        //粉丝数
        viewBinding.tvFansNum.setText(info.fansNum);
        //已上课时数
        viewBinding.tvCourseNumCompleted.setText(info.expTime);
        //未上课时数
        viewBinding.tvCourseNumNotStart.setText(info.unExpTime);
        //vip
        viewBinding.ivVip.setImageResource(info.isVip == 1 ? R.drawable.icon_vip_able_big : R.drawable.icon_vip_enable_big);
        //头像
        viewBinding.ivAvatar.setBorderColor(info.isVip == 1 ? getResources().getColor(com.cooleshow.base.R.color.color_fce2b7) : getResources().getColor(com.cooleshow.base.R.color.white));
        GlideUtils.INSTANCE.loadImage(this, info.heardUrl, viewBinding.ivAvatar, R.drawable.icon_teacher_default_head);
        GlideUtils.INSTANCE.loadImageWhitVague(this, info.heardUrl, viewBinding.ivHeaderBg, R.drawable.bg_home_page_header);
        //学历认证 教资认证标签
        updateCertStatusUI(info.degreeFlag, info.teacherFlag);
        //昵称
        viewBinding.tvNickname.setText(info.username);
        //subjectName
        try {
            viewBinding.llSubjectContainer.removeAllViews();
            viewBinding.llSubjectContainer2.removeAllViews();
            String[] subjectNames = UiUtils.splitSubjectName(info.subjectName);
            if (subjectNames != null && subjectNames.length > 0) {
                for (int i = 0; i < subjectNames.length; i++) {
                    createSubjectView(subjectNames[i]);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateCertStatusUI(int degreeFlag, int teacherFlag) {
        //学历认证
        if (degreeFlag == 1) {
            viewBinding.ivEduCert.setVisibility(View.VISIBLE);
        } else {
            viewBinding.ivEduCert.setVisibility(View.GONE);
        }

        //教资认证
        if (teacherFlag == 1) {
            viewBinding.ivTeacherCert.setVisibility(View.VISIBLE);
        } else {
            viewBinding.ivTeacherCert.setVisibility(View.GONE);
        }
    }

    private void createSubjectView(String text) {
        TextView textView = (TextView) LayoutInflater.from(this).inflate(com.cooleshow.base.R.layout.view_subject_item_layout, viewBinding.llSubjectContainer, false);
        textView.setText(text);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        if (viewBinding.llSubjectContainer.getChildCount() < 4) {
            if (viewBinding.llSubjectContainer.getChildCount() >= 1) {
                params.setMargins(SizeUtils.dp2px(4), 0, 0, 0);
            }
            viewBinding.llSubjectContainer.addView(textView, params);
        } else {
            viewBinding.llSubjectContainer2.addView(textView, params);
            viewBinding.llSubjectContainer2.setVisibility(View.VISIBLE);
        }
    }
}
