package com.iscs.bozzys.ui.pages.edit.step

import android.content.Context
import android.content.Intent
import android.view.WindowManager
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
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.WindowInsets
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.ime
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
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.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.zIndex
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewmodel.compose.viewModel
import com.iscs.bozzys.R
import com.iscs.bozzys.event.RefreshEvent
import com.iscs.bozzys.event.RefreshEventBus
import com.iscs.bozzys.ui.common.PageBase
import com.iscs.bozzys.ui.dialog.TipsDialog
import com.iscs.bozzys.ui.common.Title
import com.iscs.bozzys.ui.pages.compose.CardBox
import com.iscs.bozzys.ui.pages.compose.FormBox
import com.iscs.bozzys.ui.pages.create.job.openPagePushJob
import com.iscs.bozzys.ui.pages.edit.step.compose.NodeItem
import com.iscs.bozzys.ui.pages.edit.step.compose.ZoomPanContainer
import com.iscs.bozzys.ui.pages.vm.VMEditStep
import com.iscs.bozzys.ui.theme.Text
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 跳转到编辑流程页面
 */
fun Context.openPageEditStep(id: Int) {
    // 传递作业票id进入页面
    startActivity(Intent(this, PageEditStep::class.java).apply {
        putExtra("id", id)
    })
}

class PageEditStep : PageBase() {
    @Composable
    override fun GetViews(pv: PaddingValues) {
        val vm: VMEditStep = viewModel()
        val state by vm.state.collectAsState()
        LaunchedEffect(Unit) {
            vm.toast.initToast()
            vm.loading.initLoading()
            vm.init(intent.getIntExtra("id", 0))
        }
        // 页面布局容器
        Column(Modifier.fillMaxSize()) {
            Title(pv, "作业流程管理")
            Box(Modifier.weight(1f)) {
                ZoomPanContainer(
                    state.nodes,
                    state.connections,
                    modifier = Modifier.fillMaxSize()
                ) { scale, toTopCenter, toCenter, toLast ->
                    // 控件显示
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .zIndex(3f),
                        contentAlignment = Alignment.CenterStart
                    ) {
                        state.nodes.forEach {
                            NodeItem(it.key, state.nodes, state.node, { node ->
                                vm.updateNode(node)
                                // 将当前Node平移到屏幕中间
                                toTopCenter(node)
                                lifecycleScope.launch {
                                    // 给移动位置增加点动画效果
                                    delay(280)
                                    // 弹出Dialog
                                    vm.formDialogShow(true)
                                }
                            })
                        }
                    }
                    // 底部弹出式的Dialog
                    FormDialog(state.showFormDialog, {
                        // 回到移动中心位置前的位置，默认不添加 等反馈
                        toLast()
                        vm.formDialogShow(false)
                    }, pv, title = state.node.value.node?.nodeName ?: "") {

                        // 监听键盘弹出事件
                        val density = LocalDensity.current
                        val imeInsets = WindowInsets.ime
                        val imeBottom = imeInsets.getBottom(density)

                        Column(
                            Modifier
                                .fillMaxHeight(4 / 7f)
                                .padding(horizontal = 16.dp)
                        ) {
                            Box(
                                Modifier
                                    .fillMaxSize()
                                    .weight(1f)
                            ) {
                                LazyColumn(
                                    Modifier
                                        .imePadding()
                                        .padding(vertical = 5.dp)
                                ) {
                                    item { FormBox(state.nodeForms, { vm.onNodeFormChanged(it) }, enabled = state.enableEdit) }
                                }
                            }
                            if (imeBottom <= 0) {
                                Spacer(Modifier.height(10.dp))
                                if (state.enableEdit) Button(
                                    {
                                        vm.onNodeSave {
                                            // 优化体验，这里如果保存成功，自动检测是否需要进行下一步操作
                                            vm.onNext { complete, node ->
                                                if (node != null) {
                                                    // 刷新节点位置
                                                    vm.updateNode(node)
                                                    // 将当前Node平移到屏幕中间
                                                    RefreshEventBus.onRefreshData(RefreshEvent.UpdateNodeToMapTopCenter.apply { value = node })
                                                    lifecycleScope.launch {
                                                        // 给移动位置增加点动画效果
                                                        delay(280)
                                                        // 弹出Dialog
                                                        vm.formDialogShow(true)
                                                    }
                                                }
                                                if (complete) {
                                                    vm.showTipsDialog("提示", "当前任务节点信息都已录入，确认要进行下一步操作吗？")
                                                }
                                            }
                                        }
                                    },
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .height(50.dp)
                                        .clip(RoundedCornerShape(12.dp))
                                        .background(MaterialTheme.colorScheme.primary),
                                    shape = RoundedCornerShape(12.dp)
                                ) {
                                    Text("保存", fontSize = 16.sp, fontWeight = FontWeight.Bold)
                                }
                            }
                        }
                    }
                }
            }
            // 底部下一步按钮
            if (state.enableEdit) Column(
                Modifier
                    .fillMaxWidth()
                    .background(MaterialTheme.colorScheme.background)
                    .padding(top = 15.dp, bottom = (15f + pv.calculateBottomPadding().value).dp)
            ) {
                Button(
                    onClick = {
                        vm.onNext { complete, node ->
                            if (node != null) {
                                // 刷新节点位置
                                vm.updateNode(node)
                                // 将当前Node平移到屏幕中间
                                RefreshEventBus.onRefreshData(RefreshEvent.UpdateNodeToMapTopCenter.apply { value = node })
                                lifecycleScope.launch {
                                    // 给移动位置增加点动画效果
                                    delay(280)
                                    // 弹出Dialog
                                    vm.formDialogShow(true)
                                }
                            }
                            if (complete) {
                                vm.showTipsDialog("提示", "当前任务节点信息都已录入，确认要进行下一步操作吗？")
                            }
                        }
                    }, modifier = Modifier
                        .padding(horizontal = 16.dp)
                        .fillMaxWidth()
                        .height(50.dp)
                        .clip(RoundedCornerShape(12.dp))
                        .background(MaterialTheme.colorScheme.primary),
                    shape = RoundedCornerShape(12.dp)
                ) {
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Text("下一步", fontSize = 16.sp, fontWeight = FontWeight.Bold)
                        Icon(
                            painter = painterResource(R.drawable.next),
                            contentDescription = "",
                            modifier = Modifier
                                .padding(start = 5.dp)
                                .size(16.dp)
                        )
                    }
                }
            }
        }
        // Dialog
        TipsDialog(show = state.showTipsDialog, content = state.showTipsDialogContent, onCancel = {
            vm.hideTipsDialog()
        }, onConfirm = {
            vm.hideTipsDialog()
            openPagePushJob(intent.getIntExtra("id", 0))
            // 这里需要跳转到下一个页面，且关闭当前页面
            destroyDelay(500)
        })
    }


}

