package com.cooleshow.teacher.ui.main

import android.text.SpannableString
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.launcher.ARouter
import com.cooleshow.base.common.WebConstants
import com.cooleshow.base.ext.setVisible
import com.cooleshow.base.router.RouterPath
import com.cooleshow.base.ui.fragment.BaseMVPFragment
import com.cooleshow.base.utils.GlideUtils.loadImage
import com.cooleshow.base.utils.TimeUtils
import com.cooleshow.base.utils.UiUtils
import com.cooleshow.base.utils.Utils
import com.cooleshow.teacher.R
import com.cooleshow.teacher.adapter.HomeMenuPageAdapter
import com.cooleshow.teacher.bean.*
import com.cooleshow.teacher.constants.CourseConstants
import com.cooleshow.teacher.constants.TeacherInfoConstants
import com.cooleshow.teacher.contract.HomeContract
import com.cooleshow.teacher.databinding.FragmentHomeLayoutBinding
import com.cooleshow.teacher.presenter.main.HomePresenter
import com.cooleshow.usercenter.helper.UserHelper
import java.util.*


/**
 * Author by pq, Date on 2022/4/20.
 */
class HomeFragment : BaseMVPFragment<FragmentHomeLayoutBinding, HomePresenter>(),
    HomeContract.HomeView, View.OnClickListener {

    private var noticeId: Long = 0
    private val fragments: ArrayList<Fragment> = ArrayList()
    private lateinit var menuAdapter: HomeMenuPageAdapter;


    override fun getLayoutView(): FragmentHomeLayoutBinding {
        return FragmentHomeLayoutBinding.inflate(layoutInflater)
    }

    override fun initView(rootView: View?) {
        Utils.setHeadView(mViewBinding.viewStatusBar, requireContext(), 0)
    }

    override fun initData() {
        mViewBinding.cardMineCourse.setOnClickListener(this)
        mViewBinding.ivUnCertificationTip.setOnClickListener(this)
        mViewBinding.cardMineAssess.setOnClickListener(this)
        mViewBinding.cardAfterClassAssess.setOnClickListener(this)
        mViewBinding.ivCertificationStatus.setOnClickListener(this)
        mViewBinding.cardMineMusicSheet.setOnClickListener(this)
        mViewBinding.cardAfterClassHomework.setOnClickListener(this)
        mViewBinding.cardMineIncome.setOnClickListener(this)
        mViewBinding.ivChat.setOnClickListener(this)
        mViewBinding.bgAnnouncement.setOnClickListener(this)
        mViewBinding.cardKotofusa.setOnClickListener(this)
        mViewBinding.ivScan.setOnClickListener(this)
        initMenu();
    }

    private fun initMenu() {
        if (!this::menuAdapter.isInitialized) {
            menuAdapter = HomeMenuPageAdapter(childFragmentManager);
            menuAdapter.setFragments(fragments)
        }
        mViewBinding.viewpagerMenu.adapter = menuAdapter;
    }

    override fun createPresenter(): HomePresenter {
        return HomePresenter()
    }


    fun getTeacherInfoSuccess(teacherUserInfo: TeacherUserInfo) {
        if (isDetached) {
            return;
        }
        if (context == null || teacherUserInfo == null) {
            return
        }
        //头像
        loadImage(
            requireContext(),
            teacherUserInfo.heardUrl,
            mViewBinding.ivAvatar,
            R.drawable.icon_teacher_default_head
        )
        //昵称
        mViewBinding.tvNickname.text =
            UserHelper.getTeacherName(teacherUserInfo.username, teacherUserInfo.userId);
        //星级
        if (teacherUserInfo.starGrade.toFloat() > 0) {
            mViewBinding.ratingBar.visibility = View.VISIBLE
            mViewBinding.tvNoScore.visibility = View.GONE
            mViewBinding.ratingBar.rating = teacherUserInfo.starGrade.toFloat()
        } else {
            mViewBinding.ratingBar.visibility = View.GONE
            mViewBinding.tvNoScore.visibility = View.VISIBLE
        }
        if (!TextUtils.isEmpty(teacherUserInfo.tag)) {
            mViewBinding.llBadge.setVisible(true)
            mViewBinding.llBadge.setVipIcon(teacherUserInfo.isVip == 1)
            mViewBinding.llBadge.setData(teacherUserInfo.tag)
        } else {
            if (teacherUserInfo.isVip == 1) {
                mViewBinding.llBadge.setVipIcon(true)
                mViewBinding.llBadge.setVisible(true)
            } else {
                mViewBinding.llBadge.setVisible(false)
            }
        }

        //粉丝数
        mViewBinding.tvFansNum.text = teacherUserInfo.fansNum;
        //已上课时数
        mViewBinding.tvCourseNumCompleted.text = teacherUserInfo.expTime
        //未上课时数
        mViewBinding.tvCourseNumNotStart.text = teacherUserInfo.unExpTime
        //入驻状态
        when (teacherUserInfo.entryStatus) {
            TeacherInfoConstants.ENTRY_STATUS_DOING -> {
                //入驻审核中
                mViewBinding.ivCertificationStatus.setImageResource(R.drawable.icon_home_entry_doing)
                mViewBinding.ivCertificationStatus.visibility = View.VISIBLE
                mViewBinding.ivUnCertificationTip.visibility = View.GONE
                mViewBinding.groupTeacherExtra.visibility = View.INVISIBLE
            }
            TeacherInfoConstants.ENTRY_STATUS_PASS -> {
                //入驻审核通过
                mViewBinding.ivCertificationStatus.visibility = View.GONE
                mViewBinding.ivUnCertificationTip.visibility = View.GONE
                mViewBinding.groupTeacherExtra.visibility = View.VISIBLE
                mViewBinding.llBadge.setStyleIcon(true)
            }
            else -> {
                //未通过或者未申请
                mViewBinding.ivCertificationStatus.setImageResource(R.drawable.icon_home_un_certification)
                mViewBinding.ivCertificationStatus.visibility = View.VISIBLE
                mViewBinding.ivUnCertificationTip.visibility = View.GONE
                mViewBinding.groupTeacherExtra.visibility = View.INVISIBLE
            }
        }
        musicianAuthStatus = teacherUserInfo.musicianAuthStatus
        when (teacherUserInfo.musicianAuthStatus) {
            TeacherInfoConstants.MUSICIAN_STATUS_PASS -> {
            }
            else -> {
            }
        }
    }

    private var musicianAuthStatus: String? = null

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_un_certification_tip -> {
                //关闭认证提示
                mViewBinding.ivUnCertificationTip.setVisible(false);
            }
            R.id.card_mine_course -> {
                //我的课程
                if (UiUtils.isFastClick()) {
                    return;
                }
                ARouter.getInstance().build(RouterPath.CourseCenter.TEACHER_MINE_COURSE)
                    .navigation()
            }

            R.id.card_mine_assess -> {
                if (UiUtils.isFastClick()) {
                    return;
                }
                ARouter.getInstance().build(RouterPath.CommentCenter.TEACHER_RECEIVED_COMMENT)
                    .navigation()
            }
            R.id.card_after_class_assess -> {
                ARouter.getInstance().build(RouterPath.CommentCenter.TEACHER_COURSE_COMMENT)
                    .navigation()
            }
            R.id.iv_certification_status -> {
                //达人认证
                ARouter.getInstance().build(RouterPath.WebCenter.ACTIVITY_HTML)
                    .withString(WebConstants.WEB_URL, WebConstants.TEACHER_CERT)
                    .navigation()
            }
            R.id.card_mine_music_sheet -> {
                if (UiUtils.isFastClick()) {
                    return;
                }
                ARouter.getInstance().build(RouterPath.ScoreCenter.TEACHER_MINE_SCORE)
                    .navigation()
            }
            R.id.card_after_class_homework -> {
                if (UiUtils.isFastClick()) {
                    return;
                }
                ARouter.getInstance().build(RouterPath.WorkCenter.TEACHER_WORK_HOMEWORK)
                    .navigation()
            }
            R.id.card_mine_income -> {
                if (UiUtils.isFastClick()) {
                    return;
                }
//                ARouter.getInstance().build(RouterPath.WebCenter.ACTIVITY_HTML)
//                    .withString(WebConstants.WEB_URL, WebConstants.TEACHER_INCOME)
//                    .navigation()
                ARouter.getInstance().build(RouterPath.IncomeCenter.TEACHER_MINE_INCOME)
                    .navigation()
            }
            R.id.iv_chat -> {
                if (UiUtils.isFastClick()) {
                    return;
                }
                ARouter.getInstance().build(RouterPath.MessageCenter.TEACHER_MESSAGE_MESSAGEBOX)
                    .navigation()
            }
            R.id.bg_announcement -> {
                //点击单条公告
                ARouter.getInstance()
                    .build(RouterPath.WebCenter.ACTIVITY_HTML)
                    .withString(WebConstants.WEB_URL, WebConstants.HELP_CENTER_DETAIL + noticeId)
                    .navigation()
            }
//            R.id.im_notice_list -> {
//                //公告列表
//                ARouter.getInstance()
//                    .build(RouterPath.WebCenter.ACTIVITY_HTML)
//                    .withString(WebConstants.WEB_URL, WebConstants.HELP_CENTER_CATALOGTYPE_2)
//                    .navigation()
//            }
            R.id.card_Kotofusa -> {
                if (UiUtils.isFastClick()) {
                    return;
                }
                //云库琴房
                ARouter.getInstance()
                    .build(RouterPath.WebCenter.ACTIVITY_HTML)
                    .withString(WebConstants.WEB_URL, WebConstants.PIANO_ROOM)
                    .navigation()
            }
            R.id.iv_scan -> {
                if (UiUtils.isFastClick()) {
                    return;
                }
                //二维码扫描
                ARouter.getInstance()
                    .build(RouterPath.BaseCenter.SCAN_QR_CODE)
                    .navigation()
            }
        }

    }

    override fun onResume() {
        super.onResume()
        presenter.getHomeCount();
        presenter.queryCountOfUnread()
        presenter.helpCenterContentList()
        presenter.queryLiveAndVideo()
        presenter.appHome()
    }

    override fun getHomeCountSuccess(data: HomeCountBean?) {
        if (data != null) {
            if (data.courseSchedule == 0) {
                mViewBinding.tvMineCourseCount.text = "本周剩余\n0 课时"
            } else {
                mViewBinding.tvMineCourseCount.text =
                    getRoomAuthorTextStyleSpan(
                        "本周剩余\n",
                        data.courseSchedule.toString() + " ",
                        "课时"
                    )
            }
            if (data.courseHomework == 0) {
                mViewBinding.tvAfterClassHomeworkCount.text = "本周共 0 节课\n未布置作业"
            } else {
                mViewBinding.tvAfterClassHomeworkCount.text =
                    getRoomAuthorTextStyleSpan(
                        "本周共",
                        " " + data.courseHomework + " ",
                        "节课\n未布置作业"
                    )
            }
            if (data.courseScheduleReplied == 0) {
                mViewBinding.tvAfterClassAssessCount.text = "剩余 0 节\n尚未评价"
            } else {
                mViewBinding.tvAfterClassAssessCount.text =
                    getRoomAuthorTextStyleSpan(
                        "剩余",
                        " " + data.courseScheduleReplied + " ",
                        "节\n尚未评价"
                    )
            }
            if (data.musicSheet == 0) {
                mViewBinding.tvMineMusicSheetCount.text = "共 0 支\n乐谱"
            } else {
                mViewBinding.tvMineMusicSheetCount.text =
                    getRoomAuthorTextStyleSpan(
                        "共",
                        " " + data.musicSheet + " ",
                        "支\n乐谱"
                    )
            }
            if (data.studentReplied == 0) {
                mViewBinding.tvMineAssessCount.text = "本周收到\n0 个评价"
            } else {
                mViewBinding.tvMineAssessCount.text =
                    getRoomAuthorTextStyleSpan(
                        "本周收到\n",
                        data.studentReplied.toString() + " ",
                        "个评价"
                    )

            }
            if (data.decimal == 0.00) {
                mViewBinding.tvMineIncomeCount.text = "本月收入\n0.00 元"
            } else {
                mViewBinding.tvMineIncomeCount.text =
                    getRoomAuthorTextStyleSpan(
                        "本月收入\n",
                        data.decimal.toString() + " ",
                        "元"
                    )
            }
            if (data.pianoTime == 0) {
                mViewBinding.tvMineKotofusaCount.text = "剩余\n0 分钟"
            } else {
                mViewBinding.tvMineKotofusaCount.text =
                    getRoomAuthorTextStyleSpan(
                        "剩余\n",
                        data.pianoTime.toString() + " ",
                        "分钟"
                    )
            }
        }
    }

    private fun getRoomAuthorTextStyleSpan(
        firstText: String,
        contentText: String,
        lastText: String
    ): SpannableString? {
        return UiUtils.diffColorString(
            firstText,
            contentText,
            lastText,
            resources.getColor(com.cooleshow.base.R.color.color_999999),
            resources.getColor(R.color.color_ff5160)
        )
    }


    override fun helpCenterContentListSuccess(data: HelpCenterContentBean?) {

        if (data?.rows != null && data.rows.size > 0) {
            mViewBinding.bgAnnouncement.visibility = View.VISIBLE
            mViewBinding.tvNoticeContent.text = data.rows[0].title
            noticeId = data.rows[0].id
        } else {
            mViewBinding.bgAnnouncement.visibility = View.INVISIBLE
        }

    }

    override fun queryCountOfUnreadSuccess(data: MutableList<CountOfUnreadBean>?) {
        if (null == data || data.size == 0) {
            mViewBinding.viewUnreadMessage.setVisibility(View.GONE)
            return
        }
        var totalCount = 0
        for (datum in data) {
            totalCount += datum.value
        }
        if (totalCount > 0) {
            mViewBinding.viewUnreadMessage.setVisibility(View.VISIBLE)
        } else {
            mViewBinding.viewUnreadMessage.setVisibility(View.GONE)
        }
    }

    override fun queryLiveAndVideoSuccess(bean: HomeLiveAndVideoBean?) {
        val recentCourses = bean?.recentCourses
        mViewBinding.clLive.setVisible(recentCourses != null)
        if (recentCourses != null) {
            mViewBinding.tvLiveTitle.setText(recentCourses.courseGroupName + "即将开始")
            mViewBinding.tvLiveTime.setText(recentCourses.courseStartTime)
            val currentTime = TimeUtils.date2String(Date(System.currentTimeMillis()), "yyyy-MM-dd")
            val startTime = TimeUtils.date2String(
                TimeUtils.getDate(recentCourses.courseStartTime),
                "yyyy-MM-dd"
            )
            if (TextUtils.equals(currentTime, startTime)) {
                val timeText =
                    TimeUtils.date2String(TimeUtils.getDate(recentCourses.courseStartTime), "HH:mm")
                mViewBinding.tvLiveTime.text = "今日 $timeText"
            } else {
                mViewBinding.tvLiveTime.text = TimeUtils.date2String(
                    TimeUtils.getDate(recentCourses.courseStartTime),
                    "yyyy-MM-dd HH:mm"
                )
            }
            mViewBinding.tvGoLive.setOnClickListener { v ->
                gotoCourseDetail(recentCourses)
            }
        }
    }

    override fun appHomeSuccess(homeMenuBean: HomeMenuBean?) {
        if (isDetached) {
            return;
        }
        if (homeMenuBean?.appMenu != null && homeMenuBean.appMenu.isNotEmpty()) {
            mViewBinding.flTopMenu.setVisible(true);
            fragments.clear()
            var count: Int = homeMenuBean.appMenu.size / 4
            if (homeMenuBean.appMenu.size % 4 > 0) {
                count++
            }
            for (i in 0 until count) {
                val dataList: ArrayList<HomeMenuBean.ItemBean> =
                    java.util.ArrayList<HomeMenuBean.ItemBean>()
                var j = i * 4
                while (j < homeMenuBean.appMenu.size && j < (i + 1) * 4) {
                    dataList.add(homeMenuBean.appMenu[j])
                    j++
                }
                fragments.add(HomeMenuFragment.newInstance(dataList))
            }
            menuAdapter.setFragments(fragments);
            menuAdapter.notifyDataSetChanged()
        } else {
            fragments.clear()
            menuAdapter.notifyDataSetChanged()
            mViewBinding.flTopMenu.setVisible(false);
        }
    }

    /**
     * 跳转直播课详情页面
     *
     * @param bean
     */
    private fun gotoCourseDetail(bean: HomeLiveAndVideoBean.RecentCoursesBean?) {
        when (bean?.courseType) {
            CourseConstants.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()
            CourseConstants.OTHER_COURSE ->                 //陪练课
                ARouter.getInstance().build(RouterPath.CourseCenter.SPARRING_COURSE_DETAIL)
                    .withString(CourseConstants.COURSE_ID, bean.courseId.toString())
                    .withString(CourseConstants.COURSE_GROUP_ID, bean.courseGroupId.toString())
                    .withString(CourseConstants.STUDENT_ID, bean.studentId.toString())
                    .navigation()
            CourseConstants.PIANO_ROOM_COURSE ->
                //琴房课 跳转详情页
                ARouter.getInstance().build(RouterPath.CourseCenter.PIANO_ROOM_COURSE_DETAIL)
                    .withString(CourseConstants.COURSE_ID, bean.courseId.toString())
                    .navigation()
        }
    }

}