package com.za.ui.servicing

import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import coil.compose.AsyncImage
import com.amap.api.location.AMapLocation
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import com.permissionx.guolindev.PermissionX
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.za.base.Const
import com.za.base.theme.buttonBgColor
import com.za.base.view.CommonDialog
import com.za.base.view.LoadingManager
import com.za.base.view.ReTakePhotoDialog
import com.za.bean.db.order.PhotoTemplateInfo
import com.za.bean.request.OrderPhotoOcrRecognizeRequest
import com.za.common.GlobalData
import com.za.common.log.LogUtil
import com.za.ext.getEleOrderH5Url
import com.za.ext.noDoubleClick
import com.za.ext.toJson
import com.za.net.BaseObserver
import com.za.net.CommonMethod
import com.za.net.RetrofitHelper
import com.za.room.RoomHelper
import com.za.service.location.ZdLocationManager
import com.za.servicing.R
import com.za.ui.camera.ZdCameraXActivity
import com.za.ui.h5.CommonH5Activity
import com.za.water_marker.PhotoMarkerManager
import com.za.water_marker.bean.PhotoMarkerInfo
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import java.io.File
import java.util.concurrent.Executors

@Synchronized
private fun handlerInServicingPhoto(
	context : Context,
	aMapLocation : AMapLocation?,
	path : String?,
	photoTemplateInfo : PhotoTemplateInfo,
	success : (PhotoTemplateInfo) -> Unit,
) {
	LogUtil.print("handlerPhoto", "photoTemplateInfo==${photoTemplateInfo.toJson()}")
	val time = System.currentTimeMillis().minus(photoTemplateInfo.advanceTime ?: 0L)
	val photoTemplateInfoTemp = photoTemplateInfo.copy(photoLocalPath = path,
		photoUploadPath = null,
		realTakePhotoTime = TimeUtils.getNowString(),
		photoSource = 1,
		time = TimeUtils.millis2String(time),
		lat = aMapLocation?.latitude?.toFloat(),
		lng = aMapLocation?.longitude?.toFloat(),
		address = aMapLocation?.address)
	LogUtil.print("本地照片拍好返回结果",
		photoTemplateInfoTemp.toJson() ?: photoTemplateInfoTemp.toString())
	RoomHelper.db?.photoTemplateDao()?.update(photoTemplateInfo = photoTemplateInfoTemp)
	success(photoTemplateInfoTemp)

	var localPhotoTemplateInfo = photoTemplateInfoTemp

	//当需要添加水印并且地址不为空的情况下，才添加水印
	val file =
		if (localPhotoTemplateInfo.needWaterMarker == true && ! aMapLocation?.address.isNullOrBlank()) {
			val photoMarkerInfo = PhotoMarkerInfo(localPhotoTemplateInfo.needWaterMarker,
				needShowPhoneBrand = localPhotoTemplateInfo.needShowPhoneBrand,
				path = localPhotoTemplateInfo.photoLocalPath,
				from = "（相机）",
				lat = localPhotoTemplateInfo.lat?.toDouble(),
				lng = localPhotoTemplateInfo.lng?.toDouble(),
				address = localPhotoTemplateInfo.address,
				time = localPhotoTemplateInfo.time,
				driverName = GlobalData.driverInfoBean?.userName,
				taskCode = localPhotoTemplateInfo.taskCode)
			File(PhotoMarkerManager.addPhotoMarker(context = context, photoMarkerInfo))
		} else {
			File(localPhotoTemplateInfo.photoLocalPath !!)
		}

	if (! file.exists()) {
		localPhotoTemplateInfo = localPhotoTemplateInfo.copy(photoUploadStatus = 3)
		RoomHelper.db?.photoTemplateDao()?.update(photoTemplateInfo = localPhotoTemplateInfo)
		success(localPhotoTemplateInfo)
		return
	}

	CommonMethod.uploadImage(file = file, preview = {
		localPhotoTemplateInfo = localPhotoTemplateInfo.copy(photoUploadStatus = 4,
			photoLocalWaterMarkerPath = file.absolutePath)
		RoomHelper.db?.photoTemplateDao()?.update(photoTemplateInfo = localPhotoTemplateInfo)
		success(localPhotoTemplateInfo)
	}, success = { it ->
		if (photoTemplateInfo.recognizeType == null || photoTemplateInfo.recognizeType == 0) {
			localPhotoTemplateInfo =
				localPhotoTemplateInfo.copy(photoUploadStatus = 2, photoUploadPath = it)
			RoomHelper.db?.photoTemplateDao()?.update(photoTemplateInfo = localPhotoTemplateInfo)
			success(localPhotoTemplateInfo)
			LogUtil.print("图片上传成功", it ?: "")
			return@uploadImage
		}
		ocrRecognition(localPhotoTemplateInfo, uploadPath = it, success = {
			localPhotoTemplateInfo =
				localPhotoTemplateInfo.copy(photoUploadStatus = 2, photoUploadPath = it)
			RoomHelper.db?.photoTemplateDao()?.update(photoTemplateInfo = localPhotoTemplateInfo)
			success(localPhotoTemplateInfo)
			LogUtil.print("图片上传成功", it ?: "")
		}, failed = {
			localPhotoTemplateInfo = localPhotoTemplateInfo.copy(photoUploadStatus = 7)
			RoomHelper.db?.photoTemplateDao()?.update(photoTemplateInfo = localPhotoTemplateInfo)
			success(localPhotoTemplateInfo)
			LogUtil.print("图片上传失败", it ?: "")
		})
	}, {
		localPhotoTemplateInfo = localPhotoTemplateInfo.copy(photoUploadStatus = 3)
		RoomHelper.db?.photoTemplateDao()?.update(photoTemplateInfo = localPhotoTemplateInfo)
		success(localPhotoTemplateInfo)
		LogUtil.print("图片上传失败", it ?: "")
	})
}