@Composable
fun FormDialog(
    show: Boolean,
    onDismiss: () -> Unit,
    paddingValues: PaddingValues = PaddingValues(0.dp),
    title: String = "",
    content: @Composable () -> Unit
) {
    val ctx = LocalContext.current
    if (!show || ctx !is PageBase) return
    val scope = rememberCoroutineScope()
    // 默认放到屏幕外部
    val offsetY = remember { Animatable(1f) }
    val pvb = paddingValues.calculateBottomPadding()
    val pb = if (pvb.value > 0) pvb else 10.dp

    LaunchedEffect(Unit) {
        ctx.setNavigationLight(false)
        // 底部弹出动画处理
        offsetY.animateTo(
            targetValue = 0f,
            animationSpec = spring(dampingRatio = 0.85f, stiffness = 300f)
        )
    }

    Dialog(
        onDismissRequest = onDismiss,
        properties = DialogProperties(decorFitsSystemWindows = false)
    ) {
        val activityWindow = ctx.window
        val dialogWindow = ctx.getDialogWindow()
        SideEffect {
            if (activityWindow != null && dialogWindow != null) {
                val attributes = WindowManager.LayoutParams()
                // 复制Activity窗口属性
                attributes.copyFrom(activityWindow.attributes)
                // 这个一定要设置
                attributes.type = dialogWindow.attributes.type
                // 更新窗口属性
                dialogWindow.attributes = attributes
                // 设置窗口的宽度和高度，这段代码Dialog源码中就有哦，可以自己去查看
                dialogWindow.setLayout(
                    activityWindow.decorView.width,
                    activityWindow.decorView.height
                )
            }
        }
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Black.copy(alpha = 0.4f))
                .clickable(
                    indication = null,
                    interactionSource = remember { MutableInteractionSource() }) {
                    scope.launch {
                        offsetY.animateTo(1f, tween(200))
                        onDismiss()
                    }
                },
            contentAlignment = Alignment.BottomCenter
        ) {
            CardBox(
                topRadius = 16.dp,
                bottomRadius = 0.dp,
                modifier = Modifier
                    .graphicsLayer { translationY = offsetY.value * size.height }
                    .fillMaxWidth()
                    // 防止点击穿透
                    .clickable(
                        indication = null,
                        interactionSource = remember { MutableInteractionSource() },
                        onClick = {})
                    .background(Color.White, RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp))
            ) {
                Column(
                    Modifier
                        .fillMaxWidth()
                        .padding(bottom = pb)
                ) {
                    Row(
                        Modifier
                            .fillMaxWidth()
                            .height(40.dp)
                            .padding(horizontal = 16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Spacer(Modifier.size(40.dp))
                        Text(
                            title,
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Bold,
                            color = Text,
                            modifier = Modifier.weight(1f),
                            textAlign = TextAlign.Center
                        )
                        Icon(
                            painter = painterResource(R.drawable.close),
                            contentDescription = null,
                            modifier = Modifier
                                .offset(8.dp, 0.dp)
                                .size(36.dp)
                                .clip(RoundedCornerShape(50))
                                .clickable(onClick = {
                                    scope.launch {
                                        offsetY.animateTo(1f, tween(200))
                                        onDismiss()
                                    }
                                })
                                .padding(10.dp)
                        )
                    }
                    Spacer(
                        Modifier
                            .fillMaxWidth()
                            .height(0.5.dp)
                            .background(Color.Black.copy(alpha = 0.05f))
                    )
                    content()
                }
            }
        }
    }
}

