package com.base.scanqr.utils

import android.graphics.Bitmap
import android.graphics.Color
import com.base.scanqr.bean.EmailUIBean
import com.base.scanqr.bean.ScanBean.Companion.CREATE_TYPE_SCAN
import com.base.scanqr.bean.WifiUIBean
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.WriterException
import com.google.zxing.common.BitMatrix
import com.google.zxing.qrcode.QRCodeWriter

object QRCodeUtils {

    private val TAG = "QRCodeUtils"

//    fun generateQRCode(content: String, width: Int, height: Int): Bitmap? {
//        val writer = QRCodeWriter()
//        val hints = EnumMap<EncodeHintType, Any>(EncodeHintType::class.java)
//        hints[EncodeHintType.MARGIN] = 1 // 设置二维码边距
//        hints[EncodeHintType.ERROR_CORRECTION] = com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.L // 设置二维码的容错级别
//
//        try {
//            val bitMatrix: BitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints)
//            val w = bitMatrix.width
//            val h = bitMatrix.height
//            val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
//            for (x in 0 until w) {
//                for (y in 0 until h) {
//                    bitmap.setPixel(x, y, if (bitMatrix[x, y]) Color.BLACK else Color.WHITE)
//                }
//            }
//            return bitmap
//        } catch (e: WriterException) {
//            e.printStackTrace()
//        }
//        return null
//    }

    fun generateQRCode(content: String, width: Int, height: Int, margin: Int = 1): Bitmap? {
        val writer = QRCodeWriter()
        val hints = HashMap<EncodeHintType, Any>()
        hints[EncodeHintType.MARGIN] = margin // 设置二维码边距，默认为1
        hints[EncodeHintType.ERROR_CORRECTION] = com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.L // 设置二维码的容错级别
        hints[EncodeHintType.CHARACTER_SET] = "UTF-8" // 设置字符集为UTF-8，确保中文可以正确编码
        try {
            val bitMatrix: BitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints)
            val bitmapWidth = bitMatrix.width + margin * 2
            val bitmapHeight = bitMatrix.height + margin * 2
            val bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888)

            // 绘制带有边距的二维码
            for (x in 0 until bitMatrix.width) {
                for (y in 0 until bitMatrix.height) {
                    val nX = x + margin
                    val nY = y + margin
                    bitmap.setPixel(nX, nY, if (bitMatrix[x, y]) Color.BLACK else Color.WHITE)
                }
            }
            return bitmap
        } catch (e: WriterException) {
            e.printStackTrace()
        }
        return null
    }

    private fun getPairKeyValue(keyValue: String): Pair<String, String> {
        val split = keyValue.split(":")
        var key = ""
        kotlin.runCatching {
            key = split[0]
        }
        var value: String = ""
        kotlin.runCatching {
            value = split[1]
        }
        return Pair(key, value)
    }

    fun isWifiQR(qrCodeValue: String): Boolean {
        val flag = qrCodeValue.startsWith("WIFI:")
        if (flag) {
            return true
        }
        return false
    }

    fun createWifiBean(qrCodeValue: String): WifiUIBean {
        val startTag = "WIFI:"
        val subString = qrCodeValue.subSequence(startTag.length, qrCodeValue.length)
        LogEx.logDebug(TAG, "subString=$subString")
        val splitList = subString.split(";")
        val wifiUIBean = WifiUIBean()


        val ssidKV = splitList.find { it.startsWith("S:") } ?: ""
        wifiUIBean.ssid = getPairKeyValue(ssidKV).second

        val passWordKV = splitList.find { it.startsWith("P:") } ?: ""
        wifiUIBean.password = getPairKeyValue(passWordKV).second

        val hiddenKV = splitList.find { it.startsWith("H:") } ?: ""
        wifiUIBean.hidden = getPairKeyValue(hiddenKV).second.toBoolean()

        val securityKy = splitList.find { it.startsWith("T") }
        if (securityKy.equals("WPA/WPA2")) {
            wifiUIBean.securityId = 0
        }
        if (securityKy.equals("WEP")) {
            wifiUIBean.securityId = 1
        }
        if (securityKy.equals("")) {
            wifiUIBean.securityId = 0
        }
        return wifiUIBean
    }


    fun isEmailQR(qrCodeValue: String): Boolean {
        val flag = qrCodeValue.startsWith("MATMSG:")
        if (flag) {
            return true
        }
        return false
    }

    //MATMSG:TO:179621228@qq.com;SUB:王雷;BODY:记得记得就觉得;
    fun createEmailBean(qrCodeValue: String): EmailUIBean {
        val startTag = "MATMSG:"
        val subString = qrCodeValue.subSequence(startTag.length, qrCodeValue.length)
        LogEx.logDebug(TAG, "subString=$subString")

        val splitList = subString.split(";")
        val emailUIBean = EmailUIBean()

        val addressKV = splitList.find { it.startsWith("TO:") } ?: ""
        emailUIBean.address = getPairKeyValue(addressKV).second

        val subKV = splitList.find { it.startsWith("SUB:") } ?: ""
        emailUIBean.subject = getPairKeyValue(subKV).second

        val bodyKV = splitList.find { it.startsWith("BODY:") } ?: ""
        emailUIBean.message = getPairKeyValue(bodyKV).second

        return emailUIBean
    }
}