package com.za.ui.servicing.order_confirm.real_order_confirm

import androidx.compose.foundation.background
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.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
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.draw.alpha
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.za.base.Const
import com.za.base.theme.black5
import com.za.base.theme.black65
import com.za.base.view.CommonButton
import com.za.bean.db.order.PhotoTemplateInfo
import com.za.common.GlobalData
import com.za.common.util.ServicingSpeechManager
import com.za.ext.finish
import com.za.ui.servicing.InServicingPhotoItemView
import com.za.ui.servicing.InServicingPhotoView
import com.za.ui.servicing.InServicingPhotoWithoutTitleView
import com.za.ui.servicing.view.InServicingHeadView

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

	if (uiState.value.goNextPage != null) {
		context.finish()
	}
	Scaffold(topBar = {
		InServicingHeadView(title = "结算信息",
			orderInfo = uiState.value.orderInfo,
			onBack = { context.finish() })
	}, bottomBar = {
		CommonButton(text = "提交结算信息") {
			vm.dispatch(OrderConfirmVm.Action.Submit)
		}
	}) { it ->
		Column(modifier = Modifier
			.fillMaxSize()
			.verticalScroll(rememberScrollState())
			.padding(it)) {
			Box(modifier = Modifier
				.fillMaxWidth()
				.padding(10.dp),
				contentAlignment = Alignment.CenterStart) {
				Text(text = "结算类型:  ${uiState.value.orderInfo?.settleTypeStr ?: ""}",
					fontSize = 13.sp,
					fontWeight = FontWeight.Medium,
					color = Color.Black)
			}
			BaseFeeView(flowType = uiState.value.orderInfo?.flowType ?: 0,
				startPrice = uiState.value.startPrice,
				unitPrice = uiState.value.unitKmPrice,
				overKm = uiState.value.overKm,
				abKm = uiState.value.abKm,
				bcKm = uiState.value.bcKm,
				dispatch = { vm.dispatch(it) })
			Spacer(modifier = Modifier.height(10.dp))
			AuxiliaryFeeView(dilemmaFee = uiState.value.dilemmaFee,
				basementFee = uiState.value.basementFee,
				abroadFee = uiState.value.abRoadFee,
				bcRoadFee = uiState.value.bcRoadFee,
				photoList = uiState.value.aBAndBCPhotos,
				updatePhotoTemplate = { item ->
					vm.dispatch(OrderConfirmVm.Action.UpdatePhotoTemplate(item))
				},
				dispatch = { vm.dispatch(it) })
			Spacer(modifier = Modifier.height(10.dp))
			uiState.value.photoTemplateList?.forEachIndexed { index, photoTemplateInfo ->
				InServicingPhotoView(photoTemplateInfo = photoTemplateInfo,
					index = index + 1,
					success = { item ->
						vm.dispatch(OrderConfirmVm.Action.UpdatePhotoTemplate(item))
					})
				Spacer(modifier = Modifier.height(10.dp))
			}
		}
	}
}

