package com.dlc.exam.ui.score

import android.content.Intent
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
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.CommonUtils
import com.dlc.exam.common.ExamType
import com.dlc.exam.databinding.ActivityQueryScoreBinding
import com.dlc.exam.ui.certificate.CertificatePhotoDialog
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.ExamScoreReq
import com.rc.httpcore.vo.response.ExamTopic
import io.reactivex.disposables.Disposable

/**
 * 成绩查询
 *
 * @author ReiChin_
 */
class QueryScoreActivity :
    CommonListActivity<ExamTopic, ActivityQueryScoreBinding>(QueryScoreAdapter()),
    TitleBar.TitleListener {

    init {
        mAdapter.addChildClickViewIds(R.id.certificate, R.id.detail)
    }

    override val mSrlRefresh by lazy { viewBinding.swipeRefreshLayout }
    override val mRvContent by lazy { viewBinding.content }
    override val mListPageView by lazy { viewBinding.pageInfo }

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

    override fun initListener() {
        super.initListener()
        viewBinding.titleBar.setTitleListener(this)
        viewBinding.titleBar.setUsername(ExamApp.sLearnLoginVo?.nickName)

        // 模拟考试
        viewBinding.mockTest.setOnClickListener {
            mCurrentPage = ListPageView.FIRST_PAGE
            loadData()
        }
        // 安全准入考试
        viewBinding.safetyExam.setOnClickListener {
            mCurrentPage = ListPageView.FIRST_PAGE
            loadData()
        }
        // 负面清单考试
        viewBinding.negativeExam.setOnClickListener {
            mCurrentPage = ListPageView.FIRST_PAGE
            loadData()
        }
        // 黑名单考试
        viewBinding.blackListExam.setOnClickListener {
            mCurrentPage = ListPageView.FIRST_PAGE
            loadData()
        }
    }

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

    private fun parseScopeTypeParam(): String? {
        return when {
            // 模拟考试
            viewBinding.mockTest.isChecked -> ExamType.MOCK_TEST.type
            // 安全准入考试
            viewBinding.safetyExam.isChecked -> ExamType.SAFETY.type
            // 负面清单考试
            viewBinding.negativeExam.isChecked -> ExamType.NEGATIVE.type
            // 黑名单考试
            viewBinding.blackListExam.isChecked -> ExamType.BLACK_LIST.type
            else -> null
        }
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = mAdapter.getItem(position)
        when (view.id) {
            R.id.certificate -> {
                // 证书
                val url = "https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF"
                CertificatePhotoDialog(this, /*item.url*/url).show()
            }
            R.id.detail -> {
                // 详情
                val intent = Intent(this, ExamScoreDetailActivity::class.java)
                intent.putExtra("paperId", item.id)
                intent.putExtra("scopeType", ExamType.decodeDescByType(item.scopeType ?: ""))
                startActivity(intent)
            }
        }
    }

    override fun onHomeViewClicked(view: View) {
        finish()
    }

    override fun onLogoutViewClicked(view: View) {
        callLogoutApi {
            showToast("已退出登录")

            ExamApp.sLearnLoginVo = null
            HttpClient.token = null
            finish()
        }
    }

    override fun onBackViewClicked(view: View) {
        finish()
    }

    override fun onUserViewClicked(view: View) {
        startActivity(Intent(this, PersonalCenterActivity::class.java))
    }

}

private class QueryScoreAdapter : PageQuickAdapter<ExamTopic>(R.layout.item_query_score) {

    override fun convert(holder: BaseViewHolder, item: ExamTopic) {
        val pagePosition = pageOffsite + holder.adapterPosition + 1
        holder.setText(R.id.number, "$pagePosition")
            .setText(R.id.title, item.title)
            .setText(R.id.scopeType, ExamType.decodeDescByType(item.scopeType ?: ""))
            .setText(R.id.classifyNames, item.classifyNames)
            .setText(R.id.createTime, item.createTime)
            .setText(R.id.userScore, item.userScore)

        val isPass = isPass(item.userScore, item.qualifyScore)
        holder.setText(R.id.isPass, if (isPass) "合格" else "不合格")
            .setTextColor(R.id.isPass, Color.parseColor(if (isPass) "#2EAC2B" else "#FB3434"))
//            .setVisible(R.id.certificate, isPass)
            .setGone(R.id.certificate, true)
    }

    /**
     * 是否合格
     *
     * @param userScore 用户得分
     * @param qualifyScore 及格分
     */
    private fun isPass(userScore: String, qualifyScore: String): Boolean {
        return CommonUtils.stringParseInt(userScore) >= CommonUtils.stringParseInt(qualifyScore)
    }

}