package com.za.ui.servicing.verify

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.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.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.HorizontalDivider
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.draw.alpha
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.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.blankj.utilcode.util.ConvertUtils
import com.za.base.BaseActivity
import com.za.base.theme.black65
import com.za.base.theme.buttonBgColor
import com.za.base.view.CommonDialog
import com.za.bean.db.order.OrderInfo
import com.za.common.util.QRCodeUtil
import com.za.ext.callPhone
import com.za.ext.finish
import com.za.ext.goNextPage
import com.za.servicing.R
import com.za.ui.servicing.view.InServicingHeadView

class VerifyOrderActivity : BaseActivity() {
    @Composable
    override fun ContentView() {
        VerifyOrderScreen()
    }
}


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

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

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

    if (uiState.value.showCallPhoneDialog == true) {
        CommonDialog(
            cancelText = "取消",
            confirmText = "确定",
            title = "是否联系中道客服？",
            cancelEnable = true,
            cancel = {
                vm.dispatch(VerifyOrderVm.Action.UpdateState(uiState.value.copy(showCallPhoneDialog = false)))
            },
            dismiss = { vm.dispatch(VerifyOrderVm.Action.UpdateState(uiState.value.copy(showCallPhoneDialog = false))) },
            confirm = {
                vm.dispatch(VerifyOrderVm.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(VerifyOrderVm.Action.UpdateState(uiState.value.copy(showOfflineDialog = false)))
            },
            dismiss = { vm.dispatch(VerifyOrderVm.Action.UpdateState(uiState.value.copy(showOfflineDialog = false))) },
            confirm = {
                vm.dispatch(VerifyOrderVm.Action.UpdateState(uiState.value.copy(showOfflineDialog = false)))
                vm.dispatch(VerifyOrderVm.Action.UploadOffline)
            })
    }

    Scaffold(topBar = { InServicingHeadView(title = "验证资格", orderInfo = uiState.value.orderInfo, onBack = { context.finish() }) }, bottomBar = {
        Row(modifier = Modifier
            .fillMaxWidth()
            .background(Color.White, shape = RoundedCornerShape(topStart = 8.dp, topEnd = 8.dp))
            .padding(20.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.Center) {
            if (uiState.value.orderInfo?.verifyType != 5) {
                Box(modifier = Modifier
                    .weight(1f)
                    .clickable { vm.dispatch(VerifyOrderVm.Action.UpdateState(uiState.value.copy(showCallPhoneDialog = true))) }
                    .border(width = 0.8.dp, color = Color(0xFFDDDDDD), shape = RoundedCornerShape(4.dp))
                    .padding(vertical = 10.dp), contentAlignment = Alignment.Center) {
                    Text(text = "不符合，联系客服", fontSize = 14.sp, fontWeight = FontWeight.Medium, color = black65)
                }
                Spacer(modifier = Modifier.width(5.dp))
            }
            val buttonText = when (uiState.value.orderInfo?.verifyType) {
                0 -> {
                    "跳过验证"
                }

                5 -> {
                    "确认提交，继续任务"
                }

                else -> {
                    "符合，继续任务"
                }
            }
            Box(modifier = Modifier
                .weight(1f)
                .clickable { vm.dispatch(VerifyOrderVm.Action.UpdateState(uiState.value.copy(isGoNextPageDialog = true))) }
                .background(color = buttonBgColor, shape = RoundedCornerShape(4.dp))
                .padding(vertical = 10.dp), contentAlignment = Alignment.Center) {
                Text(text = buttonText, fontSize = 14.sp, fontWeight = FontWeight.Medium, color = Color.White)
            }
        }
    }) {
        LazyColumn(modifier = Modifier
            .fillMaxSize()
            .padding(it), contentPadding = PaddingValues(vertical = 5.dp)) {

            if (uiState.value.orderInfo?.verifyType != null && uiState.value.orderInfo?.verifyType != 0) {
                item {
                    VerifyCarView(orderInfo = uiState.value.orderInfo)
                }
            }

            if (!uiState.value.orderInfo?.arriveRemindLink.isNullOrBlank()) {
                item {
                    VerifyTipView(arriveRemind = uiState.value.orderInfo?.arriveRemind
                        ?: "", uiState.value.orderInfo?.arriveRemindLink ?: "")
                }
            }

            //重要提示
            if (!uiState.value.orderInfo?.importantTip.isNullOrBlank()) {
                item {
                    Row(modifier = Modifier
                        .fillMaxWidth()
                        .background(color = Color(0xFFFFF7EE), shape = RoundedCornerShape(4.dp))
                        .padding(vertical = 5.dp), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically) {
                        AsyncImage(model = R.drawable.sv_warn_yellow, contentDescription = "", modifier = Modifier.size(12.5.dp, 12.5.dp))
                        Spacer(modifier = Modifier.width(5.dp))
                        Text(text = uiState.value.orderInfo?.importantTip
                            ?: "", fontSize = 12.sp, fontWeight = FontWeight.Medium, color = Color.Red)
                    }
                }
            }

        }
    }
}

@Composable
private fun VerifyCarView(orderInfo: OrderInfo?) {

    Column(modifier = Modifier
        .fillMaxWidth()
        .padding(10.dp)
        .background(color = Color.White, shape = RoundedCornerShape(6.dp))
        .padding(10.dp)) {
        Box(modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 10.dp), contentAlignment = Alignment.CenterStart) {
            Text(text = "请确认本次服务车辆信息".takeIf { orderInfo?.verifyType != 5 }
                ?: ("本次服务车辆为新车\n" +
                        "需要填写车架号 "), color = Color(0xFF323643), fontWeight = FontWeight.Medium, fontSize = 14.sp)
        }

        HorizontalDivider(modifier = Modifier.alpha(0.2f))

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

        Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
            Text(text = "车牌号:", color = black65, fontSize = 13.sp, fontWeight = FontWeight.Medium)
            Spacer(modifier = Modifier.width(10.dp))
            Text(text = orderInfo?.carNo
                ?: "", fontWeight = FontWeight.Medium, fontSize = 16.sp, color = Color.Black)
        }

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

        if (orderInfo?.verifyType == 5) {
            Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
                Text(text = "车架号:", color = black65, fontSize = 13.sp, fontWeight = FontWeight.Medium)
                Spacer(modifier = Modifier.width(10.dp))
                Text(text = orderInfo.carVin
                    ?: "", fontWeight = FontWeight.Medium, fontSize = 16.sp, color = Color.Black)
            }

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

            Box(modifier = Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
                AsyncImage(model = R.drawable.sv_verify_vin, contentDescription = "", modifier = Modifier.size(220.dp, 123.dp))
            }

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

        } else if (orderInfo?.verifyType == 1 || orderInfo?.verifyType == 2) {

            Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
                Text(text = "车架号:", color = black65, fontSize = 13.sp, fontWeight = FontWeight.Medium)
                Spacer(modifier = Modifier.width(10.dp))
                Text(text = orderInfo.carVin
                    ?: "", fontWeight = FontWeight.Medium, fontSize = 16.sp, color = Color.Black)
            }

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

        }

        Row(modifier = Modifier
            .fillMaxWidth()
            .background(color = Color(0xFFFFF7EE), shape = RoundedCornerShape(4.dp))
            .padding(vertical = 5.dp),
            horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically) {
            AsyncImage(model = R.drawable.sv_warn_yellow,
                contentDescription = "",
                modifier = Modifier.size(12.5.dp, 12.5.dp))
            Spacer(modifier = Modifier.width(5.dp))
            Text(text = "请确认以上信息至少一项符合否则将无法结算", fontSize = 12.sp, fontWeight = FontWeight.Medium, color = Color(0xFFFF8F37))
        }
    }
}

@Composable
private fun VerifyTipView(arriveRemind: String, arriveRemindUrl: String) {
    Column(modifier = Modifier
        .fillMaxWidth()
        .padding(10.dp)
        .background(color = Color.White, shape = RoundedCornerShape(6.dp))
        .padding(10.dp), horizontalAlignment = Alignment.CenterHorizontally) {
        Box(modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 10.dp), contentAlignment = Alignment.CenterStart) {
            Text(text = arriveRemind, color = Color(0xFF323643), fontWeight = FontWeight.Medium, fontSize = 14.sp)
        }

        HorizontalDivider(modifier = Modifier.alpha(0.2f))
        Spacer(modifier = Modifier.height(10.dp))
        if (arriveRemindUrl.endsWith("png")
            || arriveRemindUrl.endsWith("jpg")
            || arriveRemindUrl.endsWith("jpeg")
            || arriveRemindUrl.endsWith("WebP")
        ) {
            AsyncImage(model = arriveRemindUrl, contentDescription = "")
        } else {
            AsyncImage(model = QRCodeUtil.createQRCodeBitmap(arriveRemindUrl,
                width = ConvertUtils.dp2px(200f),
                height = ConvertUtils.dp2px(200f)), contentDescription = "")
        }
    }
}