package com.dlc.exam.ui.learn.test

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
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.ActivityClassTestRecordBinding
import com.dlc.exam.ui.MainActivity
import com.dlc.exam.ui.common.BaseCountDownActivity
import com.dlc.exam.ui.me.PersonalCenterActivity
import com.dlc.exam.ui.widget.TitleBar
import com.rc.httpcore.HttpClient
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.response.ExamTopic
import java.lang.StringBuilder

/**
 * info
 *
 * @author ReiChin_
 */
class ClassTestRecordActivity : BaseCountDownActivity<ActivityClassTestRecordBinding>(),
    TitleBar.TitleListener {

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

    private val mTopicAdapter by lazy { TopicAdapter() }

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

        viewBinding.topicInfo.layoutManager = LinearLayoutManager(this)
        viewBinding.topicInfo.adapter = mTopicAdapter
    }

    override fun initData() {
        super.initData()
        // 查询数据，并显示
        queryClassTestTopic()
    }

    private fun queryClassTestTopic() {
        val paperId = intent.getStringExtra("paperId")
        if (paperId.isNullOrEmpty()) {
            finish()
            return
        }

        showLoading("加载中...")
        val disposable = ApiRepository.classTestDetail(paperId)
            .subscribe({
                dismissLoading()
                updateViews(it)
            }, { throwable ->
                dismissLoading()
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    @SuppressLint("SetTextI18n")
    private fun updateViews(data: ExamTopic?) {
        data?.let {
            it.otherData?.let { otherData ->
                // 考核名称
                viewBinding.modelName.text = otherData.assessName
                // 章节名称
                viewBinding.chapterName.text = otherData.title

                val answerInfo = StringBuilder("题目总数：${otherData.allQu}")
                if (!it.radioList.isNullOrEmpty()) {
                    answerInfo.append("          ")
                        .append("单选题数：${otherData.radioQu}")
                }
                if (!it.multiList.isNullOrEmpty()) {
                    answerInfo.append("          ")
                        .append("多选题数：${otherData.multiQu}")
                }
                if (!it.judgeList.isNullOrEmpty()) {
                    answerInfo.append("          ")
                        .append("判断题数：${otherData.judgeQu}")
                }
                viewBinding.answerInfo.text = answerInfo

                // 考核结果
                if ("100" == otherData.accuracy) {
                    viewBinding.classTestResult.text = "考核结果：全部正确，考核通过。"
                    viewBinding.completed.visibility = View.VISIBLE
                } else {
                    viewBinding.classTestResult.text = "考核结果：考核未通过。"
                    viewBinding.completed.visibility = View.GONE
                }
            }

            // 考题
            val topicData = generateTopicInfo(it.radioList, it.multiList, it.judgeList)
            mTopicAdapter.setNewInstance(topicData)
            if (topicData.isNullOrEmpty()) {
                mTopicAdapter.setEmptyView(com.rc.core.R.layout.view_list_empty)
            }
        }
    }

    private fun generateTopicInfo(
        radioList: List<ExamTopic.ElPaperQu>?,
        multiList: List<ExamTopic.ElPaperQu>?,
        judgeList: List<ExamTopic.ElPaperQu>?
    ): MutableList<TopicInfo> {

        var topicOffset = 1
        val result = mutableListOf<TopicInfo>()

        // 单选题
        if (!radioList.isNullOrEmpty()) {
            result.add(TopicInfo(TopicAdapter.ITEM_GROUP, ItemData("一、单选题", radioList.size)))

            radioList.forEachIndexed { index, elPaperQu ->
                result.add(
                    TopicInfo(
                        TopicAdapter.ITEM_TOPIC,
                        ItemData(topicData = elPaperQu),
                        index + topicOffset
                    )
                )
            }
            topicOffset += radioList.size
        }

        // 多选题
        if (!multiList.isNullOrEmpty()) {
            val groupName = if (result.isEmpty()) "一、多选题" else "二、多选题"
            result.add(TopicInfo(TopicAdapter.ITEM_GROUP, ItemData(groupName, multiList.size)))

            multiList.forEachIndexed { index, elPaperQu ->
                result.add(
                    TopicInfo(
                        TopicAdapter.ITEM_TOPIC,
                        ItemData(topicData = elPaperQu),
                        index + topicOffset
                    )
                )
            }
            topicOffset += multiList.size
        }

        // 判断题
        if (!judgeList.isNullOrEmpty()) {
            val groupName =
                if (result.isEmpty()) "一、判断题" else if (multiList.isNullOrEmpty()) "二、判断题" else "三、判断题"
            result.add(TopicInfo(TopicAdapter.ITEM_GROUP, ItemData(groupName, judgeList.size)))

            judgeList.forEachIndexed { index, elPaperQu ->
                result.add(
                    TopicInfo(
                        TopicAdapter.ITEM_TOPIC,
                        ItemData(topicData = elPaperQu),
                        index + topicOffset
                    )
                )
            }
        }

        return result
    }

    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 TopicInfo(val itemType: Int, val data: ItemData, val pIndex: Int = -1)

data class ItemData(
    val groupName: String? = null,
    val topicCount: Int = 0,
    val topicData: ExamTopic.ElPaperQu? = null
)

private class TopicAdapter : BaseDelegateMultiAdapter<TopicInfo, BaseViewHolder>() {

    companion object {
        const val ITEM_GROUP = 1
        const val ITEM_TOPIC = 2
    }

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

            override fun getItemType(data: List<TopicInfo>, position: Int) =
                data[position].itemType
        })
        getMultiTypeDelegate()!!
            .addItemType(ITEM_GROUP, R.layout.item_topic_group)
            .addItemType(ITEM_TOPIC, R.layout.item_topic)
    }

    override fun convert(holder: BaseViewHolder, item: TopicInfo) {
        when (holder.itemViewType) {
            ITEM_GROUP -> convertTopicGroup(holder, item.data)
            ITEM_TOPIC -> convertTopic(holder, item.pIndex, item.data.topicData)
        }
    }

    private fun convertTopicGroup(holder: BaseViewHolder, item: ItemData) {
        holder.setText(R.id.groupName, item.groupName)
            .setText(R.id.topicCount, "（共${item.topicCount}题）")
    }

    private fun convertTopic(holder: BaseViewHolder, pIndex: Int, item: ExamTopic.ElPaperQu?) {
        // 题干
        holder.setText(R.id.topic, "${pIndex}、${item?.content ?: ""}")

        // 选项
        val recyclerView = holder.getView<RecyclerView>(R.id.topicOptions)
        val optionAdapter = ReviewTopicOptionAdapter(item?.elPaperQuAnswerList, false)
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = optionAdapter
        optionAdapter.setEmptyView(com.rc.core.R.layout.view_list_empty)

        // 答案
//        val isRight = "1" == item?.isRight ?: false
        val isRight = true == item?.isRight ?: false
        holder.setGone(R.id.myAnswer, item?.elPaperQuAnswerList.isNullOrEmpty())
            .setText(R.id.myAnswer, if (isRight) "正确" else "错误")
            .setTextColor(R.id.myAnswer, Color.parseColor(if (isRight) "#349CFB" else "#FF6060"))
    }

    private fun topicAnswer(options: List<ExamTopic.ElPaperQuAnswer>?): String {
        if (options.isNullOrEmpty()) return ""

        val answer = StringBuilder()
        options.forEach {
            if (  it.isRight) answer.append(it.abc)
        }
        return answer.toString()
    }

}