package com.za.ui.servicing.order_confirm

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
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.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
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.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.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import coil.decode.GifDecoder
import coil.request.ImageRequest
import com.blankj.utilcode.util.ToastUtils
import com.tencent.smtt.sdk.WebChromeClient
import com.tencent.smtt.sdk.WebSettings
import com.tencent.smtt.sdk.WebView
import com.tencent.smtt.sdk.WebViewClient
import com.za.base.theme.black65
import com.za.base.view.CommonButton
import com.za.base.view.CommonDialog
import com.za.base.view.HeadView
import com.za.base.view.LoadingState
import com.za.common.log.LogUtil
import com.za.ext.getEleOrderH5Url
import com.za.ext.goStatusPage
import com.za.servicing.R
import com.za.signature.GridPaintActivity
import com.za.signature.config.PenConfig

@Composable
fun ConfirmH5SuccessScreen(vm : ConfirmH5SuccessVm = viewModel()) {
	val uiState = vm.uiState.collectAsStateWithLifecycle()
	val context = LocalContext.current
	val webView = WebView(context)

	//客户签名
	val customerSignatureLauncher =
		rememberLauncherForActivityResult(contract = ActivityResultContracts.StartActivityForResult()) {
			if (it.resultCode == Activity.RESULT_OK) {
				val value = it.data?.getStringExtra(PenConfig.SAVE_PATH)
				LogUtil.print("pen save Path", "path==$value")
				if (value.isNullOrBlank()) {
					ToastUtils.showLong("照片路径为空，请重新拍摄！")
					return@rememberLauncherForActivityResult
				}
				vm.dispatch(ConfirmH5SuccessVm.Action.UpdateCurrentEleWorkOrder(type = 1,
					path = value))
			}
		}

	//接车人签字
	val receivePeopleSignatureLauncher =
		rememberLauncherForActivityResult(contract = ActivityResultContracts.StartActivityForResult()) {
			if (it.resultCode == Activity.RESULT_OK) {
				val value = it.data?.getStringExtra(PenConfig.SAVE_PATH)
				LogUtil.print("pen save Path", "path==$value")
				if (value.isNullOrBlank()) {
					ToastUtils.showLong("照片路径为空，请重新拍摄！")
					return@rememberLauncherForActivityResult
				}
				vm.dispatch(ConfirmH5SuccessVm.Action.UpdateCurrentEleWorkOrder(type = 2,
					path = value))
			}
		}


	//服务人员签字
	val servicePeopleSignatureLauncher =
		rememberLauncherForActivityResult(contract = ActivityResultContracts.StartActivityForResult()) {
			if (it.resultCode == Activity.RESULT_OK) {
				val value = it.data?.getStringExtra(PenConfig.SAVE_PATH)
				LogUtil.print("pen save Path", "path==$value")
				if (value.isNullOrBlank()) {
					ToastUtils.showLong("照片路径为空，请重新拍摄！")
					return@rememberLauncherForActivityResult
				}
				vm.dispatch(ConfirmH5SuccessVm.Action.UpdateCurrentEleWorkOrder(type = 3,
					path = value))
			}
		}


	BackHandler(enabled = true) {}
	LaunchedEffect(key1 = Unit) {
		vm.dispatch(ConfirmH5SuccessVm.Action.Init)
	}

	if (uiState.value.goNextPage == true) {
		uiState.value.orderInfo?.goStatusPage(context)
	}

	if (uiState.value.showSignDialog != null) {
		val title = when (uiState.value.showSignDialog) {
			1 -> "客户签字缺失，请补充！"
			2 -> "接车人签字缺失，请补充！"
			3 -> "服务人员签字缺失，请补充！"
			else -> "签字缺失，请补充！"
		}
		CommonDialog(title = title, confirmText = "去签字", cancel = {
			vm.updateState(uiState.value.copy(showSignDialog = null))
		}, cancelEnable = false, confirm = {
			vm.updateState(uiState.value.copy(showSignDialog = null))
			val intent = Intent(context, GridPaintActivity::class.java)
			intent.putExtra("background", android.graphics.Color.WHITE)
			intent.putExtra("crop", true)
			intent.putExtra("fontSize", 50) //手写字体大小
			intent.putExtra("format", PenConfig.FORMAT_PNG)
			intent.putExtra("lineLength", 10) //每行显示字数（超出屏幕支持横向滚动）
			when (uiState.value.showSignDialog) {
				1 -> {
					customerSignatureLauncher.launch(intent)
				}

				2 -> {
					receivePeopleSignatureLauncher.launch(intent)
				}

				3 -> {
					servicePeopleSignatureLauncher.launch(intent)
				}
			}
		}, cancelText = "取消", dismiss = {
			vm.updateState(uiState.value.copy(showSignDialog = null))
		})
	}

	if (uiState.value.showOfflineTaskDialog == true) {
		CommonDialog(title = "提示", content = {
			Box {
				Text("有正在进行的离线任务，是否仍要提交？")
			}
		}, confirmText = "等待离线任务上传", cancelText = "清除离线任务，后续补传", confirm = {
			vm.updateState(uiState.value.copy(showOfflineTaskDialog = false))
		}, cancelEnable = true, cancel = {
			vm.dispatch(ConfirmH5SuccessVm.Action.ClearOfflineTask)
			vm.updateState(uiState.value.copy(showOfflineTaskDialog = false))
		}, dismiss = {
			vm.updateState(uiState.value.copy(showOfflineTaskDialog = false))
		})
	}

	Scaffold(topBar = {
		HeadView(title = "电子工单确认", isCanBack = false)
	}) {
		when (uiState.value.loadingState) {
			is LoadingState.Loading -> {
				Box(modifier = Modifier
					.fillMaxSize()
					.padding(it)
					.background(color = Color.White),
					contentAlignment = Alignment.Center) {
					AsyncImage(model = ImageRequest.Builder(LocalContext.current)
						.data(R.drawable.gif_loading).decoderFactory(GifDecoder.Factory()).build(),
						contentDescription = "",
						modifier = Modifier.size(80.dp))
				}
			}

			is LoadingState.LoadingSuccess -> {
				Column(modifier = Modifier
					.fillMaxSize()
					.padding(it)
					.background(color = Color.White)
					.verticalScroll(rememberScrollState())) {
					AndroidView(modifier = Modifier
						.fillMaxWidth()
						.fillMaxHeight(), 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.webViewClient = object : WebViewClient() {
							override fun onPageStarted(p0 : WebView?, p1 : String?, p2 : Bitmap?) {
								super.onPageStarted(p0, p1, p2)
								LogUtil.print("onPageStarted", "$p1---")
							}

							override fun onReceivedError(p0 : WebView?,
								p1 : Int,
								p2 : String?,
								p3 : String?) {
								super.onReceivedError(p0, p1, p2, p3)
								LogUtil.print("onReceivedError1", "$p2---$p3")
							}

							override fun onPageFinished(p0 : WebView?, p1 : String?) {
								super.onPageFinished(p0, p1)
								LogUtil.print("onPageFinished", "$p1---$p1")
							}
						}
						webView
					}, update = { webView.loadUrl(uiState.value.orderInfo?.getEleOrderH5Url()) })

					CommonButton(text = "订单完成,去结算单页") {
						vm.dispatch(ConfirmH5SuccessVm.Action.TaskFinish)
					}
				}
			}

			is LoadingState.LoadingFailed -> {
				Column(modifier = Modifier
					.fillMaxSize()
					.clickable { vm.dispatch(ConfirmH5SuccessVm.Action.Init) }
					.padding(it),
					verticalArrangement = Arrangement.Center,
					horizontalAlignment = Alignment.CenterHorizontally) {
					AsyncImage(model = R.drawable.sv_load_error,
						contentDescription = "",
						modifier = Modifier.size(120.dp))
					Spacer(modifier = Modifier.height(10.dp))
					Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
						Text(text = "加载失败，点击重试",
							fontSize = 16.sp,
							fontWeight = FontWeight.Bold,
							color = black65)
					}
				}
			}
		}
	}
}
