package com.dlc.laboratory.ui.safety

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
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.FragmentSafetyRegulationDetailBinding
import com.rc.core.log.RcLog
import com.rc.core.ui.fragment.RcBaseFragment
import com.rc.core.util.ScreenAdapter
import com.rc.httpcore.client.ApiRepository
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 SafetyRegulationDetailFragment : RcBaseFragment<FragmentSafetyRegulationDetailBinding>() {

    companion object {

        const val TAG = "SafetyRegulationDetailFragment"
    }

    override fun onResume() {
        super.onResume()
        ScreenAdapter.setCustomDensity(requireActivity())
    }

    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ) = FragmentSafetyRegulationDetailBinding.inflate(inflater, container, false)

    override fun initViews(savedInstanceState: Bundle?) {
        val data = arguments?.getSerializable("data") as? SafeBook
        if (null != data) {
            refreshUI(data)
        } else {
            val id = arguments?.getString("id") ?: ""
            querySafeBookDetail(id)
        }
    }

    private fun querySafeBookDetail(id: String) {
        showLoading("加载中...")
        val disposable = ApiRepository.safeBookDetail(id)
            .subscribe({ data ->
                dismissLoading()
                refreshUI(data)
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    private fun refreshUI(data: SafeBook?) {
        data?.let {
            // 文件内容
            if (!data.content.isNullOrEmpty()) {
                downloadPDF(data.content)
            }

            // 二维码
            GlobalScope.launch(Dispatchers.Main) {
                val bitmap = withContext(Dispatchers.IO) {
                    QRCodeEncoder.syncEncodeQRCode(
                        data.qrCodeUrl,
                        BGAQRCodeUtil.dp2px(requireContext(), 150f)
                    )
                }
                Glide.with(requireContext())
                    .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(requireContext().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 = requireContext().cacheDir.path,
            fileName = fileName,
            headers = mapOf("Accept-Encoding" to "identity")
        )
        downloadTask.execute(downloadUrl)
    }

}