private fun handlerChangeBatteryPhoto(context : Context,
	aMapLocation : AMapLocation?,
	path : String?,
	photoTemplateInfo : PhotoTemplateInfo,
	success : (PhotoTemplateInfo) -> Unit) {
	LogUtil.print("handlerPhoto", "photoTemplateInfo==${photoTemplateInfo.toJson()}")
	val time = System.currentTimeMillis().minus(photoTemplateInfo.advanceTime ?: 0L)
	val photoTemplateInfoTemp = photoTemplateInfo.copy(photoLocalPath = path,
		photoUploadPath = null,
		realTakePhotoTime = TimeUtils.getNowString(),
		photoSource = 1,
		time = TimeUtils.millis2String(time),
		lat = aMapLocation?.latitude?.toFloat(),
		lng = aMapLocation?.longitude?.toFloat(),
		address = aMapLocation?.address)
	LogUtil.print("本地照片拍好返回结果",
		photoTemplateInfoTemp.toJson() ?: photoTemplateInfoTemp.toString())
	RoomHelper.db?.changeBatteryDao()?.update(photoTemplateInfo = photoTemplateInfoTemp)
	success(photoTemplateInfoTemp)

	var localPhotoTemplateInfo = photoTemplateInfoTemp
	val file =
		if (localPhotoTemplateInfo.needWaterMarker == true && ! aMapLocation?.address.isNullOrBlank()) {
			val photoMarkerInfo = PhotoMarkerInfo(localPhotoTemplateInfo.needWaterMarker,
				needShowPhoneBrand = localPhotoTemplateInfo.needShowPhoneBrand,
				path = localPhotoTemplateInfo.photoLocalPath,
				from = "（相机）",
				lat = localPhotoTemplateInfo.lat?.toDouble(),
				lng = localPhotoTemplateInfo.lng?.toDouble(),
				address = localPhotoTemplateInfo.address,
				time = localPhotoTemplateInfo.time,
				driverName = GlobalData.driverInfoBean?.userName,
				taskCode = localPhotoTemplateInfo.taskCode)
			File(PhotoMarkerManager.addPhotoMarker(context = context, photoMarkerInfo))
		} else {
			File(localPhotoTemplateInfo.photoLocalPath !!)
		}

	if (! file.exists()) {
		localPhotoTemplateInfo = localPhotoTemplateInfo.copy(photoUploadStatus = 3)
		RoomHelper.db?.changeBatteryDao()?.update(photoTemplateInfo = localPhotoTemplateInfo)
		success(localPhotoTemplateInfo)
		return
	}

	CommonMethod.uploadImage(file = file, preview = {
		localPhotoTemplateInfo = localPhotoTemplateInfo.copy(photoUploadStatus = 4,
			photoLocalWaterMarkerPath = file.absolutePath)
		RoomHelper.db?.changeBatteryDao()?.update(photoTemplateInfo = localPhotoTemplateInfo)
		success(localPhotoTemplateInfo)
	}, success = { it ->
		if (photoTemplateInfo.recognizeType == null || photoTemplateInfo.recognizeType == 0) {
			localPhotoTemplateInfo =
				localPhotoTemplateInfo.copy(photoUploadStatus = 2, photoUploadPath = it)
			RoomHelper.db?.changeBatteryDao()?.update(photoTemplateInfo = localPhotoTemplateInfo)
			success(localPhotoTemplateInfo)
			LogUtil.print("图片上传成功", it ?: "")
			return@uploadImage
		}

		ocrRecognition(localPhotoTemplateInfo, uploadPath = it, success = {
			localPhotoTemplateInfo =
				localPhotoTemplateInfo.copy(photoUploadStatus = 2, photoUploadPath = it)
			RoomHelper.db?.changeBatteryDao()?.update(photoTemplateInfo = localPhotoTemplateInfo)
			success(localPhotoTemplateInfo)
			LogUtil.print("图片上传成功", it ?: "")
		}, failed = {
			localPhotoTemplateInfo = localPhotoTemplateInfo.copy(photoUploadStatus = 7)
			RoomHelper.db?.changeBatteryDao()?.update(photoTemplateInfo = localPhotoTemplateInfo)
			success(localPhotoTemplateInfo)
			LogUtil.print("图片上传失败", it ?: "")
		})

	}, {
		localPhotoTemplateInfo = localPhotoTemplateInfo.copy(photoUploadStatus = 3)
		RoomHelper.db?.changeBatteryDao()?.update(photoTemplateInfo = localPhotoTemplateInfo)
		success(localPhotoTemplateInfo)
		LogUtil.print("图片上传失败", it ?: "")
	})
}


