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.ads.AdsMgr
import com.base.scanqr.ads.AdsShowCallBack
import com.base.scanqr.base.BaseFragment
import com.base.scanqr.bean.ContractUIBean.Companion.createContractBean
import com.base.scanqr.bean.ContractUIBean.Companion.isContractQR
import com.base.scanqr.bean.EmailUIBean.Companion.createEmailBean
import com.base.scanqr.bean.EmailUIBean.Companion.isEmailQR
import com.base.scanqr.bean.EventUIBean.Companion.createEventBean
import com.base.scanqr.bean.EventUIBean.Companion.isEventQR
import com.base.scanqr.bean.MessageUIBean.Companion.createMessageBean
import com.base.scanqr.bean.MessageUIBean.Companion.isMessageQR
import com.base.scanqr.bean.ProductUIBean
import com.base.scanqr.bean.ScanBean.Companion.CREATE_TYPE_SCAN
import com.base.scanqr.bean.TelephoneUIBean.Companion.createTelephoneBean
import com.base.scanqr.bean.TelephoneUIBean.Companion.isTelephoneQR
import com.base.scanqr.bean.TextUIBean
import com.base.scanqr.bean.WebsiteUIBean.Companion.createWebsiteBean
import com.base.scanqr.bean.WebsiteUIBean.Companion.isWebsiteQR
import com.base.scanqr.bean.WifiUIBean.Companion.createWifiBean
import com.base.scanqr.bean.WifiUIBean.Companion.isWifiQR
import com.base.scanqr.databinding.FragmentScanBinding
import com.base.scanqr.qr.QRImageAnalyzer
import com.base.scanqr.ui.contact.ContractCodeActivity
import com.base.scanqr.ui.email.EmailCodeActivity
import com.base.scanqr.ui.event.EventCodeActivity
import com.base.scanqr.ui.message.MessageCodeActivity
import com.base.scanqr.ui.product.ProductCodeActivity
import com.base.scanqr.ui.telephone.TelephoneCodeActivity
import com.base.scanqr.ui.text.TextCodeActivity
import com.base.scanqr.ui.website.WebsiteCodeActivity
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.google.gson.Gson
import com.google.mlkit.vision.barcode.common.Barcode
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.shandian_off)
                    binding.flFlash.setOnClickListener {
                        activity.cameraUtils?.turnOnFlash()
                    }
                }
                if (state == FLASH_MODE_ON) {
                    binding.ivFlash.setImageResource(R.mipmap.shnadian_on)
                    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 (valueType == Barcode.TYPE_PRODUCT) {
            if (scanJump.get()) return
            scanJump.set(true)
            AdsMgr.showInsert(activity, false, object : AdsShowCallBack() {
                override fun close(where: Int) {
                    jumpProductCodeActivity(activity, qrCodeValue)
                }

                override fun failed(where: Int) {
                    jumpProductCodeActivity(activity, qrCodeValue)
                }

                override fun googleFailed(where: Int) {
                    jumpProductCodeActivity(activity, qrCodeValue)
                }
            })
            return
        }
        if (isMessageQR(qrCodeValue)) {
            if (scanJump.get()) return
            scanJump.set(true)
            AdsMgr.showInsert(activity, false, object : AdsShowCallBack() {
                override fun close(where: Int) {
                    jumpMessageCodeActivity(activity, qrCodeValue)
                }

                override fun failed(where: Int) {
                    jumpMessageCodeActivity(activity, qrCodeValue)
                }

                override fun googleFailed(where: Int) {
                    jumpMessageCodeActivity(activity, qrCodeValue)
                }
            })
            return
        }
        if (isContractQR(qrCodeValue)) {
            if (scanJump.get()) return
            scanJump.set(true)
            AdsMgr.showInsert(activity, false, object : AdsShowCallBack() {
                override fun close(where: Int) {
                    jumpContractCodeActivity(activity, qrCodeValue)
                }

                override fun failed(where: Int) {
                    jumpContractCodeActivity(activity, qrCodeValue)
                }

                override fun googleFailed(where: Int) {
                    jumpContractCodeActivity(activity, qrCodeValue)
                }
            })
            return
        }
        if (isTelephoneQR(qrCodeValue)) {
            if (scanJump.get()) return
            scanJump.set(true)
            AdsMgr.showInsert(activity, false, object : AdsShowCallBack() {
                override fun close(where: Int) {
                    jumpTelephoneCodeActivity(activity, qrCodeValue)
                }

                override fun failed(where: Int) {
                    jumpTelephoneCodeActivity(activity, qrCodeValue)
                }

                override fun googleFailed(where: Int) {
                    jumpTelephoneCodeActivity(activity, qrCodeValue)
                }
            })
            return
        }
        if (isEventQR(qrCodeValue)) {
            if (scanJump.get()) return
            scanJump.set(true)
            AdsMgr.showInsert(activity, false, object : AdsShowCallBack() {
                override fun close(where: Int) {
                    jumpEventCodeActivity(activity, qrCodeValue)
                }

                override fun failed(where: Int) {
                    jumpEventCodeActivity(activity, qrCodeValue)
                }

                override fun googleFailed(where: Int) {
                    jumpEventCodeActivity(activity, qrCodeValue)
                }
            })
            return
        }

        if (isWifiQR(qrCodeValue)) {
            if (scanJump.get()) return
            scanJump.set(true)
            AdsMgr.showInsert(activity, false, object : AdsShowCallBack() {
                override fun close(where: Int) {
                    jumpWifiCodeActivity(activity, qrCodeValue)
                }

                override fun failed(where: Int) {
                    jumpWifiCodeActivity(activity, qrCodeValue)
                }

                override fun googleFailed(where: Int) {
                    jumpWifiCodeActivity(activity, qrCodeValue)
                }
            })
            return
        }

        if (isEmailQR(qrCodeValue)) {
            if (scanJump.get()) return
            scanJump.set(true)
            AdsMgr.showInsert(activity, false, object : AdsShowCallBack() {
                override fun close(where: Int) {
                    jumpEmailCodeActivity(activity, qrCodeValue)
                }

                override fun failed(where: Int) {
                    jumpEmailCodeActivity(activity, qrCodeValue)
                }

                override fun googleFailed(where: Int) {
                    jumpEmailCodeActivity(activity, qrCodeValue)
                }
            })
            return
        }

        if (isWebsiteQR(qrCodeValue)) {
            if (scanJump.get()) return
            scanJump.set(true)
            AdsMgr.showInsert(activity, false, object : AdsShowCallBack() {
                override fun close(where: Int) {
                    jumpWebsiteCodeActivity(activity, qrCodeValue)
                }

                override fun failed(where: Int) {
                    jumpWebsiteCodeActivity(activity, qrCodeValue)

                }

                override fun googleFailed(where: Int) {
                    jumpWebsiteCodeActivity(activity, qrCodeValue)

                }
            })
            return
        }

        if (valueType == Barcode.TYPE_TEXT) {
            if (scanJump.get()) return
            scanJump.set(true)
            AdsMgr.showInsert(activity, false, object : AdsShowCallBack() {
                override fun close(where: Int) {
                    jumpTextCodeActivity(activity, qrCodeValue)
                }

                override fun failed(where: Int) {
                    jumpTextCodeActivity(activity, qrCodeValue)
                }

                override fun googleFailed(where: Int) {
                    jumpTextCodeActivity(activity, qrCodeValue)

                }
            })
            return
        }
    }

    private fun jumpMessageCodeActivity(activity: MainActivity, qrCodeValue: String) {
        activity.startActivity(Intent(activity, MessageCodeActivity::class.java).apply {
            val bean = createMessageBean(qrCodeValue)
            bean.needCreate = true
            bean.createType = CREATE_TYPE_SCAN
            putExtra("data", Gson().toJson(bean))
        })
    }

    private fun jumpContractCodeActivity(activity: MainActivity, qrCodeValue: String) {
        activity.startActivity(Intent(activity, ContractCodeActivity::class.java).apply {
            val bean = createContractBean(qrCodeValue)
            bean.needCreate = true
            bean.createType = CREATE_TYPE_SCAN
            putExtra("data", Gson().toJson(bean))
        })
    }

    private fun jumpTelephoneCodeActivity(activity: MainActivity, qrCodeValue: String) {
        activity.startActivity(Intent(activity, TelephoneCodeActivity::class.java).apply {
            val bean = createTelephoneBean(qrCodeValue)
            bean.needCreate = true
            bean.createType = CREATE_TYPE_SCAN
            putExtra("data", Gson().toJson(bean))
        })
    }

    private fun jumpEventCodeActivity(activity: MainActivity, qrCodeValue: String) {
        activity.startActivity(Intent(activity, EventCodeActivity::class.java).apply {
            val bean = createEventBean(qrCodeValue)
            bean.needCreate = true
            bean.createType = CREATE_TYPE_SCAN
            putExtra("data", Gson().toJson(bean))
        })
    }

    private fun jumpTextCodeActivity(activity: MainActivity, qrCodeValue: String) {
        activity.startActivity(Intent(activity, TextCodeActivity::class.java).apply {
            val bean = TextUIBean()
            bean.content = qrCodeValue
            bean.needCreate = true
            bean.createType = CREATE_TYPE_SCAN
            putExtra("data", Gson().toJson(bean))
        })
    }

    private fun jumpWebsiteCodeActivity(activity: MainActivity, qrCodeValue: String) {
        activity.startActivity(Intent(activity, WebsiteCodeActivity::class.java).apply {
            val bean = createWebsiteBean(qrCodeValue)
            bean.needCreate = true
            bean.createType = CREATE_TYPE_SCAN
            putExtra("data", Gson().toJson(bean))
        })
    }

    private fun jumpEmailCodeActivity(activity: MainActivity, qrCodeValue: String) {
        activity.startActivity(Intent(activity, EmailCodeActivity::class.java).apply {
            val bean = createEmailBean(qrCodeValue)
            bean.needCreate = true
            bean.createType = CREATE_TYPE_SCAN
            putExtra("data", Gson().toJson(bean))
        })
    }

    private fun jumpWifiCodeActivity(activity: MainActivity, qrCodeValue: String) {
        activity.startActivity(Intent(activity, WifiCodeActivity::class.java).apply {
            val bean = createWifiBean(qrCodeValue)
            bean.needCreate = true
            bean.createType = CREATE_TYPE_SCAN
            putExtra("data", Gson().toJson(bean))
        })
    }

    private fun jumpProductCodeActivity(activity: MainActivity, qrCodeValue: String) {
        activity.startActivity(Intent(activity, ProductCodeActivity::class.java).apply {
            val bean = ProductUIBean()
            bean.content = qrCodeValue
            bean.needCreate = true
            bean.createType = CREATE_TYPE_SCAN
            putExtra("data", Gson().toJson(bean))
        })
    }

    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")
        }
    }

}