package com.dlc.exam.ui.learn

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.CheckBox
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dlc.exam.ExamApp
import com.dlc.exam.R
import com.dlc.exam.common.ExamType
import com.dlc.exam.databinding.ActivitySafetyLearnBinding
import com.dlc.exam.databinding.TreeHolderSelectableHeaderBinding
import com.dlc.exam.ui.common.CommonListActivity
import com.dlc.exam.ui.common.PageQuickAdapter
import com.dlc.exam.ui.me.PersonalCenterActivity
import com.dlc.exam.ui.widget.ListPageView
import com.dlc.exam.ui.widget.TitleBar
import com.dlc.exam.ui.widget.treeview.model.TreeNode
import com.dlc.exam.ui.widget.treeview.view.AndroidTreeView
import com.rc.httpcore.HttpClient
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.request.CourseListReq
import com.rc.httpcore.vo.response.CategoryTree
import com.rc.httpcore.vo.response.ExamCourseVo
import io.reactivex.disposables.Disposable

/**
 * 安全学习
 *
 * @author ReiChin_
 */
class SafetyLearnActivity :
    CommonListActivity<ExamCourseVo, ActivitySafetyLearnBinding>(SafetyLearnAdapter()),
    TitleBar.TitleListener {

    init {
        mAdapter.addChildClickViewIds(R.id.detail)
    }

    override val mSrlRefresh by lazy { viewBinding.swipeRefreshLayout }
    override val mRvContent by lazy { viewBinding.content }
    override val mListPageView by lazy { viewBinding.pageInfo }

    private lateinit var mTreeView: AndroidTreeView

    private var mCateId: String? = null
    private var mTitle: String? = null

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

    private val mExamTypeList = mutableListOf<CheckBox>()

    override fun initListener() {
        super.initListener()
        // 全部适用类型
        viewBinding.allType.setOnClickListener { view ->
            mExamTypeList.forEach { it.isChecked = it == view }
            mCurrentPage = ListPageView.FIRST_PAGE
            loadData(true)
        }
        // 安全准入考试
        viewBinding.safetyExam.setOnClickListener { view ->
            mExamTypeList.forEach { it.isChecked = it == view }
            mCurrentPage = ListPageView.FIRST_PAGE
            loadData(true)
        }
        // 负面清单考试
        viewBinding.negativeExam.setOnClickListener { view ->
            mExamTypeList.forEach { it.isChecked = it == view }
            mCurrentPage = ListPageView.FIRST_PAGE
            loadData(true)
        }
        // 黑名单考试
        viewBinding.blackListExam.setOnClickListener { view ->
            mExamTypeList.forEach { it.isChecked = it == view }
            mCurrentPage = ListPageView.FIRST_PAGE
            loadData(true)
        }
    }

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        viewBinding.titleBar.setTitleListener(this)
        viewBinding.titleBar.setUsername(ExamApp.sLearnLoginVo?.nickName)

        mExamTypeList.clear()
        mExamTypeList.add(viewBinding.allType)
        mExamTypeList.add(viewBinding.safetyExam)
        mExamTypeList.add(viewBinding.blackListExam)
        mExamTypeList.add(viewBinding.negativeExam)

        // 学习记录
        viewBinding.learnRecord.setOnClickListener {
            startActivity(Intent(this, LearnRecordActivity::class.java))
//            val learnChapterList = ArrayList<LearnChapterBean>()
//            learnChapterList.add(LearnChapterBean().apply {
//                chapterId = "123"
//                courseId = "321"
//
//                type = "2"; // 0 为目录 其他类型同课件类型 文件类型 1 文档，2 视频，3 图片，4 音频，5 富文本
//                chapterData = "http://mpvideo.qpic.cn/0b2eweaamaaauqaa7t5wqvqvbmoda2yqabqa.f10002.mp4?dis_k=8a466e6d05b1b427bd3e96a09366d287&amp;dis_t=1640341670&amp;vid=wxv_2176467267104899076&amp;format_id=10002&amp;support_redirect=0&amp;mmversion=false"
//                duration = 74
//                title = "航拍正在建设中西安地铁十号线浐灞段"
//            })
//
//            val intent = Intent(this, LearnDetailActivity::class.java)
//            intent.putExtra("nextChapter", learnChapterList)
//            intent.putExtra("relearn", true)
//            startActivityForResult(intent, 100)
        }

        viewBinding.search.setOnClickListener {
            mTreeView.deselectAll()
            mCateId = null
            mTitle = viewBinding.key.text.toString().trim()
            mCurrentPage = ListPageView.FIRST_PAGE
            loadData(true)
        }

        handleDefaultScopeType()

        queryCategoryTree()
    }

    private fun handleDefaultScopeType() {
        when (intent.getStringExtra("exam_type")) {
            ExamType.NEGATIVE.type -> defaultCheckedView(viewBinding.negativeExam)
            ExamType.BLACK_LIST.type -> defaultCheckedView(viewBinding.blackListExam)
        }
    }

    private fun defaultCheckedView(view: View) {
        mExamTypeList.forEach { it.isChecked = it == view }
        mCurrentPage = ListPageView.FIRST_PAGE
    }

    private fun queryCategoryTree() {
        showLoading("加载中...")
        val disposable = ApiRepository.categoryTreeList()
            .subscribe({
                dismissLoading()
                initCategoryTree(it)
            }, { throwable ->
                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    private fun initCategoryTree(nodeData: List<CategoryTree>) {
        val root = TreeNode.root()

        val categoryTree = CategoryTree().apply {
            id = ""
            title = "所有分类"
        }
        val treeNode = TreeNode(TreeItem(categoryTree))
        treeNode.viewHolder = ArrowExpandSelectableHeaderHolder(this)
        treeNode.setClickListener { node, value ->
            dispatchTreeNodeClicked(node, value as TreeItem)
        }
        treeNode.isSelected = true
        root.addChildren(treeNode)

        fillFolder(root, nodeData)

        mTreeView = AndroidTreeView(this, root)
        mTreeView.setDefaultAnimation(true)
        mTreeView.setDefaultContainerStyle(R.style.TreeNodeStyleCustom)
        mTreeView.isSelectionModeEnabled = true
        viewBinding.courseType.addView(mTreeView.view)
        mTreeView.setUseAutoToggle(false)
    }

    private fun fillFolder(node: TreeNode, nodeData: List<CategoryTree>?) {
        nodeData?.forEach { item ->
            val childNode = TreeNode(TreeItem(item))
            childNode.viewHolder = ArrowExpandSelectableHeaderHolder(this)
            childNode.setClickListener { node, value ->
                dispatchTreeNodeClicked(node, value as TreeItem)
            }
            node.addChild(childNode)
            fillFolder(childNode, item.children)
        }
    }

    private fun dispatchTreeNodeClicked(node: TreeNode, value: TreeItem) {
        mTreeView.deselectAll()
        mTreeView.selectNode(node, true)

        mCateId = value.data!!.id
        mTitle = null
        mCurrentPage = ListPageView.FIRST_PAGE
        loadData(true)
    }

    override fun queryData(): Disposable? {
        showLoading("查询中...")
        val param = CourseListReq().apply {
            cateId = mCateId
            title = mTitle
            pageNum = mCurrentPage
            pageSize = ListPageView.PAGE_SIZE
            scopeType = encodeScopeType()
        }
        return ApiRepository.examCourseList(param)
            .subscribe({
                dismissLoading()
                dispatchLoadDataSuccess(it.rows, it.total)
            }, { throwable ->
                dismissLoading()
                dispatchLoadDataFailure(throwable)
            })
    }

    private fun encodeScopeType(): String {
        // 1. 安全准入考试，2. 负面清单考试，3. 黑名单考试
        return when {
            viewBinding.safetyExam.isChecked -> "1"
            viewBinding.negativeExam.isChecked -> "2"
            viewBinding.blackListExam.isChecked -> "3"
            else -> ""
        }
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = mAdapter.getItem(position)
        // 详情
        val intent = Intent(this, CourseChapterActivity::class.java)
        intent.putExtra("courseId", item.id)
        intent.putExtra("record", false)
        startActivity(intent)
    }

    override fun onRestart() {
        super.onRestart()
        loadData()
    }

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

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

            ExamApp.sLearnLoginVo = null
            HttpClient.token = null
            finish()
        }
    }

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

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

}

