package com.za.ui.servicing.ele_check

import android.app.Activity
import android.content.Intent
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.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.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.RadioButton
import androidx.compose.material3.RadioButtonDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
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 coil.compose.AsyncImage
import com.blankj.utilcode.util.ToastUtils
import com.za.base.theme.black90
import com.za.base.view.CommonButton
import com.za.base.view.CommonDialog
import com.za.bean.db.ele.EleCarDamagePhotoBean
import com.za.bean.db.ele.EleWorkOrderBean
import com.za.common.log.LogUtil
import com.za.common.util.ServicingSpeechManager
import com.za.ext.callPhone
import com.za.ext.finish
import com.za.ext.goStatusPage
import com.za.servicing.R
import com.za.ui.camera.ZdCameraXActivity
import com.za.ui.servicing.view.InServicingHeadView

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

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

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

    if (uiState.value.showCallPhoneDialog == true) {
        CommonDialog(
            cancelText = "取消",
            confirmText = "确定",
            title = "是否联系中道客服？",
            cancelEnable = true,
            cancel = {
                vm.dispatch(EleSignCheckVm.Action.UpdateState(uiState.value.copy(showCallPhoneDialog = false)))
            },
            dismiss = { vm.dispatch(EleSignCheckVm.Action.UpdateState(uiState.value.copy(showCallPhoneDialog = false))) },
            confirm = {
                vm.dispatch(EleSignCheckVm.Action.UpdateState(uiState.value.copy(showCallPhoneDialog = false)))
                context.callPhone(uiState.value.orderInfo?.hotline)
            })
    }

    //离线操作框
    if (uiState.value.showOfflineDialog == true) {
        CommonDialog(
            cancelText = "取消",
            confirmText = "离线上传",
            title = "上传失败，是否进行离线提交？",
            cancelEnable = true,
            cancel = {
                vm.dispatch(EleSignCheckVm.Action.UpdateState(uiState.value.copy(showOfflineDialog = false)))
            },
            dismiss = { vm.dispatch(EleSignCheckVm.Action.UpdateState(uiState.value.copy(showOfflineDialog = false))) },
            confirm = {
                vm.dispatch(EleSignCheckVm.Action.UpdateState(uiState.value.copy(showOfflineDialog = false)))
                vm.dispatch(EleSignCheckVm.Action.UploadOffline)
            })
    }


    Scaffold(topBar = {
        InServicingHeadView(title = "现场验车", orderInfo = uiState.value.orderInfo, onBack = { context.finish() })
    }, bottomBar = {
        CommonButton(text = "生成电子工单") {
            vm.dispatch(EleSignCheckVm.Action.UpdateState(uiState.value.copy(isGoNextPageDialog = true)))
        }
    }) { it ->
        Box(modifier = Modifier
            .fillMaxSize()
            .padding(it)) {
            EleSignCheckContent(eleWorkOrderBean = uiState.value.eleWorkOrderBean,
                photoList = uiState.value.damagePhoto,
                dispatch = { vm.dispatch(it) })
        }
    }
}