@Composable
fun BaseFeeView(flowType : Int,
	startPrice : Int?,
	unitPrice : Int?,
	overKm : Int?,
	abKm : Int?,
	bcKm : Int?,
	dispatch : (OrderConfirmVm.Action) -> Unit) {
	Column(modifier = Modifier
		.fillMaxWidth()
		.padding(horizontal = 10.dp)
		.background(color = Color.White, shape = RoundedCornerShape(6.dp))
		.padding(10.dp)) {
		Text(text = "基本费用",
			fontSize = 14.sp,
			fontWeight = FontWeight.Medium,
			color = Color.Black)
		HorizontalDivider(modifier = Modifier
			.fillMaxWidth()
			.padding(vertical = 5.dp),
			color = black5)
		if (GlobalData.driverInfoBean?.supplierType == Const.CHILD_COMPANY) {
			Spacer(modifier = Modifier.height(5.dp))
			OrderConfirmEditView(title = "起步价", value = "${startPrice ?: ""}", onValueChanged = {
				dispatch(OrderConfirmVm.Action.UpdateStartPrice(it.toIntOrNull() ?: 0))
			}, unit = "元")
			Spacer(modifier = Modifier.height(5.dp))
			OrderConfirmEditView(title = "超出公里数", value = "${overKm ?: ""}", onValueChanged = {
				dispatch(OrderConfirmVm.Action.UpdateOverKm(it.toIntOrNull() ?: 0))
			}, unit = "元")
			Spacer(modifier = Modifier.height(5.dp))
			OrderConfirmEditView(title = "每公里价格",
				value = "${unitPrice ?: ""}",
				onValueChanged = {
					dispatch(OrderConfirmVm.Action.UpdateUnitKmPrice(it.toIntOrNull() ?: 0))
				},
				unit = "元")
		} else {
			Spacer(modifier = Modifier.height(5.dp))
			OrderConfirmEditView(title = "出发地-事发地",
				isMustInput = true,
				value = "${abKm ?: ""}",
				onValueChanged = {
					dispatch(OrderConfirmVm.Action.UpdateAbKm(it.toIntOrNull() ?: 0))
				},
				unit = "公里")
			if (flowType != Const.SMALL_REPAIR) {
				Spacer(modifier = Modifier.height(5.dp))
				OrderConfirmEditView(title = "事发-目的地",
					isMustInput = true,
					value = "${bcKm ?: ""}",
					onValueChanged = {
						dispatch(OrderConfirmVm.Action.UpdateBcKm(it.toIntOrNull() ?: 0))
					},
					unit = "公里")
			}
		}
	}
}

@Composable
fun AuxiliaryFeeView(dilemmaFee : Int?,
	basementFee : Int?,
	abroadFee : Int?,
	bcRoadFee : Int?,
	photoList : List<PhotoTemplateInfo>?,
	updatePhotoTemplate : (PhotoTemplateInfo) -> Unit,
	dispatch : (OrderConfirmVm.Action) -> Unit) {
	val context = LocalContext.current
	LaunchedEffect(Unit) {
		photoList?.find { it.photoName?.contains("好评") == true }?.let {
			ServicingSpeechManager.playOrderGoodService(context)
			return@LaunchedEffect
		}
	}

	Column(modifier = Modifier
		.fillMaxWidth()
		.padding(horizontal = 10.dp)
		.background(color = Color.White, shape = RoundedCornerShape(12.dp))
		.padding(horizontal = 16.dp, vertical = 12.dp)) {
		Text(text = "附加费用",
			fontSize = 16.sp,
			fontWeight = FontWeight.Medium,
			color = Color.Black,
			modifier = Modifier.padding(bottom = 8.dp))
		HorizontalDivider(modifier = Modifier
			.fillMaxWidth()
			.padding(bottom = 12.dp),
			color = black5,
			thickness = 0.5.dp)

		if (GlobalData.driverInfoBean?.supplierType == Const.CHILD_COMPANY) {
			Column(modifier = Modifier
				.fillMaxWidth()
				.padding(bottom = 12.dp),
				verticalArrangement = Arrangement.spacedBy(12.dp)) {
				photoList?.forEachIndexed { index, photo ->
					Column(modifier = Modifier.fillMaxWidth(),
						horizontalAlignment = Alignment.CenterHorizontally) {
						OutlinedTextField(value = if (photo.numbering == "P.1") "${abroadFee ?: ""}" else "${bcRoadFee ?: ""}",
							onValueChange = { value ->
								if (photo.numbering == "P.1") {
									dispatch(OrderConfirmVm.Action.UpdateAbRoadFee(value.toIntOrNull()
										?: 0))
								} else {
									dispatch(OrderConfirmVm.Action.UpdateBcRoadFee(value.toIntOrNull()
										?: 0))
								}
							},
							modifier = Modifier
								.fillMaxWidth()
								.heightIn(min = 52.dp),
							textStyle = TextStyle(fontSize = 15.sp,
								color = Color.Black,
								textAlign = TextAlign.End,
								fontWeight = FontWeight.Normal),
							placeholder = {
								Text(text = if (photo.numbering == "P.1") "AB段路桥费" else "BC段路桥费",
									fontSize = 14.sp,
									color = black65)
							},
							trailingIcon = {
								Text(text = "元",
									fontSize = 14.sp,
									color = black65,
									modifier = Modifier.padding(end = 8.dp))
							},
							keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
							shape = RoundedCornerShape(8.dp),
							colors = OutlinedTextFieldDefaults.colors(unfocusedBorderColor = Color(
								0xFFE5E5E5),
								focusedBorderColor = Color(0xFF4C81F5),
								unfocusedContainerColor = Color(0xFFF8F8F8),
								focusedContainerColor = Color(0xFFF8F8F8)),
							singleLine = true)
						Spacer(modifier = Modifier.height(8.dp))
						Box(modifier = Modifier
							.fillMaxWidth()
							.height(80.dp)
							.background(color = Color(0xFFF8F8F8), shape = RoundedCornerShape(8.dp))) {
							InServicingPhotoItemView(photoTemplateInfo = photo,
								success = { updatePhotoTemplate(it) })
						}
					}
				}
			}
		}

		HorizontalDivider(modifier = Modifier
			.padding(vertical = 10.dp)
			.alpha(0.3f))

		OrderConfirmEditView(title = "困境费", value = "${dilemmaFee ?: ""}", onValueChanged = {
			dispatch(OrderConfirmVm.Action.UpdateDilemmaFee(it.toIntOrNull() ?: 0))
		})
		Spacer(modifier = Modifier.height(12.dp))
		OrderConfirmEditView(title = "地库费用", value = "${basementFee ?: ""}", onValueChanged = {
			dispatch(OrderConfirmVm.Action.UpdateBasementFee(it.toIntOrNull() ?: 0))
		})
	}
}

