package com.base.scanqrclear.qr

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.activity.addCallback
import androidx.core.view.isVisible
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.FacebookUIBean
import com.base.scanqrclear.bean.FacebookUIBean.Companion.createFacebookQrString
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_FACEBOOK
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_FOOD
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_INSTAGRAM
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_PAYPAL
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_SPOTIFY
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_WHATSAPP
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_X
import com.base.scanqrclear.bean.FunctionUIBean.Companion.KEY_YOUTUBE
import com.base.scanqrclear.bean.InstagramUIBean
import com.base.scanqrclear.bean.InstagramUIBean.Companion.createInstagramQrString
import com.base.scanqrclear.bean.OpenFoodBean
import com.base.scanqrclear.bean.PaypalUIBean
import com.base.scanqrclear.bean.PaypalUIBean.Companion.createPaypalQrString
import com.base.scanqrclear.bean.ScanBean
import com.base.scanqrclear.bean.SpotifyUIBean
import com.base.scanqrclear.bean.SpotifyUIBean.Companion.createSpotifyQrString
import com.base.scanqrclear.bean.WhatsappUIBean
import com.base.scanqrclear.bean.WhatsappUIBean.Companion.createWhatsappQrString
import com.base.scanqrclear.bean.XUIBean
import com.base.scanqrclear.bean.XUIBean.Companion.createXUIBeanQrString
import com.base.scanqrclear.bean.YoutubeUIBean
import com.base.scanqrclear.bean.YoutubeUIBean.Companion.createYoutubeQrString
import com.base.scanqrclear.databinding.ActivityQrResultsBinding
import com.base.scanqrclear.utils.BarUtils
import com.base.scanqrclear.utils.BitmapUtils.saveBitmapToFile
import com.base.scanqrclear.utils.KotlinExt.toFormatTime6
import com.base.scanqrclear.utils.LogEx
import com.base.scanqrclear.ui.widget.OpenFoodDialog.showOpenFoodDialog
import com.base.scanqrclear.utils.QRCodeUtils.generateEAN13Barcode
import com.base.scanqrclear.utils.QRCodeUtils.generateEAN8Barcode
import com.base.scanqrclear.utils.QRCodeUtils.generateQRCode
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.gyf.immersionbar.ktx.immersionBar
import java.io.File

class QrResultsActivity : BaseActivity<ActivityQrResultsBinding>(ActivityQrResultsBinding::inflate) {

    private var bean: ScanBean? = null
    private var scanType: String = ""
    private var qrString = ""
    private var tempImagePath: String = ""
    private var qrTitle: String = ""

    @SuppressLint("SetTextI18n")
    override fun initView() {
        super.initView()

        binding.root.updatePadding(top = BarUtils.getStatusBarHeight())

        scanType = intent.extras?.getString("scanType", "") ?: ""

        val data = intent.extras?.getString("data") ?: ""

        when (scanType) {
            KEY_FOOD -> {
                bean = Gson().fromJson(data, OpenFoodBean::class.java)
                qrString = (bean as OpenFoodBean).qrString
                binding.cardFood.visibility = View.VISIBLE
                binding.llOperation2.visibility = View.GONE
                binding.flAd.visibility = View.VISIBLE
                binding.flAd2.visibility = View.INVISIBLE
                Glide.with(this).load((bean as OpenFoodBean).image_front_url).into(binding.ivFood)
                binding.tvFoodName.text = (bean as OpenFoodBean).product_name
                qrTitle = "Barcode:"
                createNormalContent()

                generateEAN()
            }

            KEY_YOUTUBE -> {
                bean = Gson().fromJson(data, YoutubeUIBean::class.java)
                qrString = (bean as YoutubeUIBean).createYoutubeQrString()
                binding.ivQrIcon.setImageResource(R.mipmap.h_youtube)
                binding.tvQrTypeTitle.text = "Youtube"
                qrTitle = "Content:"
                createNormalContent()
                generateQR()
            }

            KEY_WHATSAPP -> {
                bean = Gson().fromJson(data, WhatsappUIBean::class.java)
                qrString = (bean as WhatsappUIBean).createWhatsappQrString()
                binding.ivQrIcon.setImageResource(R.mipmap.h_whatsapp)
                binding.tvQrTypeTitle.text = "Whatsapp"
                qrTitle = "Phone number:"
                createNormalContent()
                generateQR()
            }

            KEY_FACEBOOK -> {
                bean = Gson().fromJson(data, FacebookUIBean::class.java)
                qrString = (bean as FacebookUIBean).createFacebookQrString()
                binding.ivQrIcon.setImageResource(R.mipmap.h_facebook)
                binding.tvQrTypeTitle.text = "Facebook"
                qrTitle = "Content:"
                createNormalContent()
                generateQR()
            }

            KEY_INSTAGRAM -> {
                bean = Gson().fromJson(data, InstagramUIBean::class.java)
                qrString = (bean as InstagramUIBean).createInstagramQrString()
                binding.ivQrIcon.setImageResource(R.mipmap.h_instagram)
                binding.tvQrTypeTitle.text = "Instagram"
                qrTitle = "Content:"
                createNormalContent()
                generateQR()
            }

            KEY_X -> {
                bean = Gson().fromJson(data, XUIBean::class.java)
                qrString = (bean as XUIBean).createXUIBeanQrString()
                binding.ivQrIcon.setImageResource(R.mipmap.h_x)
                binding.tvQrTypeTitle.text = "X"
                qrTitle = "Content:"
                createNormalContent()
                generateQR()
            }

            KEY_PAYPAL -> {
                bean = Gson().fromJson(data, PaypalUIBean::class.java)
                qrString = (bean as PaypalUIBean).createPaypalQrString()
                binding.ivQrIcon.setImageResource(R.mipmap.h_paypal)
                binding.tvQrTypeTitle.text = "Paypal"
                qrTitle = "Content:"
                createNormalContent()
                generateQR()
            }

            KEY_SPOTIFY -> {
                bean = Gson().fromJson(data, SpotifyUIBean::class.java)
                qrString = (bean as SpotifyUIBean).createSpotifyQrString()
                binding.ivQrIcon.setImageResource(R.mipmap.h_spotify)
                binding.tvQrTypeTitle.text = "Spotify"

                val ss = SpannableStringBuilder("Singer Name:${(bean as SpotifyUIBean).singerName}")

                ss.setSpan(
                    ForegroundColorSpan(Color.parseColor("#666666")),
                    0, // 开始位置
                    "Singer Name:".length, // 结束位置
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE
                )

                ss.setSpan(
                    ForegroundColorSpan(Color.BLACK), // 设置颜色为黑色
                    "Singer Name:".length, // 开始位置
                    ss.length, // 结束位置
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE
                )

                binding.tvQrContent.text = ss

                binding.tvQrContent.append("\n")

                val ss2 = SpannableStringBuilder("Song:${(bean as SpotifyUIBean).song}")

                ss2.setSpan(
                    ForegroundColorSpan(Color.parseColor("#666666")),
                    0, // 开始位置
                    "Song:".length, // 结束位置
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE
                )

                ss2.setSpan(
                    ForegroundColorSpan(Color.BLACK), // 设置颜色为黑色
                    "Song:".length, // 开始位置
                    ss2.length, // 结束位置
                    Spanned.SPAN_INCLUSIVE_INCLUSIVE
                )

                binding.tvQrContent.append(ss2)

                generateQR()

            }
        }
        binding.tvTime.text = System.currentTimeMillis().toFormatTime6()


        if (binding.flAd.isVisible) {
            AdsMgr.showNative(binding.flAd, R.layout.layout_admob_item)
        }
        if (binding.flAd2.isVisible) {
            AdsMgr.showNative(binding.flAd2, R.layout.layout_admob_item)
        }
    }

