package com.za.ui.main

import android.content.Context
import android.content.Intent
import androidx.compose.foundation.background
import androidx.compose.foundation.basicMarquee
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.PaddingValues
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.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
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.blankj.utilcode.util.ActivityUtils
import com.google.gson.Gson
import com.za.base.BaseActivity
import com.za.base.theme.bgColor
import com.za.base.view.CommonButton
import com.za.base.view.EmptyView
import com.za.base.view.HeadView
import com.za.base.view.LoadError
import com.za.bean.JpushBean
import com.za.bean.db.order.OrderInfo
import com.za.common.GlobalData
import com.za.common.log.LogUtil
import com.za.common.util.DeviceUtil
import com.za.ext.convertToFlowName
import com.za.ext.copy
import com.za.ext.finish
import com.za.ext.goStatusPage
import com.za.service.PushListener
import com.za.service.ServiceManager
import com.za.service.ZdPushServiceReceive
import com.za.service.location.ZdLocationManager
import com.za.servicing.R
import kotlinx.coroutines.launch

class ServicingMainActivity : BaseActivity() {

	@Composable
	override fun ContentView() {
		ServicingMainScreen(
			jobCode = intent.getStringExtra("driverName"),
			phone = intent.getStringExtra("driverPhone"),
			taskCode = intent.getStringExtra("taskCode"),
			deviceId = DeviceUtil.getAndroidId(this),
			rescueVehicle = intent.getStringExtra("rescueVehicle"),
		)
	}

	override fun onResume() {
		super.onResume()
		setupPushMessageReceiver()
	}

	private fun setupPushMessageReceiver() {        // 注册推送消息接收器
		ServiceManager.registerPushListener(object : PushListener {
			override fun broadcast(msg : String) {
				sendMessageToMainProcess("broadcast", msg)
			}

			override fun giveUpOrder(jpushBean : JpushBean) {
				sendMessageToMainProcess("giveUp", Gson().toJson(jpushBean))
			}

			override fun importantTip(jpushBean : JpushBean) {
				sendMessageToMainProcess("importantTip", Gson().toJson(jpushBean))
			}

			override fun newOrderMsg(jpushBean : JpushBean) {
				sendMessageToMainProcess("newOrder", Gson().toJson(jpushBean))
			}

			override fun reDispatchOrder(jpushBean : JpushBean) {
				sendMessageToMainProcess("reDispatch", Gson().toJson(jpushBean))
			}

			override fun revokeOrder(jpushBean : JpushBean) {
				sendMessageToMainProcess("revoke", Gson().toJson(jpushBean))
			}
		})
	}

	private fun sendMessageToMainProcess(type : String, message : String) {        // 使用广播将消息发送到主进程
		val intent = Intent(ZdPushServiceReceive.RECEIVE_ACTION).setPackage(packageName)
		intent.putExtra("type", type)
		intent.putExtra("message", message)
		sendBroadcast(intent)
		LogUtil.print(TAG, "发送消息到主进程: $type")
	}

	companion object {
		fun goToMain(context : Context,
			driverName : String? = null,
			driverPhone : String? = null,
			taskCode : String? = null,
			rescueVehicle : String? = null) {
			val intent = Intent(context, ServicingMainActivity::class.java)
			intent.putExtra("driverName", driverName)
			intent.putExtra("driverPhone", driverPhone)
			intent.putExtra("taskCode", taskCode)
			intent.putExtra("rescueVehicle", rescueVehicle)
			context.startActivity(intent)
			context.finish()
		}
	}
}