private fun handlerNormalPhoto(context : Context,
	aMapLocation : AMapLocation?,
	path : String?,
	photoTemplateInfo : PhotoTemplateInfo,
	success : (PhotoTemplateInfo) -> Unit) {
	LogUtil.print("handlerNormalPhoto", "photoTemplateInfo==${photoTemplateInfo.toJson()}")
	val time = System.currentTimeMillis().minus(photoTemplateInfo.advanceTime ?: 0L)
	val photoTemplateInfoTemp = photoTemplateInfo.copy(photoLocalPath = path,
		photoUploadPath = null,
		realTakePhotoTime = TimeUtils.getNowString(),
		photoSource = 1,
		photoUploadStatus = 1,
		time = TimeUtils.millis2String(time),
		lat = aMapLocation?.latitude?.toFloat(),
		lng = aMapLocation?.longitude?.toFloat(),
		address = aMapLocation?.address)
	LogUtil.print("本地照片拍好返回结果",
		photoTemplateInfoTemp.toJson() ?: photoTemplateInfoTemp.toString())
	success(photoTemplateInfoTemp)

	var localPhotoTemplateInfo = photoTemplateInfoTemp
	val file =
		if (localPhotoTemplateInfo.needWaterMarker == true && ! aMapLocation?.address.isNullOrBlank()) {
			val photoMarkerInfo = PhotoMarkerInfo(localPhotoTemplateInfo.needWaterMarker,
				needShowPhoneBrand = localPhotoTemplateInfo.needShowPhoneBrand,
				path = localPhotoTemplateInfo.photoLocalPath,
				from = "（相机）",
				lat = localPhotoTemplateInfo.lat?.toDouble(),
				lng = localPhotoTemplateInfo.lng?.toDouble(),
				address = localPhotoTemplateInfo.address,
				time = localPhotoTemplateInfo.time,
				driverName = GlobalData.driverInfoBean?.userName,
				taskCode = localPhotoTemplateInfo.taskCode)
			File(PhotoMarkerManager.addPhotoMarker(context = context, photoMarkerInfo))
		} else {
			File(localPhotoTemplateInfo.photoLocalPath !!)
		}

	if (! file.exists()) {
		localPhotoTemplateInfo = localPhotoTemplateInfo.copy(photoUploadStatus = 3)
		success(localPhotoTemplateInfo)
		return
	}

	CommonMethod.uploadImage(file = file, preview = {
		localPhotoTemplateInfo = localPhotoTemplateInfo.copy(photoUploadStatus = 4,
			photoLocalWaterMarkerPath = file.absolutePath)
		success(localPhotoTemplateInfo)
	}, success = { it ->
		if (photoTemplateInfo.recognizeType == null || photoTemplateInfo.recognizeType == 0) {
			localPhotoTemplateInfo =
				localPhotoTemplateInfo.copy(photoUploadStatus = 2, photoUploadPath = it)
			success(localPhotoTemplateInfo)
			LogUtil.print("图片上传成功", it ?: "")
			return@uploadImage
		}

		ocrRecognition(localPhotoTemplateInfo, uploadPath = it, success = {
			localPhotoTemplateInfo =
				localPhotoTemplateInfo.copy(photoUploadStatus = 2, photoUploadPath = it)
			success(localPhotoTemplateInfo)
			LogUtil.print("图片上传成功", it ?: "")
		}, failed = {
			localPhotoTemplateInfo = localPhotoTemplateInfo.copy(photoUploadStatus = 7)
			success(localPhotoTemplateInfo)
			LogUtil.print("图片上传失败", it ?: "")
		})

	}, {
		localPhotoTemplateInfo = localPhotoTemplateInfo.copy(photoUploadStatus = 3)
		success(localPhotoTemplateInfo)
		LogUtil.print("图片上传失败", it ?: "")
	})
}

