package com.za.ui.camera

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Bitmap.CompressFormat
import android.graphics.Matrix
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.OptIn
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.ExperimentalGetImage
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.ImageProxy
import androidx.camera.view.LifecycleCameraController
import androidx.camera.view.PreviewView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.ImageUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.face.Face
import com.google.mlkit.vision.face.FaceDetection
import com.google.mlkit.vision.face.FaceDetectorOptions
import com.za.bean.request.DriverFaceCompareBean
import com.za.bean.request.DriverFaceCompareRequest
import com.za.common.GlobalData
import com.za.common.log.LogUtil
import com.za.common.speech.SpeechManager
import com.za.net.BaseObserver
import com.za.net.CommonMethod
import com.za.net.RetrofitHelper
import com.za.servicing.R
import com.za.signature.view.CircleImageView
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import kotlin.math.abs

class ServicePeopleRealActivity : AppCompatActivity() {
	private lateinit var lifecycleCameraController : LifecycleCameraController
	private lateinit var cameraExecutor : ExecutorService
	private var avatarBitmap : Bitmap? = null
	private var isActivityActive = true

	private var currentStep = 0
	private val steps = listOf("请保持面部居中", "请向左转头", "请向右转头", "请保持面部居中")

	private var isStepCompleted = false
	private lateinit var viewFinder : PreviewView
	private lateinit var stepText : TextView
	private lateinit var confirmationLayout : FrameLayout
	private lateinit var previewImage : CircleImageView
	private lateinit var retryButton : Button
	private lateinit var confirmButton : Button

