package com.dlc.exam.ui.score

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
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.TopicType
import com.dlc.exam.databinding.ActivityExamScoreDetailBinding
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.request.PaperQuReq
import com.rc.httpcore.vo.response.ExamTopic

/**
 * 考试成绩详情
 *
 * @author ReiChin_
 */
class ExamScoreDetailActivity : BaseCountDownActivity<ActivityExamScoreDetailBinding>(),
    ITopicChange, TitleBar.TitleListener {

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

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

    override fun initListener() {
        viewBinding.titleBar.setTitleListener(this)

        viewBinding.radioTopicArrow.setOnClickListener {
            dispatchTopicArrowClicked(it as ImageView, viewBinding.radioTopicNumber)
        }
        viewBinding.multiTopicArrow.setOnClickListener {
            dispatchTopicArrowClicked(it as ImageView, viewBinding.multiTopicNumber)
        }
        viewBinding.judgeTopicArrow.setOnClickListener {
            dispatchTopicArrowClicked(it as ImageView, viewBinding.judgeTopicNumber)
        }
    }

    private fun dispatchTopicArrowClicked(target: ImageView, recyclerView: RecyclerView) {
        // 是否为展开状态
        val isSpread = target.tag as? Boolean ?: true
        if (isSpread) {
            // 展开状态，点击后变为折叠状态
            recyclerView.visibility = View.GONE
            target.setImageResource(R.mipmap.icon_ksxt_zk)
        } else {
            // 折叠状态，点击后变为展开状态
            recyclerView.visibility = View.VISIBLE
            target.setImageResource(R.mipmap.icon_ksxt_sq)
        }
        target.tag = !isSpread
    }

    private val mRadioTopicAdapter by lazy { TopicNumberAdapter() }
    private val mMultiTopicAdapter by lazy { TopicNumberAdapter() }
    private val mJudgeTopicAdapter by lazy { TopicNumberAdapter() }

    override fun initViews(savedInstanceState: Bundle?) {
        viewBinding.titleBar.setUsername(ExamApp.sLearnLoginVo?.nickName)
        viewBinding.modelName.text = intent.getStringExtra("scopeType")

        initRecycleView(mRadioTopicAdapter, viewBinding.radioTopicNumber)
        initRecycleView(mMultiTopicAdapter, viewBinding.multiTopicNumber)
        initRecycleView(mJudgeTopicAdapter, viewBinding.judgeTopicNumber)

        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(
            R.id.topicContainer,
            PaperQuFragment.newInstance(),
            PaperQuFragment.FRAGMENT_TAG
        )
        transaction.commit()
    }

    private fun initRecycleView(numberAdapter: TopicNumberAdapter, recyclerView: RecyclerView) {
        numberAdapter.setOnItemClickListener { adapter, _, position ->
            val item = numberAdapter.getItem(position)
            mRadioTopicAdapter.selectItemId = item.id
            mRadioTopicAdapter.notifyDataSetChanged()
            mMultiTopicAdapter.selectItemId = item.id
            mMultiTopicAdapter.notifyDataSetChanged()
            mJudgeTopicAdapter.selectItemId = item.id
            mJudgeTopicAdapter.notifyDataSetChanged()

            val topicIdx = numberAdapter.indexOffsite + position + 1
            val topicTotal =
                mRadioTopicAdapter.data.size + mMultiTopicAdapter.data.size + mJudgeTopicAdapter.data.size
            queryPaperQuDetail(topicIdx, topicTotal, item.paperId, item.quId)

            if (adapter == mRadioTopicAdapter) {
                viewModel.setTopicGroupInfo(TopicGroupInfo(TopicType.RADIO, adapter.data.size))
            } else if (adapter == mMultiTopicAdapter) {
                viewModel.setTopicGroupInfo(TopicGroupInfo(TopicType.MULTI, adapter.data.size))
            } else if (adapter == mJudgeTopicAdapter) {
                viewModel.setTopicGroupInfo(TopicGroupInfo(TopicType.JUDGE, adapter.data.size))
            }
        }
        recyclerView.layoutManager = GridLayoutManager(this, 5)
        recyclerView.adapter = numberAdapter
    }

    override fun onTopicChanged(index: Int) {
        // 题目总数
        val radioSize = mRadioTopicAdapter.data.size
        val multiSize = mMultiTopicAdapter.data.size
        val judgeSize = mJudgeTopicAdapter.data.size
        val topicTotal = radioSize + multiSize + judgeSize
        if (index < 0 || index >= topicTotal) return

        if (index < radioSize) {
            // 单选题
            val item = mRadioTopicAdapter.data[index]
            changeTopic(item, index, topicTotal)
            viewModel.setTopicGroupInfo(TopicGroupInfo(TopicType.RADIO, radioSize))
        } else if (index < radioSize + multiSize) {
            // 多选题
            val item = mMultiTopicAdapter.data[index - radioSize]
            changeTopic(item, index, topicTotal)
            viewModel.setTopicGroupInfo(TopicGroupInfo(TopicType.MULTI, multiSize))
        } else if (index < topicTotal) {
            // 判断题
            val item = mJudgeTopicAdapter.data[index - radioSize - multiSize]
            changeTopic(item, index, topicTotal)
            viewModel.setTopicGroupInfo(TopicGroupInfo(TopicType.JUDGE, multiSize))
        }
    }

    /**
     * 用户答案提交成功后回调
     *
     * @param index 当前题目编号，从0开始
     * @param right 是否回答正确
     */
    override fun onAnswered(index: Int, right: Boolean) {
    }

    private fun changeTopic(item: ExamTopic.ElPaperQu, index: Int, topicTotal: Int) {
        mRadioTopicAdapter.selectItemId = item.id
        mRadioTopicAdapter.notifyDataSetChanged()
        mMultiTopicAdapter.selectItemId = item.id
        mMultiTopicAdapter.notifyDataSetChanged()
        mJudgeTopicAdapter.selectItemId = item.id
        mJudgeTopicAdapter.notifyDataSetChanged()
        queryPaperQuDetail(index + 1, topicTotal, item.paperId, item.quId)
    }

    private fun queryPaperQuDetail(
        currentNum: Int,
        topicTotal: Int,
        paperId: String?,
        quId: String?
    ) {
        showLoading("查询中...")
        val param = PaperQuReq()
        param.paperId = paperId
        param.quId = quId
        val disposable = ApiRepository.paperExamQuDetail(param)
            .subscribe({
                dismissLoading()
                it.currentNum = currentNum
                it.topicTotal = topicTotal
                viewModel.setPaperQu(it)
            }, { throwable ->
                dismissLoading()
                val data = ExamTopic.ElPaperQu()
                data.currentNum = currentNum
                data.topicTotal = topicTotal
                viewModel.setPaperQu(data)
                throwable.printStackTrace()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }


    override fun initData() {
        super.initData()
        queryScoreDetail()
    }

    private fun queryScoreDetail() {
        intent.getStringExtra("paperId")?.let { paperId ->
            showLoading("加载中")
            val disposable = ApiRepository.paperDetail(paperId)
                .subscribe({
                    dismissLoading()
                    updateViews(it)
                }, { throwable ->
                    dismissLoading()
                    throwable.printStackTrace()
                    showNetError(throwable)
                })
            addDisposable(disposable)
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateViews(data: ExamTopic?) {
        data?.let {
            viewBinding.examName.text = it.title
            viewBinding.examScore.text = "考试得分：${it.userScore}分"
            viewBinding.examDuration.text = "考试用时：${it.userTimeStr}"

            var firstSelectItem: ExamTopic.ElPaperQu? = null
            if (it.radioList.isNullOrEmpty()) {
                viewBinding.radioTopicGroup.visibility = View.GONE
                viewBinding.radioTopicNumber.visibility = View.GONE
            } else {
                viewBinding.radioTopicGroup.visibility = View.VISIBLE
                viewBinding.radioTopicNumber.visibility = View.VISIBLE
                viewBinding.radioTopicScore.text = "(分值${it.examConfig.radioSumScore})"
                firstSelectItem = it.radioList[0]
                mRadioTopicAdapter.selectItemId = firstSelectItem.id
                mRadioTopicAdapter.setNewInstance(it.radioList)
                viewModel.setTopicGroupInfo(TopicGroupInfo(TopicType.RADIO, it.radioList.size))
            }

            if (it.multiList.isNullOrEmpty()) {
                viewBinding.multiTopicGroup.visibility = View.GONE
                viewBinding.multiTopicNumber.visibility = View.GONE
            } else {
                viewBinding.multiTopicGroup.visibility = View.VISIBLE
                viewBinding.multiTopicNumber.visibility = View.VISIBLE
                viewBinding.multiTopicScore.text = "(分值${it.examConfig.multiSumScore})"
                if (null == firstSelectItem) {
                    firstSelectItem = it.multiList[0]
                    viewModel.setTopicGroupInfo(TopicGroupInfo(TopicType.MULTI, it.multiList.size))
                }
                mMultiTopicAdapter.selectItemId = firstSelectItem!!.id
                mMultiTopicAdapter.indexOffsite = it.radioList.size
                mMultiTopicAdapter.setNewInstance(it.multiList)
            }

            if (it.judgeList.isNullOrEmpty()) {
                viewBinding.judgeTopicGroup.visibility = View.GONE
                viewBinding.judgeTopicNumber.visibility = View.GONE
            } else {
                viewBinding.judgeTopicGroup.visibility = View.VISIBLE
                viewBinding.judgeTopicNumber.visibility = View.VISIBLE
                viewBinding.judgeTopicScore.text = "(分值${it.examConfig.judgeSumScore})"
                if (null == firstSelectItem) {
                    firstSelectItem = it.judgeList[0]
                    viewModel.setTopicGroupInfo(TopicGroupInfo(TopicType.JUDGE, it.multiList.size))
                }
                mJudgeTopicAdapter.selectItemId = firstSelectItem!!.id
                mJudgeTopicAdapter.indexOffsite = it.radioList.size + it.multiList.size
                mJudgeTopicAdapter.setNewInstance(it.judgeList)
            }

            val topicTotal = it.radioList.size + it.multiList.size + it.judgeList.size
            firstSelectItem?.let { firstItem ->
                queryPaperQuDetail(1, topicTotal, firstItem.paperId, firstItem.quId)
            }
        }
    }

    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 TopicNumberAdapter :
    BaseQuickAdapter<ExamTopic.ElPaperQu, BaseViewHolder>(R.layout.item_topic_number) {

    var indexOffsite = 0

    var selectItemId: String? = null

    @SuppressLint("SetTextI18n")
    override fun convert(holder: BaseViewHolder, item: ExamTopic.ElPaperQu) {
        val itemView = holder.itemView as TextView
        itemView.text = "${indexOffsite + holder.adapterPosition + 1}"
        itemView.setBackgroundResource(itemBgResource(item.isRight, item.id))
    }

    private fun itemBgResource(isRight: String, id: String): Int {
        return when {
            id == selectItemId ->
                R.drawable.circle_radius_10_blue
            "1" == isRight ->
                R.drawable.circle_radius_10_blue_20p
            else ->
                R.drawable.circle_radius_10_ffdada
        }
    }

}