package com.base.scanqrclear.ui.exportpdf

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.view.Gravity
import android.widget.LinearLayout
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import com.base.scanqrclear.R
import com.base.scanqrclear.ads.AdsMgr
import com.base.scanqrclear.base.BaseActivity
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_CONTACT
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_EMAIL
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_EVENT
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_MESSAGE
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_PRODUCT
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_TELEPHONE
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_TEXT
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_WEBSITE
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_WIFI
import com.base.scanqrclear.databinding.ActivityExportPdfBinding
import com.base.scanqrclear.utils.BarUtils
import com.base.scanqrclear.utils.ExportPdf.generatePdfWithTextAndImage
import com.base.scanqrclear.utils.LogEx
import com.base.scanqrclear.utils.QRCodeUtils
import com.base.scanqrclear.utils.QRCodeUtils.generateQRCode
import com.base.scanqrclear.utils.ToastUtils.toast
import com.gyf.immersionbar.ktx.immersionBar
import java.io.File
import java.io.FileInputStream


class ExportPdfActivity : BaseActivity<ActivityExportPdfBinding>(ActivityExportPdfBinding::inflate) {

    private var qrType: String = KEY_TEXT
    private var qrString: String = ""
    private var qrStringArray: Array<String> = arrayOf()

    private var pdfQrName: String = ""
    private var pdfTempFile: File? = null

    @SuppressLint("SetTextI18n")
    override fun initView() {
        super.initView()
        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        qrType = intent.extras?.getString("qrType", "") ?: ""
        qrString = intent.extras?.getString("qrString", "") ?: ""

        AdsMgr.showBanner(binding.flBanner, false)

        when (qrType) {
            KEY_TEXT -> {
                pdfQrName = "QR_TEXT"
                binding.tvQrType.text = "QR_TEXT"
                binding.tvQr.text = qrString
                qrStringArray = arrayOf(qrString)

                generateQRCode()
            }

            KEY_WIFI -> {
                pdfQrName = "QR_WIFI"
                binding.tvQrType.text = "QR_WIFI"
                val content = qrString.replace(";", "\n")
                binding.tvQr.text = content
                qrStringArray = content.split("\n").toTypedArray()

                generateQRCode()
            }

            KEY_EMAIL -> {
                pdfQrName = "QR_EMAIL"
                binding.tvQrType.text = "QR_EMAIL"
                val content = qrString.replace(";", "\n")
                binding.tvQr.text = content
                qrStringArray = content.split("\n").toTypedArray()

                generateQRCode()
            }

            KEY_WEBSITE -> {

                pdfQrName = "QR_URL"
                binding.tvQrType.text = "QR_URL"
                binding.tvQr.text = qrString
                qrStringArray = arrayOf(qrString)

                generateQRCode()
            }

            KEY_EVENT -> {
                pdfQrName = "QR_EVENT"
                binding.tvQrType.text = "QR_EVENT"
                val content = qrString.replace(";", "\n")
                binding.tvQr.text = content
                qrStringArray = content.split("\n").toTypedArray()

                generateQRCode(0.4f, 3.0f)
            }

            KEY_CONTACT -> {
                pdfQrName = "QR_CONTACT"
                binding.tvQrType.text = "QR_CONTACT"
                binding.tvQr.text = qrString
                qrStringArray = qrString.split("\n").toTypedArray()

                generateQRCode(0.4f, 2.5f)
            }

            KEY_TELEPHONE -> {
                pdfQrName = "QR_TELEPHONE"
                binding.tvQrType.text = "QR_TELEPHONE"
                binding.tvQr.text = qrString
                qrStringArray = arrayOf(qrString)

                generateQRCode()
            }

            KEY_MESSAGE -> {
                pdfQrName = "QR_MESSAGE"
                binding.tvQrType.text = "QR_MESSAGE"
                binding.tvQr.text = qrString
                qrStringArray = arrayOf(qrString)

                generateQRCode()
            }

            KEY_PRODUCT -> {
                pdfQrName = "QR_PRODUCT"
                binding.tvQrType.text = "QR_PRODUCT"
                binding.tvQr.text = qrString
                qrStringArray = arrayOf(qrString)

                val newWidth = this.resources.getDimensionPixelSize(R.dimen.dp_260)
                val newHeight = this.resources.getDimensionPixelSize(R.dimen.dp_155)
                val layoutParams: LinearLayout.LayoutParams = LinearLayout.LayoutParams(newWidth, newHeight)
                layoutParams.gravity = Gravity.CENTER_HORIZONTAL
                binding.ivQr.setLayoutParams(layoutParams)

                generateEAN13Barcode()
            }
        }
    }


    fun generateQRCode(scale: Float = 0.5f, imageYRate: Float = 2f) {
        Thread {
            val bitmap = generateQRCode(qrString, 735, 735, 5)
            runOnUiThread { binding.ivQr.setImageBitmap(bitmap) }

            bitmap?.let { generatePdfFile(it, scale, imageYRate) }
        }.start()
    }

    fun generateEAN13Barcode() {
        Thread {
            val bitmap = QRCodeUtils.generateEAN13Barcode(qrString, 648, 255)
            runOnUiThread { binding.ivQr.setImageBitmap(bitmap) }

            bitmap?.let { generatePdfFile(it, 0.5f, 2f) }
        }.start()
    }

    fun generatePdfFile(bitmap: Bitmap, scale: Float, imageYRate: Float) {
        val tempPdf = File(this.cacheDir, "${pdfQrName}_${System.currentTimeMillis()}.pdf")
        this.cacheDir.mkdirs()
        tempPdf.createNewFile()

        val scaledBitmap = Bitmap.createScaledBitmap(
            bitmap,
            (bitmap.width * scale).toInt(),
            (bitmap.height * scale).toInt(),
            true
        )

        val flag = generatePdfWithTextAndImage(tempPdf, scaledBitmap, pdfQrName, qrStringArray, imageYRate)
        if (flag) {
            LogEx.logDebug(TAG, "${tempPdf.absoluteFile}")
            pdfTempFile = tempPdf
        }
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            finishToMainTop()
        }
        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.tvSave.setOnClickListener {
            pdfTempFile ?: return@setOnClickListener
            launcher.launch(
                Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
                    addCategory(Intent.CATEGORY_OPENABLE)
                    setType("application/pdf")
                    putExtra(Intent.EXTRA_TITLE, pdfTempFile?.name)
                }
            ) { result ->
                val uri: Uri? = result.data?.data
                uri ?: return@launch
                pdfTempFile?.let { writePdfContent(it, uri) }
            }
        }
    }

    private fun writePdfContent(file: File, uri: Uri) = Thread {

        try {
            val ips = FileInputStream(file)
            val ops = contentResolver.openOutputStream(uri)

            // 缓冲区大小
            val buffer = ByteArray(1024)
            var length: Int
            while ((ips.read(buffer).also { length = it }) > 0) {
                ops?.write(buffer, 0, length)
            }
            ips.close()
            ops?.close()
            file.delete()
            runOnUiThread {
                toast("save pdf success", true)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }.start()

    override fun configSystemBar() {
        immersionBar {
            statusBarColor("#FFFFFFFF")
            statusBarDarkFont(false)
        }

    }
}