package com.za.ui.new_order

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
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.fillMaxHeight
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.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowRight
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.VerticalDivider
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
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.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.vectorResource
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.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.za.base.theme.bgColor
import com.za.base.theme.black50
import com.za.base.theme.black90
import com.za.base.theme.buttonBgColor
import com.za.base.view.CommonButton
import com.za.base.view.CommonDialog
import com.za.common.log.LogUtil
import com.za.ext.copy
import com.za.ext.finish
import com.za.servicing.R
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


object NewOrderUiType {
	const val SERVICING = 1 //服务中界面
	const val HISTORY = 2 //历史界面
	const val ACCEPT = 3 //接单页
	const val PENDING = 4 //待服务
	const val IN_SERVICING_HOME = 5 //首页服务中
}

data class NewOrderItemUIBean(
	val taskCode : String? = null,
	val addressProperty : String? = null,
	val address : String? = null,
	val distAddress : String? = null,
	val serviceTypeName : String? = null,
	val orderSource : String? = null,
	val settleType : Int? = null,
	val currentOrderState : String? = null,
	val supplierAuditStr : String? = null, //审核状态描述
	val reserveTime : String? = null, //预约时间
	val expectArriveTime : String? = null, //预计到达时间
	val auditFailReason : String? = null, //审核失败原因
	val bottomTextString : String? = null, //底部文字
	val hasReplaceBatteryCapable : Int? = null,  //是否具有更换电瓶的能力
	val uiType : Int? = 1, //1 服务中  2 历史订单  3 接单页  4 待服务页  5 进行中首页
)