    private fun generateEAN() {
        Thread {
            var bitmap: Bitmap? = null
            if (qrString.length == 12 || qrString.length == 13) {
                bitmap = generateEAN13Barcode(qrString, 555, 555)
            }
            if (qrString.length == 8) {
                bitmap = generateEAN8Barcode(qrString, 555, 555)
            }
            runOnUiThread {
                binding.ivQr.setImageBitmap(bitmap)
                val file = File(cacheDir, System.currentTimeMillis().toString() + ".jpg")
                bitmap?.let {
                    val flag = saveBitmapToFile(it, file.absolutePath)
                    LogEx.logDebug(TAG, "flag=$flag tempImage=${file.absolutePath}")
                    if (flag) {
                        tempImagePath = file.absolutePath
                    }
                }
            }
        }.start()
    }

    private fun generateQR() {
        Thread {
            LogEx.logDebug(TAG, "messageQrString=$qrString")
            val bitmap = generateQRCode(qrString, 735, 735, 2)
            runOnUiThread {
                binding.ivQr.setImageBitmap(bitmap)
                val file = File(cacheDir, System.currentTimeMillis().toString() + ".jpg")
                bitmap?.let {
                    val flag = saveBitmapToFile(it, file.absolutePath)
                    LogEx.logDebug(TAG, "flag=$flag tempImage=${file.absolutePath}")
                    if (flag) {
                        tempImagePath = file.absolutePath
                    }
                }
            }
        }.start()
    }

    private fun createNormalContent() {
        val ss = SpannableStringBuilder("$qrTitle$qrString")

        ss.setSpan(
            ForegroundColorSpan(Color.parseColor("#666666")), // 设置颜色为红色
            0, // 开始位置
            qrTitle.length, // 结束位置
            Spanned.SPAN_INCLUSIVE_INCLUSIVE
        )

        ss.setSpan(
            ForegroundColorSpan(Color.BLACK), // 设置颜色为黑色
            qrTitle.length, // 开始位置
            ss.length, // 结束位置
            Spanned.SPAN_INCLUSIVE_INCLUSIVE
        )

        binding.tvQrContent.text = ss
    }

    @SuppressLint("SetTextI18n")
    override fun initListener() {
        super.initListener()

        onBackPressedDispatcher.addCallback {
            finishToMainTop()
        }
        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        binding.tvSeeMore.setOnClickListener {
            showOpenFoodDialog(bean as OpenFoodBean)
        }
    }

    override fun configSystemBar() {

        immersionBar {
            statusBarColor("#FFFFFFFF")
            statusBarDarkFont(false)
        }
    }


}