package com.za.ui.servicing.departure_photo

import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.za.base.BaseActivity
import com.za.base.view.CommonButton
import com.za.base.view.CommonDialog
import com.za.bean.db.order.PhotoTemplateInfo
import com.za.ext.finish
import com.za.ext.goNextPage
import com.za.ui.servicing.InServicingPhotoView
import com.za.ui.servicing.view.InServicingHeadView

class DeparturePhotoActivity : BaseActivity() {
	@Composable
	override fun ContentView() {
		DeparturePhotoScreen()
	}
}

@Composable
fun DeparturePhotoScreen(vm : DeparturePhotoVm = viewModel()) {
	val uiState = vm.uiState.collectAsStateWithLifecycle()
	val context = LocalContext.current

	LaunchedEffect(key1 = Unit) {
		vm.dispatch(DeparturePhotoVm.Action.Init)
	}

	if (uiState.value.goNextPage != null) {
		goNextPage(uiState.value.goNextPage?.nextState, context)
	}

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

	Scaffold(topBar = {
		InServicingHeadView(title = "发车前照片",
			orderInfo = uiState.value.orderInfo,
			onBack = { context.finish() })
	}, bottomBar = {
		CommonButton(text = "验车完成") {
			vm.dispatch(DeparturePhotoVm.Action.UpdateState(uiState.value.copy(isGoNextPageDialog = true)))
		}
	}) { it ->
		LazyColumn(modifier = Modifier
			.fillMaxSize()
			.padding(it),
			contentPadding = PaddingValues(10.dp)) {

			itemsIndexed(items = uiState.value.photoTemplateList ?: arrayListOf(),
				key = { _, item -> item.hashCode() }) { index : Int, item : PhotoTemplateInfo ->
				InServicingPhotoView(photoTemplateInfo = item, index = index + 1, success = {
					vm.dispatch(DeparturePhotoVm.Action.UpdatePhotoTemplate(it))
				})
				Spacer(modifier = Modifier.height(10.dp))
			}
		}
	}
}