class ArrowExpandSelectableHeaderHolder(context: Context) :
    TreeNode.BaseNodeViewHolder<TreeItem>(context) {

    private lateinit var viewBinding: TreeHolderSelectableHeaderBinding

    override fun createNodeView(node: TreeNode?, value: TreeItem?): View {
        viewBinding = TreeHolderSelectableHeaderBinding.inflate(LayoutInflater.from(context))
        viewBinding.nodeValue.text = value?.data?.title

//        if (true == node?.isLeaf) {
//            viewBinding.arrowIcon.visibility = View.INVISIBLE
//        }
        viewBinding.arrowIcon.setOnClickListener {
            tView.toggleNode(node)
        }

        return viewBinding.root
    }

    override fun toggle(active: Boolean) {
        val imageRes = if (active) R.mipmap.ic_substract else R.mipmap.ic_plus
        viewBinding.arrowIcon.setImageResource(imageRes)
    }

    override fun toggleSelectionMode(editModeEnabled: Boolean) {
        val textColor = Color.parseColor(if (mNode.isSelected) "#349CFB" else "#333333")
        viewBinding.nodeValue.setTextColor(textColor)
    }

}

data class TreeItem(val data: CategoryTree?)

private class SafetyLearnAdapter : PageQuickAdapter<ExamCourseVo>(R.layout.item_safety_learn) {

    override fun convert(holder: BaseViewHolder, item: ExamCourseVo) {
        val pagePosition = pageOffsite + holder.adapterPosition + 1
        holder.setText(R.id.number, "$pagePosition")
            .setText(R.id.title, item.title)
            .setText(R.id.cateTitle, item.cateTitle)
            .setText(R.id.chapters, item.chapters)
            .setText(R.id.scopeType, item.decodeScopeType())
            .setText(R.id.duration, item.durationsStr)
            .setText(R.id.createTime, item.createTime)
            .setText(R.id.accessNum, item.accessNum)
            .setText(R.id.learnStatus, item.decodeLearnStatus())
    }

}