package com.yidian.shenghuoquan.newscontent.ui.alive

import android.app.ProgressDialog
import android.os.Bundle
import android.widget.Toast
import com.megvii.meglive_sdk.listener.DetectCallback
import com.megvii.meglive_sdk.listener.PreCallback
import com.megvii.meglive_sdk.manager.MegLiveManager
import com.yidian.common.AppConfig
import com.yidian.common.base.BaseActivity
import com.yidian.common.http.HttpResult
import com.yidian.common.utils.ToolsUtil
import com.yidian.shenghuoquan.newscontent.databinding.ActivityAliveLayoutBinding
import com.yidian.shenghuoquan.newscontent.http.ApiService
import com.yidian.shenghuoquan.newscontent.http.httpbean.AuthPersonalGetTokenBean
import com.yidian.shenghuoquan.newscontent.http.httpbean.AuthPersonalGetTokenCallback
import com.yidian.shenghuoquan.newscontent.http.httpbean.IdentifyIdOcrVerifyBean
import com.yidian.shenghuoquan.newscontent.http.httpbean.IdentifyIdOcrVerifyCallback
import com.yidian.shenghuoquan.newscontent.utils.KS3Core
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream

/**
 * Author: sym
 * Date: 2021/5/19 6:11 PM
 * Describe:onPreStart showDialogDismiss  onPreFinish  progressDialogDismiss
 */
class AliveTestActivity : BaseActivity<ActivityAliveLayoutBinding>(), PreCallback, DetectCallback {
    private var sign = ""
    private var bizToken = ""
    private var megLiveManager: MegLiveManager? = null
    private var modelPath = "" // 模型本地存放路径
    private var dataPath = "" // 模型本地存放路径
    private var mProgressDialog: ProgressDialog? = null

    private var idCardName: String? = null
    private var idCardNo: String? = null


    override fun createViewBinding(): ActivityAliveLayoutBinding {
        return ActivityAliveLayoutBinding.inflate(layoutInflater)
    }

    override fun getXPageName(): String {
        return ""
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initSign()
        setOnListener()
        idCardName = intent.getStringExtra("idCardName")
        idCardNo = intent.getStringExtra("idCardNo")
    }

    private fun initSign() {
        val currtTime = System.currentTimeMillis() / 1000
        val expireTime = (System.currentTimeMillis() + 60 * 60 * 100) / 1000
        sign = GenerateSign.appSign(AppConfig.KUANGSHI_ALIVE_API_KEY, AppConfig.KUANGSHI_SECRET, currtTime, expireTime)
        megLiveManager = MegLiveManager.getInstance()
        modelPath = saveAssets("faceidmodel.bin", "model")!!
        mProgressDialog = ProgressDialog(this)
        mProgressDialog!!.setCancelable(false)
    }

    private fun setOnListener() {
        viewBind.btActionYy.setOnClickListener {
            val requestParams = HashMap<String, String?>()
            requestParams["id_number"] = idCardNo
            requestParams["id_card_name"] = idCardName
            requestParams["liveness_type"] = "meglive"
            ApiService.authPersonalGetToken(authPersonalGetTokenCallback, requestParams)
        }
    }

    private val authPersonalGetTokenCallback = object : AuthPersonalGetTokenCallback {
        override fun getTokenSuccess(t: HttpResult<AuthPersonalGetTokenBean.Response?>?) {
            bizToken = t?.result?.biz_token!!
            megLiveManager?.preDetect(this@AliveTestActivity, bizToken, "zh", "https://api.megvii.com", modelPath, this@AliveTestActivity)
        }
    }

    private fun saveAssets(fileName: String, path: String): String? {
        val dir = File(getExternalFilesDir("megvii"), path)
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                return null
            }
        }
        val file = File(dir, fileName)
        var fos: FileOutputStream? = null
        var `is`: InputStream? = null
        var ret: String? = null
        try {
            var count: Int
            val buffer = ByteArray(1024)
            fos = FileOutputStream(file)
            `is` = this.assets.open(fileName)
            while (`is`.read(buffer).also { count = it } != -1) {
                fos.write(buffer, 0, count)
            }
            ret = file.absolutePath
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        } finally {
            try {
                fos?.close()
                `is`?.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return ret
    }

    override fun onPreStart() {
        showDialogDismiss()
    }

    private fun showDialogDismiss() {
        runOnUiThread {
            mProgressDialog?.show()
        }
    }

    override fun onPreFinish(token: String?, errorCode: Int, errorMessage: String?) {
        progressDialogDismiss()
        if (errorCode == 1000) {
            megLiveManager!!.setVerticalDetectionType(MegLiveManager.DETECT_VERITICAL_FRONT)
            megLiveManager!!.startDetect(this@AliveTestActivity)
        }
    }

    private fun progressDialogDismiss() {
        runOnUiThread {
            if (mProgressDialog != null) {
                mProgressDialog!!.dismiss()
            }
        }
    }

    override fun onDetectFinish(token: String?, errorCode: Int, errorMessage: String?, data: String?) {
        if (errorCode == 1000) {
            token?.let { verify(it, data!!.toByteArray()) }
        } else {
            Toast.makeText(this@AliveTestActivity, errorMessage, Toast.LENGTH_SHORT).show()
        }
    }

    private fun verify(token: String, data: ByteArray) {
        showDialogDismiss()
        saveFile(ToolsUtil.randomName(), data)
    }

    private val identifyIdOcrVerifyCallback = object : IdentifyIdOcrVerifyCallback {
        override fun identifyIdOcrVerifySuccess(t: HttpResult<IdentifyIdOcrVerifyBean.Response?>?) {
            progressDialogDismiss()
            if (t!!.result!!.verify_result) {
                Toast.makeText(this@AliveTestActivity, "活体检测结果成功    verify_result = true ", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this@AliveTestActivity, "活体检测结果失败    msg = ${t.reason}", Toast.LENGTH_SHORT).show()
            }
        }

        override fun identifyIdOcrVerifyFailure(t: HttpResult<IdentifyIdOcrVerifyBean.Response?>?) {
            progressDialogDismiss()
        }
    }

    // 将字节流转换成文件
    @Throws(Exception::class)
    fun saveFile(filename: String, data: ByteArray?) {
        if (data != null) {

            dataPath = externalCacheDir?.absolutePath + "/alive/meglive"
            val file = File(dataPath)

            if (file.exists()) {
                file.delete()
            } else {
                file.parentFile?.mkdirs()
                file.createNewFile()
            }
            val fos = FileOutputStream(file)
            fos.write(data, 0, data.size)
            fos.flush()
            fos.close()

            KS3Core.INSTANCE.uploadObject(file, KS3Core.ScenarioType.ALIVE_DETECT, object : KS3Core.OnKS3TaskListener {
                override fun onTaskStart() {
                }

                override fun onTaskProgress(progress: Double) {
                }

                override fun onTaskFinish() {
                }

                override fun onTaskCancel() {
                }

                override fun onTaskSuccess(bucket: String?, objectKey: String?) {
                    val requestParams = HashMap<String, String?>()
                    requestParams["biz_token"] = bizToken
                    requestParams["meglive_objectid"] = objectKey
                    requestParams["meglive_bucket"] = bucket
                    ApiService.identifyIdOcrVerify(identifyIdOcrVerifyCallback, requestParams)
                }

                override fun onTaskFailure(statesCode: Int, message: String?) {
                }

            })
        }
    }

}