@Composable
private fun EleSignCheckContent(eleWorkOrderBean: EleWorkOrderBean?,
                                photoList: List<EleCarDamagePhotoBean>?,
                                dispatch: (EleSignCheckVm.Action) -> Unit) {

    val context = LocalContext.current
    val takePhoto = rememberLauncherForActivityResult(contract = ActivityResultContracts.StartActivityForResult()) { it ->
        if (it.resultCode == Activity.RESULT_OK) {
            val value = it.data?.getStringExtra("path")
            LogUtil.print("takePhoto", "path==$value")
            if (value.isNullOrBlank()) {
                ToastUtils.showLong("照片路径为空，请重新拍摄！")
                return@rememberLauncherForActivityResult
            }
            dispatch(EleSignCheckVm.Action.AddDamagePhoto(value))
        }
    }
    Column(modifier = Modifier
        .fillMaxWidth()
        .padding(10.dp)
        .background(color = Color.White, shape = RoundedCornerShape(4.dp))) {
        Column(modifier = Modifier
            .fillMaxWidth()
            .background(brush = Brush.verticalGradient(arrayListOf(Color(0xFF97A0BA), Color(0xFFE1E8F3))),
                shape = RoundedCornerShape(topStart = 4.dp, topEnd = 4.dp))
            .padding(10.dp)) {
            Text(text = "验车拍照", color = Color(0xFF213B54), fontWeight = FontWeight.Bold, fontSize = 16.sp)
            Row(modifier = Modifier
                .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Start) {
                AsyncImage(model = R.drawable.sv_warn_yellow, contentDescription = "", modifier = Modifier.size(12.dp))
                Spacer(modifier = Modifier.width(5.dp))
                Text(text = "请仔细检查车辆是否有损伤，如有损伤请仔细拍摄损伤部位照片",
                    fontWeight = FontWeight.Medium,
                    fontSize = 11.sp,
                    color = Color(0xFFFF6337))
            }
        }

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

        Text(text = "车辆是否有损伤?", fontWeight = FontWeight.Medium, color = Color.Black, fontSize = 14.sp, modifier = Modifier
            .fillMaxWidth()
            .padding(start = 10.dp))

        Row(modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 10.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.Start) {
            RadioButton(selected = (eleWorkOrderBean?.hasBad != null && eleWorkOrderBean.hasBad == false),
                onClick = {
                    dispatch(EleSignCheckVm.Action.ChangeDamageState(false))
                },
                colors = RadioButtonDefaults.colors()
                    .copy(selectedColor = Color.Red))
            Text(text = "无损伤", fontSize = 14.sp, color = black90, fontWeight = FontWeight.Medium)
        }

        Row(modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 10.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.Start) {
            RadioButton(selected = (eleWorkOrderBean?.hasBad != null && eleWorkOrderBean.hasBad == true),
                onClick = {
                    dispatch(EleSignCheckVm.Action.ChangeDamageState(true))
                },
                colors = RadioButtonDefaults.colors()
                    .copy(selectedColor = Color.Red))

            Text(text = "有损伤", fontSize = 14.sp, color = black90, fontWeight = FontWeight.Medium)
        }

        Text(text = "请拍摄损伤照片:", fontSize = 14.sp, color = Color.Black, fontWeight = FontWeight.Medium, modifier = Modifier
            .fillMaxWidth()
            .padding(start = 10.dp))

        if (!photoList.isNullOrEmpty()) {
            LazyVerticalGrid(columns = GridCells.Fixed(3), contentPadding = PaddingValues(10.dp)) {
                itemsIndexed(items = photoList) { _, item ->
                    DamageItemView(item, dispatch = { dispatch(it) })
                }
            }
        }
        AsyncImage(model = R.drawable.svg_take_photo_orange,
            contentDescription = "",
            modifier = Modifier
                .size(99.dp, 67.dp)
                .padding(10.dp)
                .clickable {
                    val intent = Intent(context, ZdCameraXActivity::class.java)
                    takePhoto.launch(intent)
                },
            contentScale = ContentScale.FillBounds)
    }
}

@Composable
private fun DamageItemView(damagePhotoBean: EleCarDamagePhotoBean,
                           dispatch: (EleSignCheckVm.Action) -> Unit) {
    val context = LocalContext.current
    val showReloadDialog = remember { mutableStateOf(false) }
    val reTakePhoto = rememberLauncherForActivityResult(contract = ActivityResultContracts.StartActivityForResult()) { it ->
        if (it.resultCode == Activity.RESULT_OK) {
            val value = it.data?.getStringExtra("path")
            LogUtil.print("takePhoto", "path==$value")
            if (value.isNullOrBlank()) {
                ToastUtils.showLong("照片路径为空，请重新拍摄！")
                return@rememberLauncherForActivityResult
            }
            dispatch(EleSignCheckVm.Action.ReUploadPhoto(damagePhotoBean.copy(path = value, serverPath = null, uploadStatus = 2)))
        }
    }
    //重拍弹窗
    if (showReloadDialog.value) {
        CommonDialog(title = "预览",
            confirm = {
                showReloadDialog.value = false
                val intent = Intent(context, ZdCameraXActivity::class.java)
                reTakePhoto.launch(intent)
            },

            cancelText = "取消",
            confirmText = "重拍",
            cancelEnable = true,
            cancel = {
                showReloadDialog.value = false
            },
            dismiss = {
                showReloadDialog.value = false
            }, content = {
                Box(modifier = Modifier
                    .fillMaxWidth()
                    .height(300.dp), contentAlignment = Alignment.Center) {
                    AsyncImage(model = damagePhotoBean.path,
                        contentDescription = "",
                        modifier = Modifier.fillMaxSize(),
                        contentScale = ContentScale.FillWidth)
                }
            })
    }

    Box(modifier = Modifier
        .size(110.dp, 76.dp)
        .padding(5.dp)
        .clickable { showReloadDialog.value = true },
        contentAlignment = Alignment.BottomCenter) {
        AsyncImage(model = damagePhotoBean.path, contentDescription = "", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.FillWidth)
        Box(modifier = Modifier
            .fillMaxWidth()
            .height(18.dp)
            .background(color = Color(0xFF16B276).takeIf { damagePhotoBean.uploadStatus != 3 }
                ?: Color(0xFFC5331F))
            .alpha(0.7f), contentAlignment = Alignment.Center) {
            Text(text = damagePhotoBean.getStatusStr(),
                fontWeight = FontWeight.Medium,
                style = TextStyle.Default.copy(),
                color = Color.White, fontSize = 10.sp,
                textAlign = TextAlign.Center)
        }
    }
}