package com.base.scanqr.ui.main

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.hardware.camera2.CameraMetadata.FLASH_MODE_OFF
import android.net.Uri
import android.view.View
import android.widget.SeekBar
import androidx.camera.core.ImageCapture.FLASH_MODE_ON
import androidx.lifecycle.lifecycleScope
import com.base.scanqr.R
import com.base.scanqr.base.BaseFragment
import com.base.scanqr.bean.ScanBean.Companion.CREATE_TYPE_SCAN
import com.base.scanqr.bean.ScanBean.Companion.CREATE_TYPE_USER
import com.base.scanqr.bean.TextUIBean
import com.base.scanqr.databinding.FragmentScanBinding
import com.base.scanqr.qr.QRImageAnalyzer
import com.base.scanqr.ui.email.EmailCodeActivity
import com.base.scanqr.ui.text.TextCodeActivity
import com.base.scanqr.ui.wifi.WifiCodeActivity
import com.base.scanqr.utils.BitmapUtils.uriToBitmap
import com.base.scanqr.utils.IntentUtils.intentSafPickImage
import com.base.scanqr.utils.LogEx
import com.base.scanqr.utils.PermissionUtils.checkCameraPermission
import com.base.scanqr.utils.QRCodeUtils
import com.google.gson.Gson
import com.gyf.immersionbar.ktx.immersionBar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.concurrent.atomic.AtomicBoolean


class ScanFragment : BaseFragment<FragmentScanBinding>(FragmentScanBinding::inflate) {


    private var zoomPair = Pair(0f, 100f)
    private val qrImageAnalyzer = QRImageAnalyzer()

    override fun initView() {
        super.initView()
    }

    override fun onResumeOneShoot() {
        super.onResumeOneShoot()

        if (requireContext().checkCameraPermission()) {
            initCamera()
        } else {
            val activity = requireActivity() as MainActivity?
            activity ?: return
            activity.launcher.launch(arrayOf(Manifest.permission.CAMERA)) {
                initCamera()
            }
        }
    }

    private var cameraInit = AtomicBoolean(false)

    private fun initCamera() {
        if (cameraInit.get()) return
        val hasFlash = requireContext().packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)
        if (!hasFlash) {
            binding.flFlash.visibility = View.GONE
        }

        qrImageAnalyzer.parseAction = { qrCodeValue, valueType ->
            handleScan(qrCodeValue, valueType)
        }
        val activity = requireActivity() as MainActivity?
        activity ?: return
        activity.cameraUtils?.startBind(binding.previewView, qrImageAnalyzer)

        activity.cameraUtils?.cameraReadyCallBack = {

            //变焦
            if (activity.cameraUtils?.isZoomSupported() != true) {
                binding.llZoom.visibility = View.GONE
            } else {
                zoomPair = activity.cameraUtils?.getZoomRange() ?: Pair(0f, 100f)
                LogEx.logDebug(TAG, "zoomPair=${zoomPair.first} ${zoomPair.second}")
                binding.seekbar.max = ((zoomPair.second - zoomPair.first) * 10).toInt()
            }

            //闪光灯
            activity.cameraUtils?.getFlashState()?.observe(this) { state ->
                if (state == FLASH_MODE_OFF) {
                    binding.ivFlash.setImageResource(R.mipmap.shnadian_on)
                    binding.flFlash.setOnClickListener {
                        activity.cameraUtils?.turnOnFlash()
                    }
                }
                if (state == FLASH_MODE_ON) {
                    binding.ivFlash.setImageResource(R.mipmap.shandian_off)
                    binding.flFlash.setOnClickListener {
                        activity.cameraUtils?.turnOffFlash()
                    }
                }
            }
        }

        cameraInit.set(true)
    }

    private var scanJump = AtomicBoolean(false)

    /**
     * 处理扫描结果
     */
    private fun handleScan(qrCodeValue: String, valueType: Int) {
        LogEx.logDebug(TAG, "qrCodeValue=$qrCodeValue valueType=$valueType")
        val activity = requireActivity() as MainActivity?
        activity ?: return
        if (QRCodeUtils.isWifiQR(qrCodeValue)) {
            if (scanJump.get()) return
            scanJump.set(true)
            activity.startActivity(Intent(activity, WifiCodeActivity::class.java).apply {
                val bean = QRCodeUtils.createWifiBean(qrCodeValue)
                bean.createType = CREATE_TYPE_SCAN
                putExtra("data", Gson().toJson(bean))
            })
            return
        }

        if (QRCodeUtils.isEmailQR(qrCodeValue)) {
            if (scanJump.get()) return
            scanJump.set(true)
            activity.startActivity(Intent(activity, EmailCodeActivity::class.java).apply {
                val bean = QRCodeUtils.createEmailBean(qrCodeValue)
                bean.createType = CREATE_TYPE_SCAN
                putExtra("data", Gson().toJson(bean))
            })
            return
        }

        if (qrCodeValue.isEmpty()) {
            if (scanJump.get()) return
            scanJump.set(true)
            activity.startActivity(Intent(activity, TextCodeActivity::class.java).apply {
                val bean = TextUIBean()
                bean.content = qrCodeValue
                bean.createType = CREATE_TYPE_SCAN
                putExtra("data", Gson().toJson(bean))
            })
            return
        }
    }

    override fun onStop() {
        super.onStop()
        val activity = requireActivity() as MainActivity?
        activity?.cameraUtils?.unBind()
        cameraInit.set(false)
    }

    override fun onDestroy() {
        super.onDestroy()
        val activity = requireActivity() as MainActivity?
        activity?.cameraUtils?.unBind()
    }

    override fun initListener() {
        super.initListener()
        binding.flImage.setOnClickListener {
            val activity = requireActivity() as MainActivity?
            val intent = intentSafPickImage()
            activity?.launcher?.launch(intent) { result ->
                val uri: Uri? = result.data?.data
                uri ?: return@launch
                lifecycleScope.launch(Dispatchers.IO) {
                    val bitmap = requireContext().uriToBitmap(uri)
                    bitmap?.let {
                        launch(Dispatchers.Main) {
                            qrImageAnalyzer.processImage(requireContext(), bitmap)
                        }
                    }
                }
            }
        }
        binding.flFlash.setOnClickListener {
            val activity = requireActivity() as MainActivity?
            activity?.cameraUtils?.turnOnFlash()
        }
        binding.seekbar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    val zoom = (zoomPair.first + seekBar.progress / 10f)
                    val activity = requireActivity() as MainActivity?
                    activity?.cameraUtils?.setZoomRate(zoom)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {

            }
        })
        binding.flReduce.setOnClickListener {
            val activity = requireActivity() as MainActivity?
            activity?.cameraUtils?.setZoomRate(zoomPair.first)
            binding.seekbar.progress = 0
        }
        binding.flAdd.setOnClickListener {
            val activity = requireActivity() as MainActivity?
            activity?.cameraUtils?.setZoomRate(zoomPair.second)
            binding.seekbar.progress = binding.seekbar.max
        }
    }

    override fun onResume() {
        super.onResume()
        scanJump.set(false)
        immersionBar {
            statusBarColor("#00FFFFFF")
        }
    }

}