@Composable
private fun OrderConfirmEditView(value : String? = null,
	onValueChanged : (String) -> Unit,
	title : String,
	isMustInput : Boolean = false,
	unit : String = "元") {
	OutlinedTextField(value = value ?: "",
		onValueChange = onValueChanged,
		modifier = Modifier
			.fillMaxWidth()
			.heightIn(min = 52.dp),
		textStyle = TextStyle(fontSize = 15.sp,
			color = Color.Black,
			textAlign = TextAlign.End,
			fontWeight = FontWeight.Normal),
		placeholder = {
			Text(text = title, fontSize = 14.sp, color = black65)
		},
		trailingIcon = {
			Text(text = unit,
				fontSize = 14.sp,
				color = black65,
				modifier = Modifier.padding(end = 8.dp))
		},
		keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
		shape = RoundedCornerShape(8.dp),
		colors = OutlinedTextFieldDefaults.colors(unfocusedBorderColor = Color(0xFFE5E5E5),
			focusedBorderColor = Color(0xFF4C81F5),
			unfocusedContainerColor = Color(0xFFF8F8F8),
			focusedContainerColor = Color(0xFFF8F8F8)),
		singleLine = true)
}

@Composable
private fun OrderConfirmEditContainsPhotoView(value : String? = null,
	unit : String = "元",
	onValueChanged : (String) -> Unit,
	photoTemplateInfo : PhotoTemplateInfo,
	success : (PhotoTemplateInfo) -> Unit) {
	Column(modifier = Modifier.fillMaxWidth()) {
		Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
			Text(text = photoTemplateInfo.imageTitle ?: "",
				color = black65,
				fontSize = 13.sp,
				modifier = Modifier.width(90.dp),
				textAlign = TextAlign.Start)
			Spacer(modifier = Modifier.width(5.dp))
			OutlinedTextField(modifier = Modifier.fillMaxWidth(),
				keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Decimal),
				value = value ?: "",
				onValueChange = {
					onValueChanged(it)
				},
				trailingIcon = {
					Text(text = unit, color = black65, fontSize = 13.sp)
				},
				textStyle = TextStyle.Default.copy(textAlign = TextAlign.Right),
				colors = OutlinedTextFieldDefaults.colors(focusedContainerColor = Color(0x34E6EEFF),
					unfocusedContainerColor = Color(0xFFF8F8F8),
					focusedBorderColor = Color(0x994C81F5),
					unfocusedBorderColor = Color(0xFFF8F8F8)),
				shape = RoundedCornerShape(4.dp))
		}

		Spacer(modifier = Modifier.heightIn(10.dp))
		InServicingPhotoWithoutTitleView(photoTemplateInfo = photoTemplateInfo, success = { item ->
			success(item)
		})
	}
}