private fun ocrRecognition(photoTemplateInfo : PhotoTemplateInfo,
	uploadPath : String?,
	success : () -> Unit,
	failed : (String?) -> Unit) {
	if (uploadPath.isNullOrBlank()) {
		failed("照片路径为空！")
		return
	}
	val orderPhotoOcrRecognizeRequest =
		OrderPhotoOcrRecognizeRequest(GlobalData.currentOrder?.userOrderId,
			photoTemplateInfo.recognizeType,
			uploadPath)
	RetrofitHelper.getDefaultService().orderPhotoOcrRecognize(orderPhotoOcrRecognizeRequest)
		.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
		.subscribe(object : BaseObserver<String>() {
			override fun doSuccess(it : String?) {
				success()
			}

			override fun doFailure(code : Int, msg : String?) {
				failed(msg)
			}
		})
}


@Composable
fun InServicingPhotoView(modifier : Modifier = Modifier,
	photoTemplateInfo : PhotoTemplateInfo,
	index : Int? = null,
	success : (PhotoTemplateInfo) -> Unit) {
	Column(modifier = modifier
        .fillMaxWidth()
        .padding(horizontal = 10.dp)
        .background(color = Color.White, shape = RoundedCornerShape(6.dp))
        .padding(10.dp)) {

		if (photoTemplateInfo.photoType == 2) {
			InServicingEleView()
			return@Column
		}

		Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
			if (index != null) {
				Box(modifier = Modifier
                    .size(20.dp)
                    .background(color = buttonBgColor, shape = RoundedCornerShape(4.dp)),
					contentAlignment = Alignment.Center) {
					Text(text = "$index",
						fontWeight = FontWeight.Medium,
						style = TextStyle.Default.copy(),
						color = Color.White,
						fontSize = 14.sp)
				}
			}

			Spacer(modifier = Modifier.width(5.dp))

			Text(text = photoTemplateInfo.imageTitle ?: "其他",
				fontWeight = FontWeight.Medium,
				fontSize = 14.sp,
				color = Color.Black)
			Spacer(modifier = Modifier.width(5.dp))
			if (photoTemplateInfo.doHaveFilm == 1) {
				Text(text = "* 必拍",
					color = Color.Red,
					fontSize = 12.sp,
					fontWeight = FontWeight.Medium)
			}
			Spacer(modifier = Modifier.weight(1f))

			Text(text = photoTemplateInfo.convertPhotoStatusStr(status = photoTemplateInfo.photoUploadStatus
				?: 0),
				fontSize = 12.sp,
				fontWeight = FontWeight.Medium,
				color = photoTemplateInfo.getPhotoStatusColor())

			Spacer(modifier = Modifier.width(10.dp))
		}
		Spacer(modifier = Modifier.height(10.dp))

		InServicingPhotoItemView(modifier = Modifier.fillMaxWidth(),
			photoTemplateInfo = photoTemplateInfo,
			success = { success(it) })

		if (! photoTemplateInfo.imageDescription.isNullOrBlank()) {
			Spacer(modifier = Modifier.height(10.dp))
			Column(modifier = Modifier
                .fillMaxWidth()
                .background(color = Color(0xFFFEF5EB), shape = (RoundedCornerShape(4.dp)))
                .padding(horizontal = 10.dp, vertical = 2.dp),
				horizontalAlignment = Alignment.Start) {
				Text(text = "提示:",
					fontSize = 12.sp,
					fontWeight = FontWeight.Medium,
					color = Color(0xFFFE5656))
				Text(text = photoTemplateInfo.imageDescription,
					color = Color.Black,
					fontSize = 11.sp,
					lineHeight = TextUnit(15f, TextUnitType.Sp))
			}
		}
	}
}