@Composable
private fun ServicingMainScreen(jobCode : String? = null,
	phone : String? = null,
	taskCode : String? = null,
	vehicleId : String? = null,
	deviceId : String? = null,
	rescueVehicle : String? = null,
	vm : ServicingMainVm = viewModel()) {
	val uiState = vm.uiState.collectAsStateWithLifecycle()
	val scope = rememberCoroutineScope()
	val context = LocalContext.current

	LaunchedEffect(Unit) {
		vm.dispatch(ServicingMainVm.Action.Init(jobCode,
			phone,
			taskCode,
			vehicleId,
			deviceId,
			rescueVehicle))
		scope.launch {
			ServiceManager.initialize(GlobalData.application)
			ZdLocationManager.startContinuousLocation(GlobalData.application)

		}
	}

	Scaffold(topBar = { HeadView("订单信息确认", onBack = { context.finish() }) }, bottomBar = {
		if (uiState.value.state == 1) {
			CommonButton(text = "已确认，去服务") {
				GlobalData.currentOrder?.goStatusPage(ActivityUtils.getTopActivity())
			}
		}
	}) {
		Box(modifier = Modifier
			.fillMaxSize()
			.background(bgColor)
			.padding(it)) {
			when (uiState.value.state) {
				1 -> {
					Box(modifier = Modifier
						.fillMaxSize()
						.padding(top = 10.dp),
						contentAlignment = Alignment.TopCenter) {
						OrderItemView(GlobalData.currentOrder)
					}
				}

				2 -> {
					Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
						LoadError(message = "订单获取异常", onRetry = {
							vm.dispatch(ServicingMainVm.Action.Init(jobCode,
								phone,
								taskCode,
								vehicleId,
								deviceId,
								rescueVehicle))
						})
					}
				}

				3 -> { //
					EmptyView()
				}


				else -> {
				}
			}
		}
	}
}