	private val faceDetector = FaceDetection.getClient(FaceDetectorOptions.Builder()
		.setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE)
		.setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL)
		.setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_ALL).build())

	private var loadingDialog : AlertDialog? = null

	override fun onCreate(savedInstanceState : Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_service_people_real)        // 初始化控制器
		lifecycleCameraController = LifecycleCameraController(this).apply {
			cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
			setEnabledUseCases(LifecycleCameraController.IMAGE_CAPTURE or LifecycleCameraController.IMAGE_ANALYSIS)
		}

		initializeViews()
		setupClickListeners()

		if (allPermissionsGranted()) {
			startCamera()
		} else {
			ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS)
		}

		cameraExecutor = Executors.newSingleThreadExecutor()
		updateStepUI()
	}

	private fun initializeViews() {
		viewFinder = findViewById(R.id.viewFinder)
		viewFinder.controller = lifecycleCameraController        // 将控制器与生命周期绑定
		lifecycleCameraController.bindToLifecycle(this)

		stepText = findViewById(R.id.stepText)
		confirmationLayout = findViewById(R.id.confirmationLayout)
		previewImage = findViewById(R.id.previewImage)
		retryButton = findViewById(R.id.retryButton)
		confirmButton = findViewById(R.id.confirmButton)
	}

	private fun setupClickListeners() {
		retryButton.setOnClickListener {
			resetDetection()
		}

		confirmButton.setOnClickListener {
			returnPhotoResult()
		}
	}

	private fun captureImage() {
		lifecycleCameraController.takePicture(ContextCompat.getMainExecutor(this),
			object : ImageCapture.OnImageCapturedCallback() {
				@OptIn(ExperimentalGetImage::class)
				override fun onCaptureSuccess(image : ImageProxy) {

					val mediaImage = image.image
					LogUtil.print("拍照成功", image.imageInfo.toString())
					if (mediaImage != null) {
						val inputImage =
							InputImage.fromMediaImage(mediaImage, image.imageInfo.rotationDegrees)

						faceDetector.process(inputImage).addOnSuccessListener { faces ->
							when {
								faces.isEmpty() -> {
									runOnUiThread {
										Toast.makeText(this@ServicePeopleRealActivity,
											"未检测到人脸",
											Toast.LENGTH_SHORT).show()
									}
								}

								faces.size > 1 -> {
									runOnUiThread {
										Toast.makeText(this@ServicePeopleRealActivity,
											"检测到多个人脸，请确保画面中只有一个人脸",
											Toast.LENGTH_SHORT).show()
									}
								}

								else -> {
									LogUtil.print("人脸检测成功", faces[0].toString())
									avatarBitmap = handlerBitmap(image.toBitmap(), image.imageInfo.rotationDegrees)
									LogUtil.print("人脸认证通过", faces[0].toString())
									runOnUiThread {
										showConfirmation()
									}
								}
							}
						}.addOnFailureListener { e ->
							LogUtil.print("人脸检测失败", e)
							if (isActivityActive) {
								Toast.makeText(this@ServicePeopleRealActivity,
									"人脸检测失败",
									Toast.LENGTH_SHORT).show()
							}
						}.addOnCompleteListener {
							image.close()
						}
					} else {
						image.close()
					}
				}

				override fun onError(exc : ImageCaptureException) {
					LogUtil.print("拍照失败", exc)
					if (isActivityActive) {
						Toast.makeText(this@ServicePeopleRealActivity,
							"拍照失败",
							Toast.LENGTH_SHORT).show()
					}
				}
			})
	}

	private fun isValidFace(face : Face, imageWidth : Int, imageHeight : Int) : Boolean {
		val faceBounds = face.boundingBox
		val faceCenterX = faceBounds.centerX()
		val faceCenterY = faceBounds.centerY()
		val imageCenterX = imageWidth / 2
		val imageCenterY = imageHeight / 2

		// 计算人脸框占图片的比例
		val faceWidthRatio = faceBounds.width().toFloat() / imageWidth
		val faceHeightRatio = faceBounds.height().toFloat() / imageHeight

		// 检查人脸是否居中（允许30%的偏移）
		val centerThreshold = imageWidth * 0.8f
		val isCentered =
			abs(faceCenterX - imageCenterX) < centerThreshold && abs(faceCenterY - imageCenterY) < centerThreshold

		// 检查人脸大小是否合适（建议占据图片30%-70%的区域）
		val isProperSize = faceWidthRatio in 0.6f .. 0.7f && faceHeightRatio in 0.6f .. 0.7f

		// 检查是否是正面人脸且睁眼
		val isFrontalFace = abs(face.headEulerAngleY) < 15 && // 左右角度
				abs(face.headEulerAngleX) < 15 && // 上下角度
				abs(face.headEulerAngleZ) < 15 && // 倾斜角度
				face.rightEyeOpenProbability != null && face.leftEyeOpenProbability != null && face.rightEyeOpenProbability !! > 0.8 && face.leftEyeOpenProbability !! > 0.8

		return isCentered && isProperSize && isFrontalFace
	}

	//校正图片，解决图片可能翻转的问题
	private val rotationMatrix = Matrix()
	private fun handlerBitmap(bitmap : Bitmap, degrees : Int?) : Bitmap {
		if (degrees == null || degrees == 0) return bitmap
		rotationMatrix.reset()
		rotationMatrix.postRotate(degrees.toFloat())
		return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, rotationMatrix, true)
	}

	private fun resetDetection() {
		currentStep = 0
		isStepCompleted = false
		avatarBitmap = null
		confirmationLayout.visibility = View.GONE
		stepText.visibility = View.VISIBLE
		updateStepUI()
	}

	private fun startCamera() {
		lifecycleCameraController.setImageAnalysisAnalyzer(ContextCompat.getMainExecutor(this@ServicePeopleRealActivity),
			FaceAnalyzer { handleFaceDetection(it) })
	}

	private fun handleFaceDetection(eulerY : Float) {
		if (! isActivityActive) return

		when (currentStep) {
			0 -> {
				if (abs(eulerY) < 15) {
					if (! isStepCompleted) {
						isStepCompleted = true
						proceedToNextStep()
					}
				}
			}

			1 -> {
				if (eulerY > 15) {
					if (! isStepCompleted) {
						isStepCompleted = true
						proceedToNextStep()
					}
				}
			}

			2 -> {
				if (eulerY < - 15) {
					if (! isStepCompleted) {
						isStepCompleted = true
						proceedToNextStep()
					}
				}
			}

			3 -> {
				if (abs(eulerY) < 15) {
					if (! isStepCompleted) {
						isStepCompleted = true
						runOnUiThread {
							captureImage()
						}
					}
				}
			}
		}
	}

	private fun showConfirmation() {
		avatarBitmap?.let { bitmap ->
			Glide.with(previewImage).load(bitmap).into(previewImage)
			confirmationLayout.visibility = View.VISIBLE
			stepText.visibility = View.GONE
		} ?: run {
			AlertDialog.Builder(this).setTitle("提示")
				.setMessage("未检测到有效的人脸照片，是否重新开始检测？")
				.setPositiveButton("重新检测") { dialog, _ ->
					dialog.dismiss()
					resetDetectionProcess()
				}.setNegativeButton("取消") { dialog, _ ->
					dialog.dismiss()
					finish()
				}.setCancelable(false).show()
		}
	}

	private fun resetDetectionProcess() {
		currentStep = 0
		isStepCompleted = false
		avatarBitmap = null

		confirmationLayout.visibility = View.GONE
		stepText.visibility = View.VISIBLE
		stepText.text = steps[currentStep]

		startCamera()
	}

	private fun proceedToNextStep() {
		currentStep ++
		isStepCompleted = false
		if (currentStep < steps.size) {
			updateStepUI()
		}
	}

	private fun updateStepUI() {
		stepText.visibility = View.VISIBLE
		stepText.text = steps[currentStep]

		SpeechManager.releaseMediaPlayer()
		when (currentStep) {
			0 -> SpeechManager.playFaceCenter()
			1 -> SpeechManager.playFaceLeft()
			2 -> SpeechManager.playFaceRight()
			3 -> SpeechManager.playFaceCenter()
		}
	}

	private fun returnPhotoResult() {
		avatarBitmap?.let { bitmap ->            // 保存图片到临时文件
			val file = ImageUtils.save2Album(bitmap, CompressFormat.JPEG, 100)
			if (file?.exists() == true) {                // 创建返回结果
				val resultIntent = Intent()
				resultIntent.putExtra("path", file.absolutePath)
				setResult(RESULT_OK, resultIntent)
				finish()
			} else {
				Toast.makeText(this, "照片保存失败，请重试", Toast.LENGTH_SHORT).show()
			}
		} ?: run {
			Toast.makeText(this, "未获取到有效的人脸照片，请重试", Toast.LENGTH_SHORT).show()
		}
	}

	private fun dismissLoadingDialog() {
		loadingDialog?.dismiss()
	}

	private fun showUploadFailedDialog() {
		AlertDialog.Builder(this).setTitle("上传失败").setMessage("人脸照片上传失败，请重新识别")
			.setPositiveButton("重新识别") { dialog, _ ->
				dialog.dismiss()
				resetDetection()
			}.setNegativeButton("取消") { dialog, _ ->
				dialog.dismiss()
				finish()
			}.setCancelable(false).show()
	}

	@SuppressLint("CheckResult")
	private fun doUploadImg(file : File) {
		CommonMethod.uploadImage(file, success = {
			if (it.isNullOrBlank()) {
				ToastUtils.showLong("上传失败")
				return@uploadImage
			}
			doUpload(it)
		}, failed = {
			dismissLoadingDialog()
			showUploadFailedDialog()
		})
	}

	private fun doUpload(url : String) {
		val request = DriverFaceCompareRequest(vehicleId = GlobalData.driverInfoBean?.vehicleId,
			driverId = GlobalData.driverInfoBean?.userId,
			photoUrl = url)
		RetrofitHelper.getDefaultService().driverFaceCompare(request).subscribeOn(Schedulers.io())
			.observeOn(AndroidSchedulers.mainThread())
			.subscribe(object : BaseObserver<DriverFaceCompareBean>() {
				override fun doSuccess(it : DriverFaceCompareBean?) {
					ToastUtils.showLong("头像上传成功！")
					finish()
				}

				override fun doFailure(code : Int, msg : String?) {
					LogUtil.print("doUpload addRealAvatarActivity failed",
						"code==$msg request==$request")
					showUploadFailedDialog()
				}
			})

	}

	private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all {
		ContextCompat.checkSelfPermission(baseContext, it) == PackageManager.PERMISSION_GRANTED
	}

	override fun onRequestPermissionsResult(requestCode : Int,
		permissions : Array<String>,
		grantResults : IntArray) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults)
		if (requestCode == REQUEST_CODE_PERMISSIONS) {
			if (allPermissionsGranted()) {
				startCamera()
			} else {
				Toast.makeText(this, "需要相机权限", Toast.LENGTH_SHORT).show()
				finish()
			}
		}
	}

	override fun onResume() {
		super.onResume()
		isActivityActive = true
	}

	override fun onPause() {
		super.onPause()
		isActivityActive = false
	}

	override fun onDestroy() {
		super.onDestroy()
		isActivityActive = false
		cameraExecutor.shutdown()
	}

	private class FaceAnalyzer(private val listener : (Float) -> Unit) : ImageAnalysis.Analyzer {
		private val detector = FaceDetection.getClient(FaceDetectorOptions.Builder()
			.setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_FAST)
			.setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_NONE)
			.setClassificationMode(FaceDetectorOptions.CLASSIFICATION_MODE_NONE).build())

		@ExperimentalGetImage
		override fun analyze(imageProxy : ImageProxy) {
			val mediaImage = imageProxy.image
			if (mediaImage != null) {
				val image =
					InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)

				detector.process(image).addOnSuccessListener { faces ->
					if (faces.isNotEmpty()) {
						listener(faces[0].headEulerAngleY)
					}
				}.addOnCompleteListener {
					imageProxy.close()
				}
			} else {
				imageProxy.close()
			}
		}
	}

	companion object {
		private const val REQUEST_CODE_PERMISSIONS = 10
		private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA)
	}
}