@Composable
fun InServicingPhotoViewIsCanClick(modifier : Modifier = Modifier,
	photoTemplateInfo : PhotoTemplateInfo,
	index : Int? = null,
	isCanClick : Boolean = true,
	success : (PhotoTemplateInfo) -> Unit) {
	Column(modifier = modifier
        .fillMaxWidth()
        .padding(horizontal = 10.dp)
        .background(color = Color.White, shape = RoundedCornerShape(6.dp))
        .padding(10.dp)) {

		if (photoTemplateInfo.photoType == 2) {
			InServicingEleView()
			return
		}

		Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
			if (index != null) {
				Box(modifier = Modifier
                    .size(20.dp)
                    .background(color = buttonBgColor, shape = RoundedCornerShape(4.dp)),
					contentAlignment = Alignment.Center) {
					Text(text = "$index",
						fontWeight = FontWeight.Medium,
						style = TextStyle.Default.copy(),
						color = Color.White,
						fontSize = 14.sp)
				}
			}

			Spacer(modifier = Modifier.width(5.dp))

			Text(text = photoTemplateInfo.imageTitle ?: "其他",
				fontWeight = FontWeight.Medium,
				maxLines = 1,
				overflow = TextOverflow.Ellipsis,
				fontSize = 14.sp,
				color = Color.Black)
			Spacer(modifier = Modifier.width(5.dp))
			if (photoTemplateInfo.doHaveFilm == 1 && isCanClick) {
				Text(text = "* 必拍",
					color = Color.Red,
					fontSize = 12.sp,
					fontWeight = FontWeight.Medium)
			}
			Spacer(modifier = Modifier.weight(1f))

			Text(text = photoTemplateInfo.convertPhotoStatusStr(status = photoTemplateInfo.photoUploadStatus
				?: 0),
				fontSize = 12.sp,
				fontWeight = FontWeight.Medium,
				color = photoTemplateInfo.getPhotoStatusColor())

			Spacer(modifier = Modifier.width(10.dp))

		}
		Spacer(modifier = Modifier.height(10.dp))

		InServicingPhotoItemView(modifier = Modifier.fillMaxWidth(),
			photoTemplateInfo = photoTemplateInfo,
			isCanClick = isCanClick,
			success = { success(it) })

		if (! photoTemplateInfo.imageDescription.isNullOrBlank()) {
			Spacer(modifier = Modifier.height(10.dp))
			Column(modifier = Modifier
                .fillMaxWidth()
                .background(color = Color(0xFFFEF5EB), shape = (RoundedCornerShape(4.dp)))
                .padding(horizontal = 10.dp, vertical = 2.dp),
				horizontalAlignment = Alignment.Start) {
				Text(text = "提示:",
					fontSize = 12.sp,
					fontWeight = FontWeight.Medium,
					color = Color(0xFFFE5656))
				Text(text = photoTemplateInfo.imageDescription,
					color = Color.Black,
					fontSize = 11.sp,
					lineHeight = TextUnit(15f, TextUnitType.Sp))
			}
		}
	}
}


