package com.rehome.bhdxj.activity


import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Rect
import android.graphics.RectF
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.camera.core.ImageCapture
import androidx.camera.view.LifecycleCameraController
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.rehome.bhdxj.databinding.ActivityQrCodeBinding
import com.rehome.bhdxj.Listener.QRCodeAnalyser
import com.rehome.bhdxj.base.BaseActivityOaToolbarViewBinding
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * date:2025/02/18 14:05:28
 * author:HuangWenfei
 * description:二维码扫描
 */
class QrCodeActivity : BaseActivityOaToolbarViewBinding<ActivityQrCodeBinding>() {

    private lateinit var lifecycleCameraController: LifecycleCameraController
    private lateinit var cameraExecutor: ExecutorService
    private val CAMERA_REQUEST_CAMERA_SCAN: Int = 88 //请求码


    override fun getViewBinding() = ActivityQrCodeBinding.inflate(layoutInflater)

    override fun getToolbar() = binding.toolbarView.toolbar

    override fun initView() {
        initToolbar("二维码/条码扫描")
        setLeftOnClickListener { finish() }
        checkPermission()
        //initController()
    }

    override fun initData() {

    }

    private fun checkPermission(){
        //检测摄像头权限
        if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
            binding.frCamera.visibility=View.GONE
            Toast.makeText(
                context,
                "权限拒绝,请手动设置开启APP访问摄像头权限",
                Toast.LENGTH_LONG
            ).show()
            return
        }

        //动态权限申请
        if (ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            binding.frCamera.visibility=View.GONE
            //权限请求
            ActivityCompat.requestPermissions(
                this,
                arrayOf<String>(Manifest.permission.CAMERA),
                CAMERA_REQUEST_CAMERA_SCAN
            )
        } else {
            //已授权，打开摄像头扫描
            initController()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (CAMERA_REQUEST_CAMERA_SCAN == requestCode) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                binding.frCamera.visibility=View.VISIBLE
                //已授权，打开摄像头扫描
                initController()
            } else {
                binding.frCamera.visibility=View.GONE
                //权限拒绝
                Toast.makeText(
                    this,
                    "权限拒绝,请手动设置开启APP访问摄像头权限",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility", "UnsafeOptInUsageError")
    private fun initController() {
        cameraExecutor = Executors.newSingleThreadExecutor()
        lifecycleCameraController = LifecycleCameraController(this)
        lifecycleCameraController.bindToLifecycle(this)
        lifecycleCameraController.imageCaptureFlashMode = ImageCapture.FLASH_MODE_AUTO
        lifecycleCameraController.setImageAnalysisAnalyzer(
            cameraExecutor,
            QRCodeAnalyser { barcodes, imageWidth, imageHeight ->
                if (barcodes.isEmpty()) {
                    return@QRCodeAnalyser
                }
                initScale(imageWidth, imageHeight)
                val list = ArrayList<RectF>()
                val strList = ArrayList<String>()

                barcodes.forEach { barcode ->
                    barcode.boundingBox?.let { rect ->
                        val translateRect = translateRect(rect)
                        list.add(translateRect)
//                        Log.e(
//                            "ztzt", "left：${translateRect.left}  +" +
//                                    "  top：${translateRect.top}  +  right：${translateRect.right}" +
//                                    "  +  bottom：${translateRect.bottom}"
//                        )
//                        Log.e("ztzt", "barcode.rawValue：${barcode.rawValue}")
                        strList.add(barcode.rawValue ?: "No Value")
                    }
                }
                judgeIntent(strList)
                binding.scanView.setRectList(list)

            })
        binding.previewView.controller = lifecycleCameraController
    }

    private fun judgeIntent(list: ArrayList<String>) {
        val sb = StringBuilder()
        list.forEach {
            sb.append(it)
            //sb.append("\n")
        }
        intentToResult(sb.toString())
    }

    private fun intentToResult(result: String) {
        val resultIntent = Intent()
        val bundle = Bundle()
        bundle.putString("code", result)
        resultIntent.putExtras(bundle)
        setResult(RESULT_OK, resultIntent)
        finish();
    }

    private var scaleX = 0f
    private var scaleY = 0f

    private fun translateX(x: Float): Float = x * scaleX
    private fun translateY(y: Float): Float = y * scaleY

    //将扫描的矩形换算为当前屏幕大小
    private fun translateRect(rect: Rect) = RectF(
        translateX(rect.left.toFloat()),
        translateY(rect.top.toFloat()),
        translateX(rect.right.toFloat()),
        translateY(rect.bottom.toFloat())
    )

    //初始化缩放比例
    private fun initScale(imageWidth: Int, imageHeight: Int) {
        //Log.e("ztzt", "imageWidth：${imageWidth} + imageHeight：${imageHeight}")
        scaleY = binding.scanView.height.toFloat() / imageWidth.toFloat()
        scaleX = binding.scanView.width.toFloat() / imageHeight.toFloat()
        //Log.e("ztzt", "scaleX：${scaleX} + scaleY：${scaleY}")
    }
}