package com.duolebo.blyrobot.tools

import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import android.util.Log
import com.baidu.aip.ocr.AipOcr
import java.util.regex.Pattern


class OcrManager {
    companion object {
        @SuppressLint("StaticFieldLeak")
        val instance = OcrManager()
        val TAG = "RobotOcrManager"
        const val AK = "zy4gq9vvYa0UF133COi2ITHI"
        const val SK = "cGG1wblcyMfpKjo8bG68lZYeysrEVOFq"

        const val APP_ID = "11067709"
        const val API_KEY = "APMf6m40GKnZK74ArXYmdMCf"
        const val SECRET_KEY = "KfiA2R9BTWo5xN4R9gHeztMQ6h3seyZL"

        const val CONN_TIMEOUT = 2000
        const val SOCKET_TIMEOUT = 60000
    }

    private lateinit var context: Context
    private lateinit var aipOcr: AipOcr

    fun init(context: Context) {
        this.context = context
        initOcr()
    }

    //  初始化百度ocr调用
    private fun initOcr() {
        this.aipOcr = AipOcr(APP_ID, API_KEY, SECRET_KEY)
        aipOcr.setConnectionTimeoutInMillis(CONN_TIMEOUT)
        aipOcr.setSocketTimeoutInMillis(SOCKET_TIMEOUT)
    }

    fun imageOcr(filePath: String) : String {
        var res = ""
        try {
            val options = HashMap<String, String>()
            options["recognize_granularity"] = "big"
            options["detect_direction"] = "true"

            // 先用简单识别，每天有5w次免费额度
            var result = aipOcr.basicGeneral(filePath, options)
            res = getOcrWords(result)

            // 如果无法识别，调用高精度识别，每天500次额度
            if (TextUtils.isEmpty(res)) {
                result = aipOcr.basicAccurateGeneral(filePath, options)
                res = getOcrWords(result)
            }

            Log.i(TAG, "imageOrc: $res")
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return res
    }

    private fun getOcrWords(result: org.json.JSONObject): String {
        var words = ""
        val wordsResult = result.getJSONArray("words_result")
        val num = result.getInt("words_result_num")
        if (wordsResult != null && num > 0) {
            val len = wordsResult.length()
            for ( i in 0..len) {
                val wordsObject = wordsResult.getJSONObject(i)
                try {
                    val rawWords = wordsObject.getString("words")
                    // 提取数字
                    val regEx = "[^0-9]"
                    val p = Pattern.compile(regEx)
                    val m = p.matcher(rawWords)
                    val newWords = m.replaceAll("").trim()
                    if (newWords.length == 11) {
                        words = newWords
                        break
                    }
                    else if (words.isEmpty()) {
                        words = newWords
                    }
                    else if (newWords.length > words.length) {
                        words = newWords
                    }

                } catch (e : java.lang.Exception) {
                    e.printStackTrace()
                }
            }
        }

        // 长度小于8的直接丢弃
        if (words.length < 7) {
            words = ""
        }

       return words
    }

    interface OcrListener {
        fun onResult(result: String)
    }

}