package xn.hxp.ui.still

import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewbinding.ViewBinding
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.king.zxing.util.CodeUtils
import xn.hxp.databinding.ActivityMsdsBinding
import xn.hxp.ui.adapter.MsdsListAdapter
import xn.hxp.utils.TimeUpdater
import xn.hxp.utils.UiManager
import com.blankj.utilcode.util.LogUtils
import com.rc.core.ui.activity.BaseActivity
import com.rc.core.util.EscapeUnescape
import com.rc.core.util.VideoFullScreenWebChromeClient
import com.rc.core.util.WebViewHelper
import com.rc.httpcore.HttpClient
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.client.ApiRepository
import xn.hxp.app.ChemicalApp
import java.net.URLEncoder

//MSDS
class MsdsActivity : BaseActivity() {

    private lateinit var timeUpdater: TimeUpdater
    private val mAdapter by lazy { MsdsListAdapter(this) }
    private var mId: String? = null  //生成id  用于第二个页面
    private var mCont: String? = null  //文件地址
    private var mName: String? = null //文件名称

    lateinit var viewBinding: ActivityMsdsBinding
    override fun setViewBinding(): ViewBinding {
        viewBinding = ActivityMsdsBinding.inflate(layoutInflater)
        return viewBinding
    }

    override fun onInit() {
        viewBinding.rvView?.layoutManager = LinearLayoutManager(this)
        viewBinding.rvView?.adapter = mAdapter
        viewBinding.tvReturn.text = "返回${ChemicalApp.confs!!.backTime}s"

        msdsDetails(null)

        viewBinding.screen.setOnClickListener {
            if (mCont!!.isEmpty()) {
                showToast("文件地址不能为空")
                return@setOnClickListener
            }
            //全屏
            var map = mutableMapOf<String, String>()
            map["mCont"] = mCont!!
            map["mName"] = mName!!
            map["mId"] = mId!!
            UiManager.switcher(this, map, MsdsScreenActivity::class.java)
        }

        viewBinding.butSearch.setOnClickListener {
            val trim = viewBinding.searchValue.text.toString().trim()
            if (trim.isNotEmpty()) {
                msdsDetails(trim)
            } else {
                msdsDetails(null)
            }
        }
        viewBinding.tvReturn.setOnClickListener {
            finish()
        }
        val handler = Handler(Looper.getMainLooper())
        timeUpdater = TimeUpdater(handler) { currentTime ->
            viewBinding.nowTime.text = "$currentTime"
        }
        // 启动定时更新
        timeUpdater.startUpdating()

        // 使用 Glide 加载网络图片
        viewBinding.deptName.text = "${ChemicalApp.confs!!.deptName}-${ChemicalApp.confs!!.roomNum}"
        Glide.with(this)
            .load("${HttpConfig.API_BASE_IMG_URL}${ChemicalApp.confs!!.circularLogo}")
            .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
            .into(viewBinding.image)

        val webViewHelper = WebViewHelper(viewBinding.webView, viewBinding.progressbar)
        webViewHelper.initWebView(
            webChromeClientProxy = VideoFullScreenWebChromeClient(
                viewBinding.videoFullScreen
            )
        )
        mAdapter.setOnItemClickListener { adapter, view, position ->
            mAdapter.data.forEach { it.isType = false }
            mAdapter.data[position].isType = true
            mAdapter.notifyDataSetChanged()
            if (mAdapter.data[position].content != null) {
                mCont = mAdapter.data[position].content
                mName = mAdapter.data[position].name
                val webViewHelper = WebViewHelper(viewBinding.webView, viewBinding.progressbar)
                webViewHelper.initWebView(
                    webChromeClientProxy = VideoFullScreenWebChromeClient(
                        viewBinding.videoFullScreen
                    )
                )

                viewBinding.webView.loadDataWithBaseURL(
                    null,
                    EscapeUnescape.unescape("$mCont"),
                    "text/html",
                    "utf-8",
                    null
                )
                mId = mAdapter.data[position].id
                LogUtils.i("当前文档地址:${HttpConfig.API_BASE_QC_URL}?code=${mAdapter.data[position].id}&type=1")
//                if (mCode != null) {
                //二维码需要改动  拉取公用配置
                val qrCode: Bitmap = CodeUtils.createQRCode(
                    "https://labcontrol.nwafu.edu.cn/api/?code=$mId&type=1",
                    200,
                    null
                )
                viewBinding.imgSign.setImageBitmap(qrCode)
//                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            timeUpdater.stopUpdating()
        } catch (e: Exception) {
        }
    }

    override fun cdFinish() {
        finish()
    }

    override fun onBackPressed() {
        super.onBackPressed()
        finish()
    }

    override fun cdTime(cd: Int) {
        viewBinding.tvReturn.text = "返回${cd}s"
    }

    //msdsDetails
    private fun msdsDetails(searchValue: String?) {
        showLoading("查询中...")
        val disposable =
            ApiRepository.getMsdsDetails(searchValue)
                .subscribe({ data ->
                    dismissLoading()
                    LogUtils.i("===1====数据成功")
                    data.records[0].isType = true
                    mAdapter.setNewInstance(data.records.toMutableList())
                    mCont = mAdapter.data[0].content
                    mName = mAdapter.data[0].name
                    mId = mAdapter.data[0].id
                    //二维码需要改动  拉取公用配置
                    val qrCode: Bitmap = CodeUtils.createQRCode(
                        "https://labcontrol.nwafu.edu.cn/api/?code=${mAdapter.data[0].id}&type=1",
                        200,
                        null
                    )
                    LogUtils.i("当前文档初始化地址:${HttpConfig.API_BASE_QC_URL}?code=${mAdapter.data[0].id}&type=1")
                    viewBinding.imgSign.setImageBitmap(qrCode)

                    val html = StringBuilder()
                    html.append("<HTML><HEAD><LINK href=\"simple_table.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>")
                    html.append(EscapeUnescape.unescape(mCont))
                    html.append("</body></HTML>")

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

                }, { throwable ->
                    dismissLoading()
                    LogUtils.i("===1====数据失败")
                    showNetError(throwable)

                })
        addDisposable(disposable)
    }


}