package com.za.ui.main

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.tooling.preview.Preview
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.permissionx.guolindev.PermissionX
import com.za.base.BaseActivity
import com.za.common.GlobalData
import com.za.common.log.LogUtil
import com.za.ext.goStatusPage
import com.za.servicing.R

class ServiceLauncherActivity : BaseActivity() {

	// 添加设置页面返回结果处理
	private val settingsLauncher =
		registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { // 从设置页面返回后，重新检查权限并尝试导航
			checkPermissionsAndNavigate(true)
		}

	@Composable
	override fun ContentView() {
		LaunchedEffect(key1 = Unit) {
			checkPermissionsAndNavigate()
		}
		LauncherScreen()
	}

	private fun checkPermissionsAndNavigate(fromSettings : Boolean = false) {
		val permissions = getRequiredPermissions()

		// 首先检查是否已经拥有所有基础权限
		if (permissions.all { PermissionX.isGranted(this, it) }) { // 检查后台定位权限
			checkBackgroundLocation(fromSettings)
			return
		}

		// 请求基础权限
		PermissionX.init(this).permissions(permissions)
			.onExplainRequestReason { scope, deniedList ->
				val message = buildPermissionMessage(deniedList)
				scope.showRequestReasonDialog(deniedList, message, "确定", "取消")
			}.onForwardToSettings { scope, deniedList ->
				scope.showForwardToSettingsDialog(deniedList,
					"您需要在设置中手动授予所有权限才能使用应用",
					"去设置",
					"取消")
			}.request { allGranted, _, _ ->
				if (allGranted) { // 基础权限获取成功后，请求后台定位权限
					checkBackgroundLocation(fromSettings)
				} else {
					ToastUtils.showLong("请授予所有必需的权限才能使用应用")
					finish()
				}
			}
	}

	private fun checkBackgroundLocation(fromSettings : Boolean = false) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // 检查是否有前台定位权限
			val hasForegroundLocation =
				PermissionX.isGranted(this, Manifest.permission.ACCESS_FINE_LOCATION)
			val hasBackgroundLocation =
				PermissionX.isGranted(this, Manifest.permission.ACCESS_BACKGROUND_LOCATION)

			if (hasForegroundLocation && hasBackgroundLocation) {
				navigateToNextScreen()
				return
			}

			// 如果是从设置页面返回，且已经有前台权限，直接导航（即使没有后台权限也允许使用）
			if (fromSettings && hasForegroundLocation) {
				navigateToNextScreen()
				return
			}

			// 如果已经有前台权限但没有后台权限，直接跳转到设置页面
			if (hasForegroundLocation) {
				openAppSettings("请在设置中将位置权限设置为【始终允许】")
				return
			}

			// 如果连前台权限都没有，先请求前台权限
			PermissionX.init(this).permissions(Manifest.permission.ACCESS_FINE_LOCATION)
				.onExplainRequestReason { scope, deniedList ->
					scope.showRequestReasonDialog(deniedList,
						"需要位置权限来确定您的当前位置，以便为您提供准确的服务",
						"确定",
						"取消")
				}.request { allGranted, _, _ ->
					if (allGranted) { // 获得前台权限后，引导用户去设置页面开启后台权限
						openAppSettings("请在设置中将位置权限设置为【始终允许】")
					} else {
						ToastUtils.showLong("需要位置权限才能使用应用")
						finish()
					}
				}
		} else { // Android 10以下版本不需要特别申请后台定位权限
			navigateToNextScreen()
		}
	}

	private fun openAppSettings(message : String) {
		ToastUtils.showLong(message)
		try {
			val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
				data = Uri.fromParts("package", packageName, null)
				addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
			}
			settingsLauncher.launch(intent)
		} catch (e : Exception) {
			ToastUtils.showLong("无法打开应用设置页面，请手动前往设置")
			finish()
		}
	}

	private fun buildPermissionMessage(permissions : List<String>) : String {
		return when {
			permissions.contains(Manifest.permission.ACCESS_FINE_LOCATION) -> "需要位置权限来确定您的当前位置，以便为您提供准确的服务"

			permissions.contains(Manifest.permission.CAMERA) -> "需要相机权限来拍摄照片和扫描二维码"

			permissions.contains(Manifest.permission.RECORD_AUDIO) -> "需要录音权限来进行语音通话"

			permissions.any {
				it in listOf(Manifest.permission.READ_EXTERNAL_STORAGE,
					Manifest.permission.READ_MEDIA_IMAGES,
					Manifest.permission.READ_MEDIA_VIDEO)
			} -> "需要存储权限来保存必要的文件和图片"

			else -> "这些权限是应用正常运行所必需的"
		}
	}

	private fun getRequiredPermissions() : List<String> = buildList { // 基础权限
		add(Manifest.permission.ACCESS_FINE_LOCATION)
		add(Manifest.permission.CAMERA)
		add(Manifest.permission.CALL_PHONE)
		add(Manifest.permission.RECORD_AUDIO)
		add(Manifest.permission.READ_CALL_LOG)

		// 存储权限适配优化
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
			add(Manifest.permission.POST_NOTIFICATIONS)
			add(Manifest.permission.READ_MEDIA_IMAGES)
			add(Manifest.permission.READ_MEDIA_VIDEO)
		} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { // Android 10+ 使用分区存储，不再需要 WRITE_EXTERNAL_STORAGE
			add(Manifest.permission.READ_EXTERNAL_STORAGE)
			add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
		} else { // Android 9以下保留完整存储权限
			add(Manifest.permission.READ_EXTERNAL_STORAGE)
			add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
		}
	}

	private fun navigateToNextScreen() {
		if (GlobalData.isMaster) {
			GlobalData.currentOrder?.goStatusPage(this)
			return
		}
		val driverName = intent.getStringExtra("driverName")
		val driverPhone = intent.getStringExtra("driverPhone")
		val taskCode = intent.getStringExtra("taskCode")
		val rescueVehicle = intent.getStringExtra("rescueVehicle")
		if (driverName.isNullOrBlank() || driverPhone.isNullOrBlank() || taskCode.isNullOrBlank() || rescueVehicle.isNullOrBlank()) {
			ToastUtils.showLong("缺少必要参数，请重新启动应用")
			LogUtil.print("navigateToNextScreen",
				"driverName=$driverName driverPhone=$driverPhone taskCode=$taskCode rescueVehicle=$rescueVehicle")
			Log.e("navigateToNextScreen",
				"driverName=$driverName driverPhone=$driverPhone taskCode=$taskCode rescueVehicle=$rescueVehicle")
			finish()
			return
		}
		ServicingMainActivity.goToMain(
			this,
			driverName = driverName,
			driverPhone = driverPhone,
			taskCode = taskCode,
			rescueVehicle = rescueVehicle,
		)
	}
}

@Preview
@Composable
private fun LauncherScreen() {
	Scaffold { paddingValues ->
		Box(modifier = Modifier
			.fillMaxSize()
			.padding(paddingValues),
			contentAlignment = Alignment.Center) {
			AsyncImage(model = R.mipmap.ic_launcher,
				contentDescription = "Launch Screen Background",
				modifier = Modifier.fillMaxSize(),
				contentScale = ContentScale.FillBounds)
		}
	}
}