@Composable
fun InServicingPhotoWithoutTitleView(modifier : Modifier = Modifier,
	photoTemplateInfo : PhotoTemplateInfo,
	index : Int? = null,
	success : (PhotoTemplateInfo) -> Unit) {
	Column(modifier = modifier
        .fillMaxWidth()
        .padding(horizontal = 10.dp)
        .background(color = Color.White, shape = RoundedCornerShape(6.dp))
        .padding(10.dp)) {

		if (photoTemplateInfo.photoType == 2) {
			InServicingEleView()
			return
		}

		Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
			if (index != null) {
				Box(modifier = Modifier
                    .size(20.dp)
                    .background(color = buttonBgColor, shape = RoundedCornerShape(4.dp)),
					contentAlignment = Alignment.Center) {
					Text(text = "$index",
						fontWeight = FontWeight.Medium,
						style = TextStyle.Default.copy(),
						color = Color.White,
						fontSize = 14.sp)
				}
			}

			Spacer(modifier = Modifier.width(5.dp))
			if (photoTemplateInfo.doHaveFilm == 1) {
				Text(text = "* 必拍",
					color = Color.Red,
					fontSize = 12.sp,
					fontWeight = FontWeight.Medium)
			}
			Spacer(modifier = Modifier.weight(1f))

			Text(text = photoTemplateInfo.convertPhotoStatusStr(status = photoTemplateInfo.photoUploadStatus
				?: 0),
				fontSize = 12.sp,
				fontWeight = FontWeight.Medium,
				color = photoTemplateInfo.getPhotoStatusColor())

			Spacer(modifier = Modifier.width(10.dp))
		}
		Spacer(modifier = Modifier.height(10.dp))

		InServicingPhotoItemView(modifier = Modifier.fillMaxWidth(),
			photoTemplateInfo = photoTemplateInfo,
			success = { success(it) })
	}
}

