package com.dlc.exam.ui.exam

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
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.ActivityMockExamBinding
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.rc.httpcore.HttpClient
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.request.MockTestReq
import com.rc.httpcore.vo.response.MockTestVo
import com.rc.httpcore.vo.response.TopicClassifyVo
import io.reactivex.disposables.Disposable

/**
 * 模拟考试
 *
 * @author ReiChin_
 */
class MockExamActivity :
    CommonListActivity<MockTestVo, ActivityMockExamBinding>(MockExamAdapter()),
    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 val mMockExamTypeAdapter by lazy { MockExamTypeAdapter() }

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

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

        mMockExamTypeAdapter.setOnItemClickListener { _, _, position ->
            val item = mMockExamTypeAdapter.getItem(position)
            mMockExamTypeAdapter.selectedItemId = item.id
            mMockExamTypeAdapter.notifyDataSetChanged()

            mCurrentPage = ListPageView.FIRST_PAGE
            loadData()
        }
        viewBinding.mockExamType.layoutManager = LinearLayoutManager(this)
        viewBinding.mockExamType.adapter = mMockExamTypeAdapter
    }

    override fun initData() {
        super.initData()

        // 查询模拟考试类型
        queryMockExamType()
    }

    private fun queryMockExamType() {
        showLoading("加载中...")
        val disposable = ApiRepository.classifyQueryOption()
            .subscribe({ data ->
                dismissLoading()
                val newlyData = data?.toMutableList() ?: mutableListOf()
                newlyData.add(0, TopicClassifyVo().apply {
                    id = ""
                    title = "全部"
                })

                mMockExamTypeAdapter.setNewInstance(newlyData)
                // 默认显示第0条数据
                mMockExamTypeAdapter.selectedItemId = newlyData[0].id
                mCurrentPage = ListPageView.FIRST_PAGE
                loadData(true)
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
                mMockExamTypeAdapter.setEmptyView(com.rc.core.R.layout.view_list_empty)
            })
        addDisposable(disposable)
    }

    override fun autoLoadData() = false

    override fun queryData(): Disposable? {
        showLoading("查询中...")
        val param = MockTestReq().apply {
            classifyIds = mMockExamTypeAdapter.selectedItemId
            pageNum = mCurrentPage
            pageSize = ListPageView.PAGE_SIZE
        }
        return ApiRepository.onlineList(param)
            .subscribe({
                dismissLoading()
                dispatchLoadDataSuccess(it.rows, it.total)
            }, { throwable ->
                dismissLoading()
                dispatchLoadDataFailure(throwable)
            })
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        // 立即考试
        val item = mAdapter.getItem(position)
        val intent = Intent(this, ExamActivity::class.java)
        intent.putExtra("exam_type", ExamType.MOCK_TEST.type)
        intent.putExtra("examId", item.id)
        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 MockExamTypeAdapter :
    BaseQuickAdapter<TopicClassifyVo, BaseViewHolder>(R.layout.item_exam_type) {

    var selectedItemId: String? = null

    override fun convert(holder: BaseViewHolder, item: TopicClassifyVo) {
        val textView = (holder.itemView as TextView)
        textView.text = item.title
        textView.setBackgroundResource(
            if (selectedItemId == item.id)
                R.drawable.bg_item_checked else R.drawable.bg_item_normal
        )
        val textColor = Color.parseColor(if (selectedItemId == item.id) "#349CFB" else "#333333")
        textView.setTextColor(textColor)
    }

}

private class MockExamAdapter : PageQuickAdapter<MockTestVo>(R.layout.item_mock_exam) {

    override fun convert(holder: BaseViewHolder, item: MockTestVo) {
        val pagePosition = pageOffsite + holder.adapterPosition + 1
        holder.setText(R.id.number, "$pagePosition")
            .setText(R.id.title, item.title)
            .setText(R.id.classifyNames, item.classifyNames)
            .setText(R.id.totalScore, item.totalScore)
            .setText(R.id.qualifyScore, item.qualifyScore)
    }

}