package com.yidian.shenghuoquan.newscontent.ui.idcard

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.megvii.demo.activity.IDCardDetectActivity
import com.megvii.demo.utils.Configuration
import com.megvii.idcardquality.IDCardQualityLicenseManager
import com.megvii.licensemanager.Manager
import com.yidian.common.base.BaseActivity
import com.yidian.shenghuoquan.newscontent.databinding.ActivityIdcardBinding
import com.yidian.shenghuoquan.newscontent.http.ApiService
import com.yidian.shenghuoquan.newscontent.http.httpbean.GetIDCardOCRBean
import com.yidian.shenghuoquan.newscontent.http.httpbean.IGetIDCardOCRCallback
import com.yidian.shenghuoquan.newscontent.ui.alive.AliveTestActivity
import com.yidian.shenghuoquan.newscontent.ui.auth.LifeAccountAuthDataManager
import com.yidian.shenghuoquan.newscontent.utils.KS3Core
import com.yidian.utils.ToastUtil
import java.io.File
import java.io.FileOutputStream


/**
 * Author: sym
 * Date: 2021/5/20 4:00 PM
 * Describe:
 */
class IDCardTestActivity : BaseActivity<ActivityIdcardBinding>() {
    private lateinit var mIdCardLicenseManager: IDCardQualityLicenseManager
    private val INTO_IDCARDSCAN_PAGE = 100

    private var idCardFront: Bitmap? = null
    private var idCardBack: Bitmap? = null
    private lateinit var idCardFrontObjectKey: String
    private lateinit var idCardBackObjectKey: String
    private lateinit var idCardFrontBucket: String
    private lateinit var idCardBackBucket: String

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

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewBind.btStart.setOnClickListener {
            //1、初始化配置
            initConfig()
            //2、请求授权信息
            startGetLicense()
        }
        viewBind.btnOcr.setOnClickListener {
            if (idCardFront == null || idCardBack == null) {
                return@setOnClickListener
            }
            val frontFile = File(externalCacheDir?.absolutePath + "/ocr/idCardFront.jpg")
            if (frontFile.exists()) {
                frontFile.delete()
            } else {
                frontFile.parentFile?.mkdirs()
                frontFile.createNewFile()
            }
            val backFile = File(externalCacheDir?.absolutePath + "/ocr/idCardBack.jpg")
            if (backFile.exists()) {
                backFile.delete()
            } else {
                backFile.parentFile?.mkdirs()
                backFile.createNewFile()
            }
            idCardFront?.compress(Bitmap.CompressFormat.JPEG, 100, FileOutputStream(frontFile))
            idCardBack?.compress(Bitmap.CompressFormat.JPEG, 100, FileOutputStream(backFile))
            KS3Core.INSTANCE.uploadObject(frontFile, KS3Core.ScenarioType.ID_CARD, object : KS3Core.OnKS3TaskListener {
                override fun onTaskStart() {

                }

                override fun onTaskProgress(progress: Double) {

                }

                override fun onTaskFinish() {

                }

                override fun onTaskCancel() {

                }

                override fun onTaskSuccess(bucket: String?, objectKey: String?) {
                    if (objectKey != null) {
                        idCardFrontObjectKey = objectKey
                    }
                    if (bucket != null) {
                        idCardFrontBucket = bucket
                    }
                    KS3Core.INSTANCE.uploadObject(backFile, KS3Core.ScenarioType.ID_CARD, object : KS3Core.OnKS3TaskListener {
                        override fun onTaskStart() {

                        }

                        override fun onTaskProgress(progress: Double) {

                        }

                        override fun onTaskFinish() {

                        }

                        override fun onTaskCancel() {

                        }

                        override fun onTaskSuccess(bucket: String?, objectKey: String?) {
                            if (objectKey != null) {
                                idCardBackObjectKey = objectKey
                            }
                            if (bucket != null) {
                                idCardBackBucket = bucket
                            }
                            val requestParams = HashMap<String, String?>()
                            requestParams["posit_image_objectid"] = idCardFrontObjectKey
                            requestParams["back_image_objectid"] = idCardBackObjectKey
                            requestParams["posit_bucket"] = idCardFrontBucket
                            requestParams["back_bucket"] = idCardBackBucket
                            ApiService.getIDCardOCR(object : IGetIDCardOCRCallback {
                                override fun getIDCardOCRSuccess(result: GetIDCardOCRBean.Response?) {
                                    Log.d(KS3Core.TAG, "name: ${result?.posit?.name}, id num: ${result?.posit?.idcard_number}")
                                    ToastUtil.showToast(this@IDCardTestActivity, "ocr result, name: ${result?.posit?.name}, number: ${result?.posit?.idcard_number}")
                                    // 身份证OCR成功后执行活体检测
                                    val intent = Intent(this@IDCardTestActivity, AliveTestActivity::class.java)
                                    intent.putExtra("idCardName", result?.posit?.name)
                                    intent.putExtra("idCardNo", result?.posit?.idcard_number)
                                    startActivity(intent)
                                }

                                override fun getIDCardOCRFailure(message: String?) {

                                }


                            }, requestParams)
                        }

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

                        }

                    })
                }

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

                }

            })
        }

        requestCameraPerm()

    }

    private fun startGetLicense() {
        mIdCardLicenseManager = IDCardQualityLicenseManager(this)
        var status: Long = 0
        try {
            status = mIdCardLicenseManager.checkCachedLicense()
        } catch (e: Throwable) {
            e.printStackTrace()
        }

        if (status > 0) { //大于0，已授权或者授权未过期
            val intent = Intent(this, IDCardDetectActivity::class.java)
            this.startActivityForResult(intent, INTO_IDCARDSCAN_PAGE)
            Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show()
        } else { //需要重新授权
            Toast.makeText(this, "没有缓存的授权信息，开始授权", Toast.LENGTH_SHORT).show()
            Thread {
                try {
                    getLicense()
                } catch (e: Throwable) {
                    e.printStackTrace()
                }
            }.start()
        }
    }

    private fun getLicense() {
        //参数2 是否使用ipv6
        val manager = Manager(this, true)
        manager.registerLicenseManager(mIdCardLicenseManager)

        val uuid = Configuration.getUUID(this)
        val authMsg = mIdCardLicenseManager.getContext(uuid)
        manager.takeLicenseFromNetwork(authMsg)
        if (mIdCardLicenseManager.checkCachedLicense() > 0) { //大于0，已授权或者授权未过期
            runOnUiThread {
                val intent = Intent(
                    this,
                    IDCardDetectActivity::class.java
                )
                this.startActivityForResult(intent, INTO_IDCARDSCAN_PAGE)
                Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT)
                    .show()
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //@TODO 权限通过后的回调

    }

    private fun initConfig() {
        if (viewBind.rbV.isChecked) {
            Configuration.setIsVertical(this, true)
        } else {
            Configuration.setIsVertical(this, false)
        }
        if (viewBind.rbFront.isChecked) {
            Configuration.setCardType(this, 1)
        } else {
            Configuration.setCardType(this, 2)
        }
    }


    private fun requestCameraPerm() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED
            ) {
                requestPermissions(
                    arrayOf(Manifest.permission.CAMERA),
                    100
                )
            }
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == INTO_IDCARDSCAN_PAGE && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                val bytes = data.getByteArrayExtra("idcardimg_bitmap")
                if (Configuration.getCardType(this) == 1) {
                    idCardFront = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
                    viewBind.resultIdcardImageFront.setImageBitmap(idCardFront)
                } else {
                    idCardBack = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
                    viewBind.resultIdcardImageBack.setImageBitmap(idCardBack)
                }
            }
        }
    }
}