@Composable
fun InServicingPhotoItemView(modifier : Modifier = Modifier,
	photoTemplateInfo : PhotoTemplateInfo,
	isCanClick : Boolean = true,
	success : (PhotoTemplateInfo) -> Unit) {
	val context = LocalContext.current
	val aMapLocation = remember { mutableStateOf<AMapLocation?>(null) }
	val executors = Executors.newFixedThreadPool(4)
	val getResult =
		rememberLauncherForActivityResult(contract = ActivityResultContracts.StartActivityForResult()) { it ->
			if (it.resultCode == Activity.RESULT_OK) {
				val value = it.data?.getStringExtra("path")
				LogUtil.print("takePhoto", "path==$value")
				if (value.isNullOrBlank()) {
					ToastUtils.showLong("照片路径为空，请重新拍摄！")
					return@rememberLauncherForActivityResult
				}
				executors.execute {
					when (photoTemplateInfo.myCustomPhotoType) {
						Const.PhotoType.InServicing -> handlerInServicingPhoto(context,
							aMapLocation.value,
							value,
							photoTemplateInfo) { success(it) }

						Const.PhotoType.ChangeBattery -> handlerChangeBatteryPhoto(context,
							aMapLocation.value,
							value,
							photoTemplateInfo) { success(it) }

						Const.PhotoType.NormalImage -> handlerNormalPhoto(context,
							aMapLocation.value,
							value,
							photoTemplateInfo) { success(it) }
					}
				}
			}
		}

	val showPreviewPhotoDialog = remember { mutableStateOf(false) }
	if (showPreviewPhotoDialog.value) {
		CommonDialog(title = photoTemplateInfo.imageTitle ?: "预览",
			confirm = { showPreviewPhotoDialog.value = false },
			cancelText = "取消",
			confirmText = "确定",
			cancelEnable = true,
			cancel = {
				showPreviewPhotoDialog.value = false
			},
			dismiss = {
				showPreviewPhotoDialog.value = false
			},
			content = {
				Box(modifier = Modifier
                    .fillMaxWidth()
                    .height(300.dp),
					contentAlignment = Alignment.Center) {
					AsyncImage(model = photoTemplateInfo.getFormatPhotoUrl(),
						contentDescription = "",
						modifier = Modifier.fillMaxSize(),
						contentScale = ContentScale.FillWidth)
				}
			})
	}

	//重拍弹窗
	val showReTakePhotoDialog = remember { mutableStateOf(false) }
	if (showReTakePhotoDialog.value) {
		ReTakePhotoDialog(title = photoTemplateInfo.imageTitle ?: "预览",
			confirm = {
				showReTakePhotoDialog.value = false
				if (! PermissionX.isGranted(context,
						android.Manifest.permission.ACCESS_FINE_LOCATION)
				) {
					ToastUtils.showShort("定位权限未开启！")
					return@ReTakePhotoDialog
				}
				LoadingManager.showLoading()
				ZdLocationManager.getSingleLocation(isNeedAddress = true, success = {
					LoadingManager.hideLoading()
					aMapLocation.value = it
					val intent = Intent(context, ZdCameraXActivity::class.java)
					getResult.launch(intent)
				}, failed = {
					LoadingManager.hideLoading()
					aMapLocation.value = GlobalData.currentLocation
					val intent = Intent(context, ZdCameraXActivity::class.java)
					getResult.launch(intent)
					ToastUtils.showShort(it)
					LogUtil.print("上传图片定位获取失败",
						"使用全局定位，location==${GlobalData.currentLocation.toJson()}")
				})
			},
			cancel = {
				showReTakePhotoDialog.value = false
			},
			againSubmit = {
				showReTakePhotoDialog.value = false
				LoadingManager.showLoading()
				ZdLocationManager.getSingleLocation(isNeedAddress = true, success = { it ->
					LoadingManager.hideLoading()
					when (photoTemplateInfo.myCustomPhotoType) {
						Const.PhotoType.InServicing -> handlerInServicingPhoto(context,
							it,
							photoTemplateInfo.photoLocalPath,
							photoTemplateInfo) { success(it) }

						Const.PhotoType.ChangeBattery -> handlerChangeBatteryPhoto(context,
							it,
							photoTemplateInfo.photoLocalPath,
							photoTemplateInfo) { success(it) }
					}
				}, failed = {
					LoadingManager.hideLoading()
					aMapLocation.value = GlobalData.currentLocation
					val intent = Intent(context, ZdCameraXActivity::class.java)
					getResult.launch(intent)
					ToastUtils.showShort(it)
					LogUtil.print("上传图片定位获取失败",
						"使用全局定位，location==${GlobalData.currentLocation.toJson()}")
				})
			},
			dismiss = {
				showReTakePhotoDialog.value = false
			},
			path = photoTemplateInfo.photoLocalPath,
			showAgain = photoTemplateInfo.photoUploadPath.isNullOrBlank())
	}

	Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) {
		Box(contentAlignment = Alignment.TopStart, modifier = Modifier
            .weight(1f)
            .height(100.dp)) {
			if (photoTemplateInfo.myCustomPhotoType == Const.PhotoType.ChangeBattery) {
				AsyncImage(model = photoTemplateInfo.getFormatPhotoUrl()?.toIntOrNull(),
					contentDescription = "",
					modifier = Modifier
                        .fillMaxSize()
                        .clickable { showPreviewPhotoDialog.value = true }
                        .clip(shape = RoundedCornerShape(3.dp)),
					contentScale = ContentScale.FillBounds)
			} else {
				AsyncImage(model = photoTemplateInfo.getFormatPhotoUrl(),
					contentDescription = "",
					modifier = Modifier
                        .fillMaxSize()
                        .clickable { showPreviewPhotoDialog.value = true }
                        .clip(shape = RoundedCornerShape(3.dp)),
					contentScale = ContentScale.FillBounds)
			}

			AsyncImage(model = R.drawable.sv_photo_example,
				contentDescription = "",
				modifier = Modifier.size(52.dp, 14.dp),
				contentScale = ContentScale.FillWidth)
		}

		Spacer(modifier = Modifier.width(10.dp))
		Box(modifier = Modifier
            .weight(1f)
            .height(100.dp)) {
			AsyncImage(model = photoTemplateInfo.photoLocalPath ?: photoTemplateInfo.photoUploadPath
			?: R.drawable.sv_servicing_take_photo,
				contentDescription = "",
				modifier = Modifier
                    .fillMaxSize()
                    .clickable {
                        if (! isCanClick) {
                            return@clickable
                        }
                        if (photoTemplateInfo.photoLocalPath.isNullOrBlank()) {
                            if (! PermissionX.isGranted(context,
                                    android.Manifest.permission.ACCESS_FINE_LOCATION)
                            ) {
                                ToastUtils.showShort("定位权限未开启！")
                                return@clickable
                            }
                            LoadingManager.showLoading()
                            ZdLocationManager.getSingleLocation(isNeedAddress = true, success = {
                                LoadingManager.hideLoading()
                                aMapLocation.value = it
                                val intent = Intent(context, ZdCameraXActivity::class.java)
                                getResult.launch(intent)
                            }, failed = {
                                LoadingManager.hideLoading()
                                aMapLocation.value = GlobalData.currentLocation
                                val intent = Intent(context, ZdCameraXActivity::class.java)
                                getResult.launch(intent)
                                ToastUtils.showShort(it)
                                LogUtil.print("上传图片定位获取失败",
                                    "使用全局定位，location==${GlobalData.currentLocation.toJson()}")
                            })
                            return@clickable
                        }
                        showReTakePhotoDialog.value = true
                    }
                    .clip(shape = RoundedCornerShape(3.dp)),
				contentScale = ContentScale.FillBounds)
		}
	}
}

