package com.dlc.exam.ui.learn

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseDelegateMultiAdapter
import com.chad.library.adapter.base.delegate.BaseMultiTypeDelegate
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dlc.exam.ExamApp
import com.dlc.exam.R
import com.dlc.exam.databinding.ActivityCourseChapterBinding
import com.dlc.exam.ui.MainActivity
import com.dlc.exam.ui.common.BaseCountDownActivity
import com.dlc.exam.ui.learn.test.ClassTestActivity
import com.dlc.exam.ui.learn.test.ClassTestRecordListActivity
import com.dlc.exam.ui.me.PersonalCenterActivity
import com.dlc.exam.ui.widget.TitleBar
import com.google.gson.Gson
import com.rc.httpcore.HttpClient
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.response.ExamCourseVo

/**
 * 安全学习-章节
 *
 * @author ReiChin_
 */
class CourseChapterActivity : BaseCountDownActivity<ActivityCourseChapterBinding>(),
    TitleBar.TitleListener {

    override fun createViewBinding() =
        ActivityCourseChapterBinding.inflate(LayoutInflater.from(this))

    private val mChapterAdapter by lazy { ChapterAdapter() }
    private var mCourseId: String = ""
    private var mRecord: Boolean = false
    private var mVideoDraggable: String? = null

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        viewBinding.titleBar.setTitleListener(this)
        viewBinding.titleBar.setUsername(ExamApp.sLearnLoginVo?.userName)
        mRecord = intent.getBooleanExtra("record", false)

        mChapterAdapter.record = mRecord
        mChapterAdapter.addChildClickViewIds(R.id.startLearn, R.id.classTest, R.id.classTestRecord)
        mChapterAdapter.setOnItemChildClickListener { _, view, position ->
            val item = mChapterAdapter.data[position]
            when (view.id) {
                R.id.startLearn -> {
                    // 开始学习
//                    dispatchStartLearn(item.data.learnStatus, position)
                    dispatchStartLearn(item.data)
                }

                R.id.classTest -> {
                    // 课后考核课后考核
                    dispatchClassTest(item.data.id)
                }

                R.id.classTestRecord -> {
                    // 考核记录
                    dispatchClassTestRecord(item.data.id)
                }
            }
        }
        viewBinding.chapterContent.layoutManager = LinearLayoutManager(this)
        viewBinding.chapterContent.adapter = mChapterAdapter
    }

    private fun dispatchClassTestRecord(chapterId: String?) {
        val intent = Intent(this, ClassTestRecordListActivity::class.java)
        intent.putExtra("chapterId", chapterId)
        startActivity(intent)
    }

    private fun dispatchClassTest(chapterId: String?) {
        val intent = Intent(this, ClassTestActivity::class.java)
        intent.putExtra("chapterId", chapterId)
        startActivityForResult(intent, 100)
    }

    private fun dispatchStartLearn(courseVo: ExamCourseVo.ChapterVo) {
        val chapterBean = LearnChapterBean().apply {
            chapterId = courseVo.id
            courseId = courseVo.courseId
            type = courseVo.type
            chapterData = courseVo.chapterData
            duration = courseVo.duration
            title = courseVo.title
            assessStatus = courseVo.showClassTest()
        }
        val intent = Intent()
        intent.putExtra("Chapter", chapterBean)
        intent.putExtra("relearn", "1" == courseVo.learnStatus)
        //  视频处理
        if (chapterBean.type == "2") {
            intent.setClass(this, LearnDetailExoActivity::class.java)
        }
        // WebView处理
        else {
            intent.setClass(this, LearnDetailLibOfficeActivity::class.java)
        }
        startActivityForResult(intent, 100)
    }

    private fun dispatchStartLearn(learnStatus: String?, position: Int) {
//        val intent = Intent(this, FullScreenActivity::class.java)
//        startActivityForResult(intent, 100)
        val intent = Intent(this, LearnDetailActivity::class.java)
        intent.putExtra("nextChapter", nextChapterList(position))
        intent.putExtra("relearn", "1" == learnStatus)
        intent.putExtra("videoDraggable", "0" != mVideoDraggable)
        startActivityForResult(intent, 100)
    }

    private fun nextChapterList(position: Int): ArrayList<LearnChapterBean> {
        val learnChapterList = ArrayList<LearnChapterBean>()
        val size = mChapterAdapter.data.size
        for (index in position until size) {
            val item = mChapterAdapter.data[index]
            if (item.itemType == ChapterAdapter.PLAN_SECTION
                && (index == position || "1" != item.data.learnStatus)
            ) {
                val chapterBean = LearnChapterBean().apply {
                    chapterId = item.data.id
                    courseId = item.data.courseId
                    type = item.data.type
                    chapterData = item.data.chapterData
                    duration = item.data.duration
                    title = item.data.title
                    assessStatus = item.data.showClassTest()
                }
                learnChapterList.add(chapterBean)
            }
        }
        return learnChapterList
    }

    override fun initData() {
        super.initData()
        mCourseId = intent.getStringExtra("courseId") ?: ""
        queryCourseDetail()
    }

    private fun queryCourseDetail() {
        showLoading("加载中...")
        val disposable = ApiRepository.examCourseDetail(mCourseId)
            .subscribe({
                dismissLoading()
                updateViews(it)
            }, { throwable ->
                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    @SuppressLint("SetTextI18n")
    private fun updateViews(data: ExamCourseVo?) {
        LogUtils.json(data)
        data?.let {
            mVideoDraggable = it.videoDraggable

            if (0L != it.learnDurations) {
                // 已学习时长
                viewBinding.learnDuration.text = "已学习时长：${it.learnDurationStr ?: ""}"
            }
            // 章节名称
            viewBinding.chapterName.text = data.allCateTitle
            // 学习时长
            viewBinding.time.text = "学习时长：${it.durationsStr ?: ""}"
            // 有效期
            viewBinding.termValidity.text =
                "有效期：${if ("0" == it.ceType) "永久" else it.ceTime ?: ""}"
            // 已有1250人学习
            viewBinding.learnPersonCount.text = "已有${it.learns ?: "0"}人学习"

            val chapterData = generateChapterData(it.chapterList)
            mChapterAdapter.setNewInstance(chapterData)
            if (chapterData.isNullOrEmpty()) {
                mChapterAdapter.setEmptyView(com.rc.core.R.layout.view_list_empty)
            }
        }
    }

    private fun generateChapterData(data: List<ExamCourseVo.ChapterVo>?): MutableList<ChapterInfo>? {
        if (data.isNullOrEmpty()) return null

        val result = mutableListOf<ChapterInfo>()
        data.forEachIndexed { index, pItem ->
            result.add(ChapterInfo(ChapterAdapter.PLAN_CHAPTER, pItem, index))
            if (!pItem.children.isNullOrEmpty()) {
                pItem.children.mapTo(result, {
                    ChapterInfo(ChapterAdapter.PLAN_SECTION, it)
                })
            }
        }
        return result
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (100 == requestCode) {
            if (RESULT_OK == resultCode) {
                queryCourseDetail()
            }
        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    override fun onHomeViewClicked(view: View) {
        startActivity(Intent(this, MainActivity::class.java))
    }

    override fun onLogoutViewClicked(view: View) {
        callLogoutApi {
            showToast("已退出登录")

            ExamApp.sLearnLoginVo = null
            HttpClient.token = null

            startActivity(Intent(this, MainActivity::class.java))
        }
    }

    override fun onBackViewClicked(view: View) {
        finish()
    }

    override fun onUserViewClicked(view: View) {
        startActivity(Intent(this, PersonalCenterActivity::class.java))
    }

}

data class ChapterInfo(val itemType: Int, val data: ExamCourseVo.ChapterVo, val pIndex: Int = -1)

private class ChapterAdapter : BaseDelegateMultiAdapter<ChapterInfo, BaseViewHolder>() {

    var record: Boolean = false

    companion object {
        const val PLAN_CHAPTER = 1
        const val PLAN_SECTION = 2
    }

    init {
        setMultiTypeDelegate(object : BaseMultiTypeDelegate<ChapterInfo>() {

            override fun getItemType(data: List<ChapterInfo>, position: Int) =
                data[position].itemType
        })
        getMultiTypeDelegate()!!
            .addItemType(PLAN_CHAPTER, R.layout.item_chapter)
            .addItemType(PLAN_SECTION, R.layout.item_section)
    }

    override fun convert(holder: BaseViewHolder, item: ChapterInfo) {
        when (holder.itemViewType) {
            PLAN_CHAPTER -> convertChapter(holder, item)
            PLAN_SECTION -> convertSection(holder, item)
        }
    }

    private fun convertChapter(holder: BaseViewHolder, item: ChapterInfo) {
        holder.setText(R.id.chapterPosition, "${item.pIndex + 1}")
            .setText(R.id.chapterName, item.data.title)
    }

    private fun convertSection(holder: BaseViewHolder, item: ChapterInfo) {
        holder.setText(R.id.sectionName, item.data.title)
            .setText(R.id.videoDuration, "时长：${item.data.durationStr ?: ""}")

        // 学习状态 0 学习中，2 未学习，3 待考核，1 已完成
        val learnStatus = item.data.formatLearnStatus()
        holder.setGone(R.id.learnCompleted, 2 == learnStatus)
        learnStatusImg(learnStatus)?.let { holder.setImageResource(R.id.learnCompleted, it) }

        if (record) {
            holder.setGone(R.id.startLearn, true)
                .setGone(R.id.classTest, true)
                .setGone(R.id.learnDuration, "1" != item.data.learnStatus)
                .setText(R.id.learnDuration, "已学习时长：${item.data.durationStr ?: ""}")
                .setGone(R.id.classTestRecord, !item.data.showClassTestRecord())
        } else {
            holder.setGone(R.id.startLearn, false)
                .setText(
                    R.id.startLearn,
                    if ("1" == item.data.learnStatus) "重新学习" else "开始学习"
                )
                .setGone(R.id.classTest, !item.data.showClassTest())
                .setGone(R.id.learnDuration, true)
                .setGone(R.id.classTestRecord, true)
        }
    }

    /**
     * 学习状态imageview src
     *
     * @param learnStatus 学习状态 0 学习中，2 未学习，3 待考核，1 已完成
     */
    private fun learnStatusImg(learnStatus: Int): Int? {
        return when (learnStatus) {
            0 -> R.mipmap.icon_xxzyz
            1 -> R.mipmap.icon_ywcyz
            3 -> R.mipmap.icon_dkhyz
            else -> null
        }
    }

}