package com.dlc.eboard.ui.msds

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
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.R
import com.dlc.eboard.databinding.ActivityInstructionBinding
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.WebViewHelper
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.vo.response.HazardBook
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * MSDS
 *
 * @author ReiChin_
 */
open class InstructionActivity :
    BaseCountDownActivity<ActivityInstructionBinding>() {

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

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

    private val mInstructionAdapter by lazy { InstructionAdapter() }

    private var mCurrentData: HazardBook? = null

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

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

        showLoading("加载中...")
        val disposable = ApiRepository.hazardBookList()
            .subscribe({ data ->
                dismissLoading()
                mInstructionAdapter.setNewInstance(data?.toMutableList())
                if (data.isNullOrEmpty()) {
                    mInstructionAdapter.setEmptyView(R.layout.view_list_empty)
                } else {
                    // 默认显示第0条数据
                    mInstructionAdapter.selectedItemId = data[0].id
                    showHazardBookDetail(data[0].id)
//                    refreshDetailUI(data[0])

                    // 处理AutoCompleteTextView
                    val adapter = AutoCompleteAdapter(data.toMutableList())
                    viewBinding.sdmsInput.setAdapter(adapter)
                    viewBinding.sdmsInput.setOnItemClickListener { _, _, position, _ ->
                        val item = adapter.visibilityData[position]
                        // TODO ReiChin_ 移动RecycleView的位置
                        mInstructionAdapter.selectedItemId = item.id
                        mInstructionAdapter.notifyDataSetChanged()
                        showHazardBookDetail(item.id)
//                        refreshDetailUI(item)
                    }
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
                mInstructionAdapter.setEmptyView(R.layout.view_list_empty)
            })
        addDisposable(disposable)
    }

    private fun showHazardBookDetail(id: String?) {
        showLoading("查询中...")
        val disposable = ApiRepository.hazardBookDetail(id ?: "")
            .subscribe({ data ->
                dismissLoading()
                refreshDetailUI(data)
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    private fun refreshDetailUI(data: HazardBook?) {
        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@InstructionActivity, 150f)
                    )
                }
                Glide.with(this@InstructionActivity)
                    .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.name)
                }
                startActivity(intent)
            }
        }
    }

    protected open fun onEboard() = true

    override fun enabledBackCountDown() = true

    override fun enabledLogoutCountDown() = true

}

private class InstructionAdapter :
    BaseQuickAdapter<HazardBook, BaseViewHolder>(R.layout.item_instruction) {

    var selectedItemId: String? = null

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

}

private class AutoCompleteAdapter(data: MutableList<HazardBook>? = null) :
    BaseAdapter(), Filterable {

    private var originalData: MutableList<HazardBook> = data ?: arrayListOf()

    var visibilityData: MutableList<HazardBook>

    init {
        visibilityData = mutableListOf<HazardBook>().apply { addAll(originalData) }
    }

    override fun getCount() = visibilityData.size

    override fun getItem(position: Int) = visibilityData[position]

    override fun getItemId(position: Int) = position.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val tempView: View
        val holder = if (null == convertView) {
            tempView = LayoutInflater.from(parent!!.context)
                .inflate(R.layout.item_auto_complete_drop_down, parent, false)
            ViewHolder(tempView.findViewById(R.id.text1)).apply {
                tempView.tag = this
            }
        } else {
            tempView = convertView
            convertView.tag as ViewHolder
        }

        val itemData = getItem(position)
        holder.item.text = itemData.name

        return tempView
    }

    private class ViewHolder(val item: TextView)

    private var mFilter: Filter? = null

    override fun getFilter(): Filter {
        if (null == mFilter)
            mFilter = InstructionFilter()
        return mFilter!!
    }

    private val mLock = Any()

    inner class InstructionFilter : Filter() {

        override fun performFiltering(prefix: CharSequence?): FilterResults {
            val results = FilterResults()

            if (prefix.isNullOrEmpty()) {
                val list: MutableList<HazardBook>
                synchronized(mLock) {
                    list = mutableListOf<HazardBook>().apply { addAll(originalData) }
                }
                results.values = list
                results.count = list.size
            } else {
                val fPrefix = prefix.toString().toLowerCase()

                val newlyData = originalData.filter {
                    val fName = it.name?.toLowerCase()
                    val fPinYinChar = it.pinYinChar?.toLowerCase()
                    fName?.contains(fPrefix) ?: false || fPinYinChar?.contains(fPrefix) ?: false
                }
                results.values = newlyData
                results.count = newlyData.size
            }
            return results
        }

        override fun publishResults(constraint: CharSequence?, results: FilterResults) {
            visibilityData.clear()
            visibilityData.addAll(results.values as Collection<HazardBook>)
            if (results.count > 0) {
                notifyDataSetChanged()
            } else {
                notifyDataSetInvalidated()
            }
        }
    }

}