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

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dlc.exam.R
import com.dlc.exam.databinding.FragmentExamTopicBinding
import com.dlc.exam.ui.score.ITopicChange
import com.dlc.exam.ui.score.PaperQuViewModel
import com.rc.core.ui.fragment.RcBaseFragment
import com.rc.httpcore.vo.response.ExamTopic
import java.lang.StringBuilder

/**
 * info
 *
 * @author ReiChin_
 */
class ReviewClassTestFragment : RcBaseFragment<FragmentExamTopicBinding>() {

    companion object {
        const val FRAGMENT_TAG = "ReviewClassTestFragment"

        fun newInstance() = ReviewClassTestFragment()
    }

    private val viewModel by lazy {
        ViewModelProvider(requireActivity(), ViewModelProvider.NewInstanceFactory()).get(
            PaperQuViewModel::class.java
        )
    }

    private var mCurrentNum: Int = 1 // 当前题目编号
    private var mTopicTotal: Int = 0 // 总题目数据

    private val mOptionAdapter by lazy { ReviewTopicOptionAdapter() }

    private var mITopicChange: ITopicChange? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is ITopicChange) {
            this.mITopicChange = context
        }
    }

    override fun onDetach() {
        this.mITopicChange = null
        super.onDetach()
    }

    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ) = FragmentExamTopicBinding.inflate(inflater, container, false)

    @SuppressLint("SetTextI18n")
    override fun initViews(savedInstanceState: Bundle?) {
        viewBinding.remainingTimeLabel.visibility = View.GONE
        viewBinding.remainingTime.visibility = View.GONE
        viewBinding.topicTypeDesc.visibility = View.GONE

        viewModel.paperQuData.observe(viewLifecycleOwner) { data ->
            mCurrentNum = data.currentNum
            mTopicTotal = data.topicTotal
            updateViews(data)
        }

        viewModel.groupInfoData.observe(viewLifecycleOwner) { data ->
            viewBinding.topicType.text = data.topicType.desc
        }

        viewBinding.topicOptions.layoutManager = LinearLayoutManager(requireContext())
        viewBinding.topicOptions.adapter = mOptionAdapter

        viewBinding.prevTopic.setOnClickListener {
            //  上一题
            val prevIndex = mCurrentNum - 2
            if (prevIndex < 0) {
                showToast("已经是第一题")
                return@setOnClickListener
            }
            mITopicChange?.onTopicChanged(prevIndex)
        }
        viewBinding.nextTopic.setOnClickListener {
            // 下一题
            val nextIndex = mCurrentNum
            if (nextIndex >= mTopicTotal) {
                showToast("已经是最后题")
                return@setOnClickListener
            }
            mITopicChange?.onTopicChanged(nextIndex)
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateViews(data: ExamTopic.ElPaperQu?) {
        // 题干
        // 18、题目名称题目名称题目名称题目名称题目名称题目名称题目名称题目名称。
        viewBinding.topic.text = "${data?.currentNum ?: ""}、${data?.content ?: ""}"

        // 选项
        mOptionAdapter.setNewInstance(data?.elPaperQuAnswerList)

        // 答案
        viewBinding.answerInfo.visibility = View.VISIBLE
        val isRight = true == data?.isRight ?: false
        viewBinding.myAnswer.text = if (isRight) "正确" else "错误"
        viewBinding.myAnswer.setTextColor(Color.parseColor(if (isRight) "#349CFB" else "#FF6060"))
//        viewBinding.topicAnswer.text = "答案：${topicAnswer(data?.elPaperQuAnswerList)}"
    }

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

}

class ReviewTopicOptionAdapter(
    data: MutableList<ExamTopic.ElPaperQuAnswer>? = null,
    private val showAnswer: Boolean = true
) :
    BaseQuickAdapter<ExamTopic.ElPaperQuAnswer, BaseViewHolder>(R.layout.item_topic_option, data) {

    override fun convert(holder: BaseViewHolder, item: ExamTopic.ElPaperQuAnswer) {
        holder.setText(R.id.optionText, "${item.abc}: ${item.content}")
            .setTextColor(R.id.optionText, optionTextColor(item.isRight, item.checked))
            .setImageResource(R.id.optionRadio, radioImageResource(item.isRight, item.checked))
    }

    private fun optionTextColor(isRight: Boolean, checked: Boolean): Int {
        return when (checked) {
            true -> {
                if (showAnswer) {
                    if (isRight)
                        Color.parseColor("#349CFB")
                    else
                        Color.parseColor("#FF6060")
                } else
                    Color.parseColor("#0183FA")
            }
            else -> Color.parseColor("#333333")
        }
    }

    private fun radioImageResource(isRight: Boolean, checked: Boolean): Int {
        return when (checked) {
            true -> {
                if (showAnswer) {
                    if (isRight)
                        R.drawable.ic_radio_on_right
                    else
                        R.drawable.ic_radio_on_error
                } else
                    R.drawable.ic_radio_on_normal
            }
            else -> R.drawable.ic_radio_off
        }
    }

}