package com.za.ui.servicing.ele_sign

import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.blankj.utilcode.util.TimeUtils
import com.za.base.theme.black65
import com.za.base.view.CommonButton
import com.za.base.view.CommonDialog
import com.za.common.GlobalData
import com.za.common.util.ServicingSpeechManager
import com.za.ext.finish
import com.za.ext.goStatusPage
import com.za.servicing.R
import com.za.ui.servicing.view.InServicingHeadView
import com.za.ui.view.SignatureView
import kotlin.math.ceil

@Composable
fun EleSignScreen(vm : EleSignVm = viewModel()) {
	val context = LocalContext.current
	val uiState = vm.uiState.collectAsStateWithLifecycle()
	LaunchedEffect(key1 = Unit) {
		vm.dispatch(EleSignVm.Action.Init)
		ServicingSpeechManager.playOrderCustomSign(context)
	}

	if (uiState.value.isGoNextPageDialog == true) {
		CommonDialog(cancelText = "取消",
			confirmText = "前往下一步",
			title = "是否前往下一步？",
			cancelEnable = true,
			cancel = {
				vm.dispatch(EleSignVm.Action.UpdateState(uiState.value.copy(isGoNextPageDialog = false)))
			},
			dismiss = {
				vm.dispatch(EleSignVm.Action.UpdateState(uiState.value.copy(isGoNextPageDialog = false)))
			},
			confirm = {
				vm.dispatch(EleSignVm.Action.UpdateState(uiState.value.copy(isGoNextPageDialog = false)))
				vm.dispatch(EleSignVm.Action.Upload)
			})
	}

	if (uiState.value.goNextPage != null) {
		uiState.value.orderInfo?.goStatusPage(context)
		context.finish()
	}

	//离线操作框
	if (uiState.value.showOfflineDialog == true) {
		CommonDialog(cancelText = "取消",
			confirmText = "离线上传",
			title = "上传失败，是否进行离线提交？",
			cancelEnable = true,
			cancel = {
				vm.dispatch(EleSignVm.Action.UpdateState(uiState.value.copy(showOfflineDialog = false)))
			},
			dismiss = {
				vm.dispatch(EleSignVm.Action.UpdateState(uiState.value.copy(showOfflineDialog = false)))
			},
			confirm = {
				vm.dispatch(EleSignVm.Action.UpdateState(uiState.value.copy(showOfflineDialog = false)))
				vm.dispatch(EleSignVm.Action.UploadOffline)
			})
	}

	Scaffold(topBar = {
		InServicingHeadView(title = "车况检查表",
			orderInfo = uiState.value.orderInfo,
			onBack = { context.finish() })
	}, bottomBar = {
		CommonButton(text = "签名完成，开始作业") {
			vm.dispatch(EleSignVm.Action.UpdateState(uiState.value.copy(isGoNextPageDialog = true)))
		}
	}) { it ->
		LazyColumn(modifier = Modifier
			.fillMaxWidth()
			.padding(it)
			.padding(horizontal = 10.dp)) {
			item {
				Spacer(modifier = Modifier.height(10.dp))
				Row(modifier = Modifier.fillMaxWidth(),
					verticalAlignment = Alignment.Bottom,
					horizontalArrangement = Arrangement.SpaceBetween) {
					AsyncImage(model = R.mipmap.ic_company_brand,
						contentDescription = "",
						modifier = Modifier.size(86.dp, 25.dp),
						contentScale = ContentScale.FillWidth)
					Spacer(modifier = Modifier.weight(1f))
					Text(text = "日期:${
						TimeUtils.millis2String(System.currentTimeMillis(), "yyyy-MM-dd")
					}", color = Color.Black, fontWeight = FontWeight.Normal, fontSize = 11.sp)
				}
				Spacer(modifier = Modifier.height(5.dp))
			}

			item {
				Column(modifier = Modifier
					.fillMaxWidth()
					.border(0.5.dp, color = Color(0xFF989898))
					.padding(10.dp)) {
					Text(text = "一、车辆信息",
						color = Color.Black,
						fontWeight = FontWeight.SemiBold,
						fontSize = 12.sp)

					Spacer(modifier = Modifier.height(5.dp))
					Row(modifier = Modifier.fillMaxWidth(),
						verticalAlignment = Alignment.CenterVertically) {

						Text(text = "车牌号：", fontSize = 12.sp, color = black65)
						Spacer(modifier = Modifier.width(5.dp))
						Text(text = GlobalData.currentOrder?.carNo ?: "",
							textDecoration = TextDecoration.Underline,
							fontSize = 12.sp,
							fontWeight = FontWeight.Medium,
							color = Color.Black)

						Spacer(modifier = Modifier.weight(1f))

						Text(text = "车架号后6位：", fontSize = 12.sp, color = black65)
						Spacer(modifier = Modifier.width(5.dp))
						Text(text = uiState.value.eleWorkOrderBean?.carVin ?: "",
							textDecoration = TextDecoration.Underline,
							fontSize = 12.sp,
							fontWeight = FontWeight.Medium,
							color = Color.Black)
					}

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

					Row(modifier = Modifier.fillMaxWidth(),
						verticalAlignment = Alignment.CenterVertically) {

						Text(text = "救援类型：", fontSize = 12.sp, color = black65)
						Spacer(modifier = Modifier.width(5.dp))
						Text(text = uiState.value.eleWorkOrderBean?.orderType ?: "",
							textDecoration = TextDecoration.Underline,
							fontSize = 12.sp,
							fontWeight = FontWeight.Medium,
							color = Color.Black)

					}

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

					Row(modifier = Modifier.fillMaxWidth(),
						verticalAlignment = Alignment.CenterVertically) {

						Text(text = "车辆损伤情况：", fontSize = 12.sp, color = black65)
						Spacer(modifier = Modifier.width(5.dp))
						Text(text = "有损伤".takeIf { uiState.value.eleWorkOrderBean?.hasBad == true }
							?: "无损伤",
							textDecoration = TextDecoration.Underline,
							fontSize = 12.sp,
							fontWeight = FontWeight.Medium,
							color = Color.Black)
					}

					if (! uiState.value.damagePhoto.isNullOrEmpty()) {
						val height = uiState.value.damagePhoto?.size?.div(3.0) ?: 1
						LazyVerticalGrid(modifier = Modifier
							.fillMaxWidth()
							.height(80.times(ceil(height.toDouble())).dp),
							columns = GridCells.Fixed(3)) {
							items(items = uiState.value.damagePhoto !!) { item ->
								Box(modifier = Modifier
									.size(110.dp, 76.dp)
									.padding(5.dp),
									contentAlignment = Alignment.BottomCenter) {
									AsyncImage(model = item.serverPath.takeIf { item.path.isNullOrBlank() }
										?: item.path,
										contentDescription = "",
										modifier = Modifier.fillMaxSize(),
										contentScale = ContentScale.FillWidth)
								}
							}
						}
					}
				}

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

			item {

			}

			item {
				Column(modifier = Modifier
					.fillMaxWidth()
					.border(0.5.dp, color = Color(0xFF989898))
					.padding(10.dp)) {
					Row {
						Text(text = "二、服务须知",
							color = Color.Black,
							fontWeight = FontWeight.SemiBold,
							fontSize = 12.sp)
						Text(text = "（请顾客认证阅读，并在理解且无异议后签字确认）",
							color = Color.Red,
							fontWeight = FontWeight.SemiBold,
							fontSize = 10.sp)
					}

					Box(modifier = Modifier
						.fillMaxWidth()
						.height(250.dp)
						.verticalScroll(rememberScrollState())) {
						Text(text = uiState.value.eleWorkOrderBean?.serviceContent.takeIf { ! uiState.value.eleWorkOrderBean?.serviceContent.isNullOrBlank() }
							?: context.getString(R.string.service_content),
							fontSize = 11.sp,
							color = Color(0xE6252525))
					}

					Spacer(modifier = Modifier.height(10.dp))
					Row(verticalAlignment = Alignment.CenterVertically) {
						AsyncImage(model = R.drawable.sv_star,
							contentDescription = "",
							modifier = Modifier.size(15.dp))
						Spacer(modifier = Modifier.width(5.dp))
						Text(text = "客户对上述内容知晓并接受，签字准许实施救援服务。",
							color = Color.Red,
							fontWeight = FontWeight.Bold,
							fontSize = 10.sp)
					}
					Spacer(modifier = Modifier.height(10.dp))
					Text(text = "困境救援案件，为了完成救援而导致的不可避免的车辆损伤，客户自行承担此类风险和损失。",
						color = Color.Black,
						fontWeight = FontWeight.Bold,
						fontSize = 10.sp)
					Spacer(modifier = Modifier.height(10.dp))
					Row(verticalAlignment = Alignment.CenterVertically) {
						Text(text = "客户签名:",
							fontSize = 10.sp,
							fontWeight = FontWeight.Bold,
							color = Color.Black)
						Text(text = "(正楷)",
							fontSize = 8.sp,
							fontWeight = FontWeight.Bold,
							color = Color.Red)
						Spacer(modifier = Modifier.width(5.dp))
						SignatureView(serverPath = uiState.value.eleWorkOrderBean?.serverCustomSignPath
							?: uiState.value.eleWorkOrderBean?.localCustomSignPath, success = {
							if (it.isNullOrBlank()) {
								return@SignatureView
							}
							vm.dispatch(EleSignVm.Action.UploadSignature(it))
						})
					}
				}
			}
		}
	}
}


