package com.dlc.exam.ui.learn

import android.content.Intent
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.databinding.ActivityLearnRecordBinding
import com.dlc.exam.ui.MainActivity
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.LearnRecordReq
import com.rc.httpcore.vo.response.CategoryTree
import com.rc.httpcore.vo.response.LearnRecordVo
import io.reactivex.disposables.Disposable

/**
 * 学习记录
 *
 * @author ReiChin_
 */
class LearnRecordActivity :
    CommonListActivity<LearnRecordVo, ActivityLearnRecordBinding>(LearnRecordAdapter()),
    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() = ActivityLearnRecordBinding.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?.userName)

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

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

        queryCategoryTree()
    }

    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 = LearnRecordReq().apply {
            cateId = mCateId
            cateTitle = mTitle
            page = mCurrentPage
            pageSize = ListPageView.PAGE_SIZE
            scopeType = encodeScopeType()
        }
        return ApiRepository.examLearnRecord(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.courseId)
        intent.putExtra("record", true)
        startActivity(intent)
    }

    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))
    }

}

private class LearnRecordAdapter : PageQuickAdapter<LearnRecordVo>(R.layout.item_learn_record) {

    override fun convert(holder: BaseViewHolder, item: LearnRecordVo) {
        val pagePosition = pageOffsite + holder.adapterPosition + 1
        holder.setText(R.id.number, "$pagePosition")
//            .setText(R.id.courseTitle, item.courseTitle)
            .setText(R.id.courseTitle, item.title)
            .setText(R.id.cateTitle, item.cateTitle)
            .setText(R.id.scopeType, item.decodeScopeType())
            .setText(R.id.learnTime, item.learnTime)
            .setText(R.id.learnDuration, item.learnDurationStr)
            .setText(R.id.bonusPoints, item.bonusPoints)
            .setText(R.id.learnStatus, item.decodeLearnStatus())
    }

}