// 1 服务中  2 历史订单
@Composable
fun NewOrderItem(uiBean : NewOrderItemUIBean?,
	goInServicing : () -> Unit = {},
	goHistory : () -> Unit = {},
	goDetail : () -> Unit = {},
	goNextPage : () -> Unit = {},
	goAccept : () -> Unit = {},
	refuelOrder : () -> Unit = {},
	goOrderPhoto : () -> Unit = {},
	goEle : () -> Unit = {},
	goChange : () -> Unit = {}) {
	val context = LocalContext.current
	val horizontalPadding = 26.dp
	Card(modifier = Modifier
		.fillMaxWidth()
		.clickable {
			if (uiBean?.uiType == NewOrderUiType.HISTORY) {
				goHistory()
				return@clickable
			}
			if (uiBean?.uiType == NewOrderUiType.IN_SERVICING_HOME || uiBean?.uiType == NewOrderUiType.PENDING) {
				goDetail()
				return@clickable
			}
		}
		.background(color = bgColor),
		colors = CardDefaults.cardColors().copy(containerColor = Color.White),
		shape = RoundedCornerShape(8.dp),
		border = BorderStroke(width = 0.6.dp, color = Color(0xFFE6E6E6))) {

		NewOrderItemHead(uiBean = uiBean, goInServicing = goInServicing, goChange = goChange)

		if (uiBean?.uiType == NewOrderUiType.HISTORY) {
			Spacer(modifier = Modifier.height(15.dp))
			Row(modifier = Modifier
				.fillMaxWidth()
				.height(20.dp)
				.padding(horizontal = horizontalPadding),
				verticalAlignment = Alignment.CenterVertically,
				horizontalArrangement = Arrangement.Absolute.SpaceBetween) {
				Text(text = uiBean?.serviceTypeName ?: "",
					color = black90,
					fontWeight = FontWeight.SemiBold,
					fontSize = 17.sp)
				Text(uiBean?.currentOrderState ?: "",
					color = Color(0xFFF19028),
					fontWeight = FontWeight.Medium,
					fontSize = 13.sp)
			}
		} else {
			Spacer(modifier = Modifier.height(15.dp))
			Row(modifier = Modifier
				.fillMaxWidth()
				.height(20.dp)
				.clickable { uiBean?.taskCode.copy(context = context) }
				.padding(horizontal = horizontalPadding),
				verticalAlignment = Alignment.CenterVertically) {
				Text("单号", color = black50, fontWeight = FontWeight.Medium, fontSize = 13.sp)
				Spacer(modifier = Modifier.width(10.dp))
				Text(uiBean?.taskCode ?: "",
					color = black90,
					fontWeight = FontWeight.SemiBold,
					fontSize = 16.sp,
					modifier = Modifier.wrapContentSize(align = Alignment.Center))
				Spacer(modifier = Modifier.width(10.dp))
				Icon(imageVector = ImageVector.vectorResource(R.drawable.sv_new_copy),
					contentDescription = null,
					modifier = Modifier.size(13.dp))
			}
		}

		Spacer(modifier = Modifier.height(10.dp))
		Row(modifier = Modifier
			.fillMaxWidth()
			.padding(horizontal = horizontalPadding),
			verticalAlignment = Alignment.CenterVertically) {
			AsyncImage(model = R.drawable.sv_settle_month.takeIf { uiBean?.settleType == 1 }
				?: R.drawable.sv_settle_cash,
				contentDescription = null,
				modifier = Modifier.size(31.dp, 16.dp))
			Spacer(modifier = Modifier.width(10.dp))
			Text(uiBean?.orderSource ?: "",
				color = Color.Black,
				modifier = Modifier.width(140.dp),
				maxLines = 1,
				overflow = TextOverflow.Ellipsis,
				fontWeight = FontWeight.Medium,
				fontSize = 12.sp)
			Spacer(Modifier.weight(1f))
			Text(uiBean?.addressProperty ?: "",
				color = Color.Black,
				maxLines = 1,
				overflow = TextOverflow.Ellipsis,
				modifier = Modifier.width(100.dp),
				fontWeight = FontWeight.SemiBold,
				fontSize = 14.sp)
		}

		if (! uiBean?.reserveTime.isNullOrBlank()) {
			Spacer(modifier = Modifier.height(4.dp))
			Row(modifier = Modifier
				.fillMaxWidth()
				.height(20.dp)
				.padding(horizontal = horizontalPadding),
				verticalAlignment = Alignment.CenterVertically) {
				AsyncImage(model = R.drawable.sv_order_reserve,
					contentDescription = null,
					modifier = Modifier.size(31.dp, 16.dp))
				Spacer(modifier = Modifier.width(10.dp))
				Text(uiBean?.reserveTime ?: "",
					color = Color(0xFF354E9E),
					fontWeight = FontWeight.Medium,
					fontSize = 12.sp)
			}
		}


		Spacer(modifier = Modifier.height(10.dp))
		if (uiBean?.distAddress.isNullOrBlank()) {

			Row(modifier = Modifier
				.fillMaxWidth()
				.padding(horizontal = 18.dp)
				.background(color = Color(0x80F8FBFF), shape = RoundedCornerShape(4.dp))
				.border(width = 0.3.dp, color = Color(0xFFD8E4F0), shape = RoundedCornerShape(4.dp))
				.padding(horizontal = 12.dp, vertical = 10.dp),
				verticalAlignment = Alignment.CenterVertically) {

				AsyncImage(model = R.drawable.sv_rescuing,
					contentDescription = null,
					modifier = Modifier.size(16.dp))
				Spacer(modifier = Modifier.width(10.dp))
				Text(uiBean?.address ?: "",
					maxLines = 2,
					overflow = TextOverflow.Ellipsis,
					fontSize = 12.5.sp,
					fontWeight = FontWeight.Medium,
					color = black90)
			}
		} else {
			Row(modifier = Modifier
				.fillMaxWidth()
				.height(140.dp)
				.padding(horizontal = 18.dp)
				.background(color = Color(0x80F8FBFF), shape = RoundedCornerShape(4.dp))
				.border(width = 0.3.dp, color = Color(0xFFD8E4F0), shape = RoundedCornerShape(4.dp))
				.padding(horizontal = 12.dp, vertical = 5.dp)) {

				Column(horizontalAlignment = Alignment.CenterHorizontally,
					verticalArrangement = Arrangement.SpaceAround) {
					Spacer(modifier = Modifier.height(10.dp))
					AsyncImage(model = R.drawable.sv_rescuing,
						contentDescription = null,
						modifier = Modifier.size(16.dp))

					if (! uiBean?.distAddress.isNullOrBlank()) {
						VerticalDivider(modifier = Modifier.weight(1f),
							color = Color(0xFFC1C1C1).copy(0.5f))

						AsyncImage(model = R.drawable.sv_dist,
							contentDescription = null,
							modifier = Modifier.size(16.dp))
						Spacer(modifier = Modifier.height(10.dp))
					}

				}

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

				Column(verticalArrangement = Arrangement.SpaceAround,
					modifier = Modifier.fillMaxHeight()) {
					Text(uiBean?.address ?: "",
						maxLines = 2,
						overflow = TextOverflow.Ellipsis,
						fontSize = 12.5.sp,
						fontWeight = FontWeight.Medium,
						color = black90)
					if (uiBean?.distAddress.isNullOrBlank() == false) {
						HorizontalDivider(modifier = Modifier
							.alpha(0.1f)
							.padding(vertical = 5.dp))
						Text(uiBean?.distAddress ?: "",
							maxLines = 2,
							overflow = TextOverflow.Ellipsis,
							fontSize = 12.5.sp,
							fontWeight = FontWeight.Medium,
							color = black90)
					}
				}
			}
		}

		if (! uiBean?.auditFailReason.isNullOrBlank()) {
			Row(modifier = Modifier
				.fillMaxWidth()
				.padding(horizontal = 18.dp)
				.background(color = Color(0xFFFFF7EE), shape = RoundedCornerShape(4.dp))
				.padding(horizontal = 15.dp, vertical = 10.dp),
				verticalAlignment = Alignment.CenterVertically) {
				Icon(imageVector = ImageVector.vectorResource(R.drawable.sv_warn_yellow),
					contentDescription = "",
					tint = Color(0xFFFF8F37))
				Spacer(modifier = Modifier.width(7.dp))
				Text(uiBean?.auditFailReason ?: "",
					color = Color(0xFFFF8F37),
					fontWeight = FontWeight.Medium,
					fontSize = 12.sp)
			}
		}

		if (uiBean?.uiType == NewOrderUiType.HISTORY) {
			Spacer(modifier = Modifier.height(10.dp))

			Row(modifier = Modifier
				.fillMaxWidth()
				.padding(horizontal = 20.dp),
				horizontalArrangement = Arrangement.SpaceAround) {
				AsyncImage(model = R.drawable.sv_order_photo,
					contentDescription = null,
					modifier = Modifier
						.size(93.dp, 25.dp)
						.clickable { goOrderPhoto() },
					contentScale = ContentScale.None)

				AsyncImage(model = R.drawable.sv_order_ele,
					contentDescription = null,
					modifier = Modifier
						.size(93.dp, 25.dp)
						.clickable { goEle() },
					contentScale = ContentScale.None)

				if (uiBean.hasReplaceBatteryCapable == 1) {
					AsyncImage(model = R.drawable.sv_order_change,
						contentDescription = null,
						modifier = Modifier
							.size(93.dp, 25.dp)
							.clickable {
								goChange()
							},
						contentScale = ContentScale.None)
				}
			}
		}


		if (uiBean?.uiType == NewOrderUiType.SERVICING || uiBean?.uiType == NewOrderUiType.ACCEPT) {
			Spacer(modifier = Modifier.height(10.dp))

			if (uiBean?.uiType == NewOrderUiType.ACCEPT) {
				Row(modifier = Modifier
					.fillMaxWidth()
					.padding(horizontal = 5.dp)) {
					CommonButton(text = "拒绝",
						modifier = Modifier
							.weight(1f)
							.padding(vertical = 10.dp, horizontal = 5.dp)
							.background(color = buttonBgColor.copy(alpha = 0.5f),
								shape = RoundedCornerShape(4.dp))
							.padding(vertical = 15.dp)) {
						refuelOrder()
					}

					CommonButton(text = uiBean?.bottomTextString ?: "",
						modifier = Modifier
							.weight(2f)
							.padding(vertical = 10.dp, horizontal = 5.dp)
							.background(color = buttonBgColor, shape = RoundedCornerShape(4.dp))
							.padding(vertical = 15.dp)) {
						goAccept()
					}
				}
			} else {
				CommonButton(text = uiBean?.bottomTextString ?: "") {
					goNextPage()
				}
			}
		}

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

@Composable
fun NewOrderItemHead(uiBean : NewOrderItemUIBean?,
	goInServicing : () -> Unit = {},
	goChange : () -> Unit = {}) {

	var timeOut by remember { mutableStateOf<String?>(null) }
	if (uiBean?.uiType == NewOrderUiType.ACCEPT) {
		NewOrderTimeOut(countValue = { timeOut = it })
	}

	when (uiBean?.uiType) {
		NewOrderUiType.IN_SERVICING_HOME, NewOrderUiType.PENDING, NewOrderUiType.SERVICING, NewOrderUiType.ACCEPT -> {
			Row(modifier = Modifier
				.fillMaxWidth()
				.clickable {
					if (uiBean?.uiType == NewOrderUiType.IN_SERVICING_HOME) {
						goInServicing()
						return@clickable
					}
					if (uiBean?.uiType == NewOrderUiType.PENDING) {
						goChange()
						return@clickable
					}
				}
				.padding(horizontal = 5.dp, vertical = 3.dp)
				.background(color = Color(0xFFF9FDFF),
					shape = RoundedCornerShape(topStart = 5.dp,
						topEnd = 5.dp,
						bottomStart = 0.dp,
						bottomEnd = 0.dp))
				.padding(top = 14.dp, bottom = 8.dp, start = 21.dp, end = 16.dp),
				verticalAlignment = Alignment.CenterVertically) {
				Text(uiBean.serviceTypeName ?: "",
					color = black90,
					maxLines = 1,
					overflow = TextOverflow.Ellipsis,
					fontWeight = FontWeight.Medium,
					modifier = Modifier.fillMaxWidth(0.5f),
					fontSize = 17.sp)
				Spacer(Modifier.weight(1f))

				if (uiBean?.uiType == NewOrderUiType.SERVICING) {
					Text("预计到达：",
						color = Color(0xFFF19028),
						fontWeight = FontWeight.Medium,
						fontSize = 13.sp)
					Spacer(modifier = Modifier.width(8.dp))
					Text("${
						uiBean.expectArriveTime?.split(" ")?.get(1)
					}", color = Color(0xFFF19028), fontWeight = FontWeight.Medium, fontSize = 13.sp)
				} else if (uiBean?.uiType == NewOrderUiType.ACCEPT) {
					Text("超时剩余：",
						color = Color.Red,
						fontWeight = FontWeight.Medium,
						fontSize = 13.sp)
					Spacer(modifier = Modifier.width(8.dp))
					Text(timeOut ?: "",
						color = Color.Red,
						fontWeight = FontWeight.Medium,
						fontSize = 13.sp)
				} else {
					Text(uiBean?.currentOrderState ?: "",
						color = Color(0xFFF19028),
						modifier = Modifier.fillMaxWidth(0.4f),
						overflow = TextOverflow.Ellipsis,
						maxLines = 1,
						fontWeight = FontWeight.Medium,
						fontSize = 13.sp)
					Spacer(modifier = Modifier.width(8.dp))

					Icon(Icons.Default.KeyboardArrowRight,
						contentDescription = null,
						modifier = Modifier.size(13.dp),
						tint = Color.Gray)
				}
			}
		}

		NewOrderUiType.HISTORY -> {
			Row(modifier = Modifier
				.fillMaxWidth()
				.padding(horizontal = 5.dp, vertical = 3.dp)
				.background(color = Color(0xFFF9FDFF),
					shape = RoundedCornerShape(topStart = 5.dp,
						topEnd = 5.dp,
						bottomStart = 0.dp,
						bottomEnd = 0.dp))
				.padding(top = 14.dp, bottom = 8.dp, start = 21.dp, end = 16.dp),
				verticalAlignment = Alignment.CenterVertically) {
				Text(uiBean?.taskCode ?: "",
					color = black90,
					fontWeight = FontWeight.Medium,
					fontSize = 17.sp)
				Spacer(modifier = Modifier.width(9.dp))
				Icon(imageVector = ImageVector.vectorResource(R.drawable.sv_new_copy),
					contentDescription = null,
					modifier = Modifier.size(13.dp))
				Spacer(Modifier.weight(1f))
				Box(modifier = Modifier
					.background(color = Color(0x99FFEBEB), shape = RoundedCornerShape(4.dp))
					.border(width = 0.5.dp,
						color = Color(0xFFFFC7B8),
						shape = RoundedCornerShape(4.dp))
					.padding(horizontal = 4.dp, vertical = 2.dp)) {
					Text(uiBean?.supplierAuditStr ?: "",
						color = Color(0xFFFF5656),
						fontWeight = FontWeight.Normal,
						fontSize = 10.sp,
						style = TextStyle.Default.copy())
				}
				Spacer(modifier = Modifier.width(8.dp))
				Icon(Icons.Default.KeyboardArrowRight,
					contentDescription = null,
					modifier = Modifier.size(13.dp),
					tint = Color.Gray)
			}
		}
	}

	HorizontalDivider(modifier = Modifier.alpha(0.1f))
}

@Composable
private fun NewOrderTimeOut(countValue : (String) -> Unit) {
	val context = LocalContext.current
	var timerJob : Job? = null
	val scope = rememberCoroutineScope()
	var timeCount by remember { mutableStateOf<String?>(null) }
	var showTimeOutDialog by remember { mutableStateOf(false) }
	DisposableEffect(timerJob) {
		timerJob = scope.launch {
			try {
				var timeLeft = 120
				while (timeLeft > 0) {
					delay(1000)
					timeLeft --
					timeCount = "$timeLeft"
					countValue(timeCount ?: "")
				}
				if (timeLeft == 0) {
					showTimeOutDialog = true
				}
			} catch (e : Exception) {
				LogUtil.print("startTimer", "倒计时异常: ${e.message}")
			}
		}

		onDispose {
			timerJob?.cancel()
			timerJob = null
		}
	}
	if (showTimeOutDialog) {
		CommonDialog(cancelText = "关闭",
			confirmText = "确定",
			title = "订单已超时",
			message = "当前订单已超时，请等待新的订单",
			cancelEnable = false,
			dismiss = {
				showTimeOutDialog = false
				context.finish()
			},
			confirm = {
				showTimeOutDialog = false
				context.finish()
			})
	}
}