package com.doverfuelingsolutions.testdemo.driver.lib

import android.content.ContentValues
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.media.ThumbnailUtils
import android.util.Base64
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.doverfuelingsolutions.testdemo.api.dto.DFSResult
import com.doverfuelingsolutions.testdemo.driver.printer.ComPrintManager
import com.doverfuelingsolutions.testdemo.driver.printer.PrintStatusListen
import com.doverfuelingsolutions.testdemo.driver.tools.BoardTool
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType
import com.google.zxing.MultiFormatReader
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.common.HybridBinarizer
import java.io.ByteArrayInputStream
import java.util.*
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

class PrintManager : LifecycleObserver, PrintStatusListen {

    companion object {
        var operator = ""
    }

    private lateinit var comPrintManager: ComPrintManager

    private var callback: ((success: Boolean) -> Unit)? = null
    private var boardTool: BoardTool = BoardTool()

    override fun receivePrintStatus(value: Int) {
        val success = value >= 0
        callback?.invoke(success)
        callback = null
    }


    suspend fun printQRTest() = suspendCoroutine<DFSResult<Any>> {
        val manager = this
        Thread {
            if (!manager::comPrintManager.isInitialized) {
                try {
                    val printUartPath = boardTool.printUartPath()
//                    comPrintManager = ComPrintManager("/dev/ttyS3", 115200, this) //自助机旧主板用这个
                    comPrintManager = ComPrintManager(printUartPath, 115200, this) //新主板用这个
                } catch (e: Exception) {
                    it.resume(DFSResult.fail("初始化打印机失败"))
                }
            }

            callback = { success ->
                it.resume(if (success) DFSResult.success(true) else DFSResult.fail("打印失败"))
            }

            val qrContent = decode("iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAYAAAA+s9J6AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAABJhSURBVHhe7dNBrhw5EgTRvv+le7TQ8i184A6ykE0DD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Sc0K4U6mZLONp0UTXdCse4a5hvTR6tLFetOaFYKdTIlnW06KZruhGLdNcw3po9WlyqaTqZoVgp1qeJE15iiWSnUyZRmNmW+MX20ulTRdDJFs1KoSxUnusYUzUqhTqY0synzjemj1aWKppMpmpVCXao40TWmaFYKdTKlmU2Zb0wfrS5VNJ1M0awU6lLFia4xRbNSqJMpzWzKfGP6aHWpoulkimalUJcqTnSNKZqVQp1MaWZT5hvTR6tLFU2XKtSlfgV9W+MJdDd1zXxj+mh1qaLpUoW61K+gb2s8ge6mrplvTB+tLlU0XapQl/oV9G2NJ9Dd1DXzjemj1aWKpksV6lK/gr6t8QS6m7pmvjF9tLpU0XSpQl3qV9C3NZ5Ad1PXzDeeeLRY3721L+2EZlNF2ol09kQnU5rZlPnGE48W67u39qWd0GyqSDuRzp7oZEozmzLfeOLRYn331r60E5pNFWkn0tkTnUxpZlPmG088Wqzv3tqXdkKzqSLtRDp7opMpzWzKfOOJR4v13Vv70k5oNlWknUhnT3QypZlNmW/Uo28pmk4KdVKoS21I96lrFOqkaLrUNfONevQtRdNJoU4KdakN6T51jUKdFE2Xuma+UY++pWg6KdRJoS61Id2nrlGok6LpUtfMN+rRtxRNJ4U6KdSlNqT71DUKdVI0Xeqa+UY9+pai6aRQJ4W61IZ0n7pGoU6Kpktds9/4eDz+L96P8PG4zPsRPh6XeT/Cx+My70f4eFzm/Qgfj8u8H+HjcZn3I3w8LvN+hI/HZd6P8PG4zPsRPh6XeT/Cx+My70f4eFzm/Qgfj8u8H+HjcZn3I3w8LvN+hI/HZd6P8PG4zPsRPh6XeT/Cx+Mq//77PwAuiJZjSHnPAAAAAElFTkSuQmCC")
            comPrintManager.printOrderOkBillHsQRCodeTest(qrContent)

        }.start()
    }

    fun convertToBlackWhite(bmp: Bitmap): Bitmap? {
        println(bmp.config)
        var width = bmp.width
        val height = bmp.height
        if (width > 640) {
            width = 640
        }
        //        if (height > 2000){
//            return null;
//        }
        val pixels = IntArray(width * height)
        bmp.getPixels(pixels, 0, width, 0, 0, width, height)
        val gray = IntArray(height * width)
        try {
            for (i in 0 until height) {
                for (j in 0 until width) {
                    val grey = pixels[width * i + j]
                    val red = grey and 0x00FF0000 shr 16
                    gray[width * i + j] = red
                }
            }
        } catch (e: java.lang.Exception) {
            Log.e(ContentValues.TAG, "PrintBmp:" + e.message)
        }
        var e = 0
        for (i in 0 until height) {
            for (j in 0 until width) {
                val g = gray[width * i + j]
                if (g >= 128) {
                    pixels[width * i + j] = -0x1
                    e = g - 255
                } else {
                    pixels[width * i + j] = -0x1000000
                    e = g - 0
                }
                if (j < width - 1 && i < height - 1) {
                    gray[width * i + j + 1] += 3 * e / 8
                    gray[width * (i + 1) + j] += 3 * e / 8
                    gray[width * (i + 1) + j + 1] += e / 4
                } else if (j == width - 1 && i < height - 1) {
                    gray[width * (i + 1) + j] += 3 * e / 8
                } else if (j < width - 1 && i == height - 1) {
                    gray[width * i + j + 1] += e / 4
                }
            }
        }
        val newBmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
        newBmp.setPixels(pixels, 0, width, 0, 0, width, height)
        return ThumbnailUtils.extractThumbnail(newBmp, width, height)
    }

    //解析二维码内容
    private fun decode(base64:String):String? {
        val decode = Base64.decode(base64, Base64.DEFAULT)
        val byteArrayInputStream = ByteArrayInputStream(decode)
        val bitmap = BitmapFactory.decodeStream(byteArrayInputStream)
        return decode(bitmap)
    }

    //解析二维码内容
    private fun decode(bmp: Bitmap): String? {
        val hints: Hashtable<DecodeHintType, String?> = Hashtable()
        hints[DecodeHintType.CHARACTER_SET] = "utf-8"
        return try {
            val width = bmp.width
            val height = bmp.height
            val pixels = IntArray(width * height)
            bmp.getPixels(pixels, 0, width, 0, 0, width, height)
            val source = RGBLuminanceSource(width, height, pixels)
            MultiFormatReader().decode(BinaryBitmap(HybridBinarizer(source)), hints).text
        } catch (e: java.lang.Exception) {
            ""
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private fun create() {
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private fun destroy() {
        Thread{
            comPrintManager.destroy()
        }.start()
    }
}