package com.example.chemical.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 com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.example.chemical.ChemicalApp
import com.example.chemical.R
import com.example.chemical.comm.Constants
import com.example.chemical.databinding.ActivityMsdsBinding
import com.example.chemical.ui.adapter.MsdsListAdapter
import com.example.chemical.ui.common.BaseCountDownActivity
import com.example.chemical.utils.TimeUpdater
import com.example.chemical.utils.UiManager
import com.king.zxing.util.CodeUtils
import com.rc.core.log.RcLog
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 java.net.URLEncoder

//MSDS
class MsdsActivity : BaseCountDownActivity<ActivityMsdsBinding>() {

    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 //文件名称

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

    override fun initViews(savedInstanceState: Bundle?) {
        super.initViews(savedInstanceState)
        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()
        }
    }

    override fun initData() {
        super.initData()
        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
                RcLog.info("当前文档地址:${HttpConfig.API_BASE_QC_URL}?code=${mAdapter.data[position].id}&type=1")
//                if (mCode != null) {
                //二维码需要改动  拉取公用配置
                val qrCode: Bitmap = CodeUtils.createQRCode(
                    "${HttpConfig.API_BASE_QC_URL}?code=$mId&type=1",
                    200,
                    null
                )
                viewBinding.imgSign.setImageBitmap(qrCode)
//                }
            }
        }

    }

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

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

    //msdsDetails
    private fun msdsDetails(searchValue: String?) {
        showLoading("查询中...")
        val disposable =
            ApiRepository.getMsdsDetails(searchValue)
                .subscribe({ data ->
                    dismissLoading()
                    RcLog.info("===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(
                        "${HttpConfig.API_BASE_QC_URL}?code=${mAdapter.data[0].id}&type=1",
                        200,
                        null
                    )
                    RcLog.info("当前文档初始化地址:${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()
                    RcLog.info("===1====数据失败")
                    showNetError(throwable)

                })
        addDisposable(disposable)
    }


}