@Composable
private fun OrderItemView(orderInfo : OrderInfo?) {
	val context = LocalContext.current

	Card(modifier = Modifier
		.fillMaxWidth()
		.padding(horizontal = 10.dp, vertical = 5.dp),
		shape = RoundedCornerShape(16.dp),
		elevation = CardDefaults.cardElevation(defaultElevation = 2.dp, hoveredElevation = 4.dp),
		colors = CardDefaults.cardColors(containerColor = Color.White)) {
		Column(modifier = Modifier
			.fillMaxWidth()
			.padding(16.dp),
			verticalArrangement = Arrangement.spacedBy(16.dp)) { // 订单头部
			Row(modifier = Modifier
				.fillMaxWidth()
				.background(brush = Brush.linearGradient(colors = listOf(Color(0xFFF5F9FF),
					Color(0xFFEDF4FF)),
					start = androidx.compose.ui.geometry.Offset(0f, 0f),
					end = androidx.compose.ui.geometry.Offset(Float.POSITIVE_INFINITY, 0f)),
					shape = RoundedCornerShape(12.dp))
				.padding(horizontal = 12.dp, vertical = 10.dp),
				horizontalArrangement = Arrangement.SpaceBetween,
				verticalAlignment = Alignment.CenterVertically) {
				Row(verticalAlignment = Alignment.CenterVertically,
					horizontalArrangement = Arrangement.spacedBy(8.dp)) {
					Text(text = orderInfo?.taskCode ?: "",
						fontSize = 15.sp,
						fontWeight = FontWeight.Bold,
						color = Color(0xFF1A1A1A))

					Icon(painter = painterResource(R.drawable.sv_copy),
						contentDescription = "复制",
						modifier = Modifier
							.size(25.dp)
							.clickable {
								orderInfo?.taskCode?.copy(context)
							},
						tint = Color(0xFF666666))
				}
				Button(onClick = {

				},
					colors = ButtonDefaults.buttonColors(containerColor = Color(0xFFFF5A2C)),
					contentPadding = PaddingValues(horizontal = 14.dp, vertical = 2.dp),
					shape = RoundedCornerShape(16.dp),
					modifier = Modifier.height(28.dp)) {
					Text(text = orderInfo?.convertToFlowName() ?: "",
						fontSize = 13.sp,
						fontWeight = FontWeight.Medium)
				}
			}

			// 车辆位于
			if (! orderInfo?.addressProperty.isNullOrBlank()) {
				Row(modifier = Modifier
					.fillMaxWidth()
					.background(color = Color(0xFFF8F9FA), shape = RoundedCornerShape(10.dp))
					.padding(vertical = 12.dp, horizontal = 16.dp),
					verticalAlignment = Alignment.CenterVertically) {
					Icon(painter = rememberVectorPainter(image = Icons.Default.Menu),
						contentDescription = null,
						modifier = Modifier.size(20.dp),
						tint = Color(0xFF3364B7))
					Spacer(modifier = Modifier.width(8.dp))
					Text(text = "服务类型：", fontSize = 13.sp, color = Color(0x802F3059))
					Spacer(modifier = Modifier.weight(1f))
					Text(text = orderInfo?.serviceTypeName ?: "",
						fontSize = 15.sp,
						fontWeight = FontWeight.SemiBold,
						color = Color(0xFF2F3059))
				}
			}

			// 车牌信息
			if (! orderInfo?.plateNumber.isNullOrBlank()) {
				Row(modifier = Modifier
					.fillMaxWidth()
					.background(color = Color(0xFFF8F9FA), shape = RoundedCornerShape(10.dp))
					.padding(vertical = 12.dp, horizontal = 16.dp),
					verticalAlignment = Alignment.CenterVertically) {
					Icon(painter = painterResource(id = R.drawable.sv_map_marker_driver),
						contentDescription = null,
						modifier = Modifier.size(20.dp),
						tint = Color(0xFF3364B7))
					Spacer(modifier = Modifier.width(8.dp))
					Text(text = "车牌号：", fontSize = 13.sp, color = Color(0x802F3059))
					Spacer(modifier = Modifier.weight(1f))
					Text(text = orderInfo?.plateNumber ?: "",
						fontSize = 15.sp,
						fontWeight = FontWeight.SemiBold,
						color = Color(0xFF2F3059))
				}
			}

			// 地址信息容器
			Column(modifier = Modifier
				.fillMaxWidth()
				.background(color = Color(0xFFFAFBFC), shape = RoundedCornerShape(12.dp))
				.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { // 救援地址信息
				AddressItem(icon = {
					Box(modifier = Modifier
						.size(10.dp)
						.background(Color(0xFFFD8205), CircleShape))
				}, label = "救援地", address = orderInfo?.address ?: "")

				// 只有当目的地不为空时才显示分割线和目的地信息
				if (! orderInfo?.distAddress.isNullOrBlank()) {
					HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp),
						color = Color(0xFFEEEEEE))

					AddressItem(icon = {
						Box(modifier = Modifier
							.size(10.dp)
							.background(Color(0xFF5CC4BF), CircleShape))
					}, label = "目的地", address = orderInfo?.distAddress ?: "")
				}
			}

			//重要提示
			if (! orderInfo?.importantTip.isNullOrBlank()) { // 订单状态
				Box(modifier = Modifier
					.fillMaxWidth()
					.background(brush = Brush.linearGradient(colors = listOf(Color(0xFFFFF3E0),
						Color(0xFFFFE0B2)),
						start = androidx.compose.ui.geometry.Offset(0f, 0f),
						end = androidx.compose.ui.geometry.Offset(Float.POSITIVE_INFINITY, 0f)),
						shape = RoundedCornerShape(10.dp))
					.padding(12.dp),
					contentAlignment = Alignment.Center) {
					Text(text = orderInfo?.importantTip ?: "",
						color = Color(0xFFFF5722),
						fontSize = 15.sp,
						fontWeight = FontWeight.Bold,
						modifier = Modifier.basicMarquee())
				}
			}
		}
	}
}

@Composable
private fun AddressItem(icon : @Composable () -> Unit, label : String, address : String) {
	Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
		Row(verticalAlignment = Alignment.CenterVertically,
			horizontalArrangement = Arrangement.spacedBy(8.dp)) {
			icon()
			Text(text = label, fontSize = 13.sp, color = Color(0x802F3059))
		}

		Text(text = address,
			fontSize = 15.sp,
			color = Color(0xFF2F3059),
			fontWeight = FontWeight.Medium,
			modifier = Modifier.padding(start = 18.dp))
	}
}

@Preview
@Composable
private fun ServiceMainPreview() {
	ServicingMainScreen()
}