@Composable
private fun InServicingEleView() {
	val context = LocalContext.current
	val webView = WebView(context)
	Box(modifier = Modifier
        .fillMaxWidth()
        .height(200.dp)) {
		AndroidView(modifier = Modifier
            .fillMaxWidth()
            .height(200.dp), factory = {
			webView.webChromeClient = WebChromeClient()
			val webSetting = webView.settings
			webSetting.allowFileAccess = true
			webSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
			webSetting.setSupportZoom(true)
			webSetting.builtInZoomControls = true
			webSetting.useWideViewPort = true
			webSetting.loadWithOverviewMode = true
			webSetting.setSupportMultipleWindows(false)
			webSetting.setAppCacheEnabled(true)
			webSetting.domStorageEnabled = true
			webSetting.javaScriptEnabled = true
			webSetting.setGeolocationEnabled(true)
			webSetting.setAppCacheMaxSize(Long.MAX_VALUE)
			webSetting.blockNetworkImage = false // 解决图片不显示
			webSetting.mixedContentMode = 0
			webSetting.setAppCachePath(context.getDir("appcache", 0).path)
			webSetting.databasePath = context.getDir("databases", 0).path
			webView
		}, update = { webView.loadUrl(GlobalData.currentOrder?.getEleOrderH5Url()) })
		Box(Modifier
            .fillMaxWidth()
            .height(200.dp)
            .noDoubleClick {
                CommonH5Activity.goH5Activity(context,
                    url = GlobalData.currentOrder?.getEleOrderH5Url(),
                    title = "电子工单",
                    isCanBack = true)
            })
	}
}