package com.dlc.eboard.ui.risk

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dlc.eboard.LabApp
import com.dlc.eboard.R
import com.dlc.eboard.common.CommonUtils
import com.dlc.eboard.databinding.ActivityRiskBinding
import com.dlc.eboard.ui.common.BaseCountDownActivity
import com.dlc.eboard.ui.common.HtmlFullScreenActivity
import com.dlc.eboard.ui.widget.NavViewCompat
import com.dlc.eboard.ui.widget.TitleBar
import com.rc.core.util.EscapeUnescape
import com.rc.core.util.VideoFullScreenWebChromeClient
import com.rc.core.util.WebViewHelper
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.request.HazardReq
import com.rc.httpcore.vo.response.LabHazardVo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 危险源
 *
 * @author ReiChin_
 */
open class RiskActivity :
    BaseCountDownActivity<ActivityRiskBinding>() {

    override fun createViewBinding() = ActivityRiskBinding.inflate(layoutInflater)

    override val mTitleBar: TitleBar by lazy { viewBinding.titleBar }
    override val mNavView: NavViewCompat by lazy { viewBinding.navView }

    private val mRiskAdapter by lazy { RiskAdapter() }

    private var mCurrentData: LabHazardVo? = null

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        val webViewHelper = WebViewHelper(viewBinding.webView, viewBinding.progressbar)
        webViewHelper.initWebView(webChromeClientProxy = VideoFullScreenWebChromeClient(viewBinding.videoFullScreen))
    }

    override fun initData() {
        mRiskAdapter.setOnItemClickListener { _, _, position ->
            val item = mRiskAdapter.getItem(position)
            mRiskAdapter.selectedItemId = item.id
            mRiskAdapter.notifyDataSetChanged()
            refreshDetailUI(item)
        }
        viewBinding.risk.layoutManager = LinearLayoutManager(this)
        viewBinding.risk.adapter = mRiskAdapter

        queryHazardList()
    }

    private fun queryHazardList() {
        if (null == LabApp.sLabConfig) {
            showToast("暂无实验室信息，即将重新获取")
            CommonUtils.restartApp(this)
            return
        }

        showLoading("加载中...")
        val param = HazardReq().apply {
            subId = LabApp.sLabConfig!!.labId
            pageNum = 1
            pageSize = 50
        }
        val disposable = ApiRepository.hazardlist(param)
            .subscribe({ data ->
                dismissLoading()
                mRiskAdapter.setNewInstance(data?.toMutableList())
                if (data.isNullOrEmpty()) {
                    mRiskAdapter.setEmptyView(R.layout.view_list_empty)
                    viewBinding.qrGroup.visibility = View.INVISIBLE
                } else {
                    viewBinding.qrGroup.visibility = View.VISIBLE
                    // 默认显示第0条数据
                    mRiskAdapter.selectedItemId = data[0].id
                    refreshDetailUI(data[0])
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
                mRiskAdapter.setEmptyView(R.layout.view_list_empty)
                viewBinding.qrGroup.visibility = View.INVISIBLE
            })
        addDisposable(disposable)
    }

    private fun refreshDetailUI(data: LabHazardVo?) {
        this.mCurrentData = data
        data?.let {
            // 文件内容
            if (!data.content.isNullOrEmpty()) {
                val html = StringBuilder()
                html.append("<HTML><HEAD><LINK href=\"simple_table.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>")
                html.append(EscapeUnescape.unescape(data.content))
                html.append("</body></HTML>")

                viewBinding.webView.loadDataWithBaseURL(
                    "file:///android_asset/",
                    html.toString(),
                    "text/html",
                    "utf-8",
                    null
                )
            }

            // 二维码
            GlobalScope.launch(Dispatchers.Main) {
                val bitmap = withContext(Dispatchers.IO) {
                    QRCodeEncoder.syncEncodeQRCode(
                        data.qrCodeUrl,
                        BGAQRCodeUtil.dp2px(this@RiskActivity, 150f)
                    )
                }
                Glide.with(this@RiskActivity)
                    .asBitmap()
                    .load(bitmap)
                    .error(R.mipmap.img_error)
                    .into(viewBinding.qrCode)
            }
        }
    }

    override fun initListener() {
        viewBinding.fullScreen.setOnClickListener {
            // 全屏
            mCurrentData?.let { data ->
                // 进入全屏画面
                val intent = Intent(this, HtmlFullScreenActivity::class.java).apply {
                    putExtra("html_content", data.content)
                    putExtra("onEboard", onEboard())
                    putExtra("name", data.chName)
                }
                startActivity(intent)
            }
        }
    }

    protected open fun onEboard() = true

    override fun enabledBackCountDown() = true

    override fun enabledLogoutCountDown() = true

}

/**
 * 危险源列表
 */
private class RiskAdapter :
    BaseQuickAdapter<LabHazardVo, BaseViewHolder>(R.layout.item_risk){

    var selectedItemId: String? = null

    override fun convert(holder: BaseViewHolder, item: LabHazardVo) {
        val textView = (holder.itemView as TextView)
        textView.text = "${item.code ?: ""} ${item.chName ?: ""}"
        textView.setBackgroundResource(
            if (selectedItemId == item.id)
                R.drawable.bg_item_checked else R.drawable.bg_item_normal
        )
    }

}