package com.dlc.eboard.ui.rule

import android.os.Bundle
import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder
import com.bumptech.glide.Glide
import com.dlc.eboard.R
import com.dlc.eboard.databinding.ActivitySafetyRegulationDetailBinding
import com.dlc.eboard.ui.common.BaseCountDownActivity
import com.dlc.eboard.ui.widget.NavViewCompat
import com.dlc.eboard.ui.widget.TitleBar
import com.rc.core.log.RcLog
import com.rc.core.ui.ActivityCollector
import com.rc.httpcore.net.DownloadListener
import com.rc.httpcore.net.DownloadTask
import com.rc.httpcore.vo.response.SafeBook
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

/**
 * 规章制度-详情
 *
 * @author ReiChin_
 */
class SafetyRegulationDetailActivity :
    BaseCountDownActivity<ActivitySafetyRegulationDetailBinding>() {

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

    override val mTitleBar: TitleBar? = null
    override val mNavView: NavViewCompat? = null

    private var mData: SafeBook? = null
    private var onEboard: Boolean = false

    override fun initViews(savedInstanceState: Bundle?) {
        mData = intent.getSerializableExtra("data") as SafeBook?
        if (null == mData) finish()
        onEboard = intent.getBooleanExtra("onEboard", false)

        viewBinding.homeLayout.setOnClickListener {
            if (onEboard) {
                logoutCountDownFinish()
            } else {
                ActivityCollector.removeActivity(2)
            }
        }
        viewBinding.backLayout.setOnClickListener { finish() }
    }

    override fun initData() {
        mData?.let { data ->
            viewBinding.titleText.text = data.name

            // 文件内容
            if (!data.content.isNullOrEmpty()) {
                downloadPDF(data.content)
            }

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

    private fun downloadPDF(downloadUrl: String) {
        showLoading("加载中...")
        val fileName = "pdf_safe_book.pdf"
        val pdfFile = File(cacheDir, fileName)
        if (pdfFile.exists()) {
            pdfFile.delete()
        }
        val downloadTask = DownloadTask(
            listener = object : DownloadListener {
                override fun onProgress(progress: Int) {
                    RcLog.info("download pdf, progress:$progress")
                }

                override fun onSuccess() {
                    dismissLoading()
                    viewBinding.pdfview.fromFile(pdfFile)
                        .defaultPage(1)
                        .showMinimap(false)
                        .swipeVertical(true)
                        .enableSwipe(true)
                        .load()
                }

                override fun onFailed(errMsg: String?) {
                    dismissLoading()
                    errMsg?.let { showToast(it) }
                }

                override fun onPaused() {
                }

                override fun onCanceled() {
                }

            },
            dlPath = cacheDir.path,
            fileName = fileName,
            headers = mapOf("Accept-Encoding" to "identity")
        )
        downloadTask.execute(downloadUrl)
    }

    override fun enabledBackCountDown() = true

    override fun refreshBackCountDownView(countDown: Int) {
        viewBinding.countDown.text = "(${countDown}s)"
    }

}