<!--
 * 文件说明：开始节点参数面板，配置流程入口参数。
 * 作用范围：仅服务于流程设计器模块。
 -->
<template>
    <el-collapse v-model="activeNames">
        <el-collapse-item name="1" icon-position="left">
            <template #title>
                输入参数
                <el-button :circle="true" size="small" @click="(e) => addFormItem(e, 'inputParams')" class="addFormItem">
                    <el-icon :size="14">
                        <Plus />
                    </el-icon>
                </el-button>
            </template>
            <el-form :inline="true" :model="formData" :rules="rules" ref="dynamicFormRef" label-position="top"
                label-width="auto">
                <FormItemRecursive formType="input" :current-list="formData.inputParams" prop-path="inputParams"
                    :depth="0" :is-first-level="true" :endDepth="2" :parent-path="[]"
                    @delete-item="(path) => deleteTopLevelItem(path, 'inputParams')" />
            </el-form>
        </el-collapse-item>
    </el-collapse>
</template>

<script setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { Plus, Minus } from '@element-plus/icons-vue'
import FormItemRecursive from '../FormItemRecursive.vue'
import { getInput } from '@/utils/flow'
import { useQuote } from './useQuote.js'

const props = defineProps({
    data: Object
})

const emit = defineEmits(['save-success', 'save-error'])

const formData = reactive({
    inputParams: [],
})

const rules = reactive({})
const dynamicFormRef = ref()

const activeNames = ref(['1', '2'])

// 添加表单项
/**
 * 新增 addFormItem 对应的数据或交互；作用范围仅限当前组件或模块。
 * @param {*} e 触发操作的浏览器事件
 * @param {*} type 目标类型
 */
const addFormItem = (e, type) => {
    e.stopPropagation()
    const obj = {
        name: '',
        type: type === 'nodeParams' ? 'input' : 'string',
        required: false,
        children: [],
        input: ''
    }
    if (!formData[type]) formData[type] = []
    formData[type].push(obj)
}

// 删除输入参数（非递归）
/**
 * 处理 handleDelete 对应的数据或交互；作用范围仅限当前组件或模块。
 * @param {*} index 目标项索引
 */
const handleDelete = (index) => {
    formData.nodeParams.splice(index, 1)
}

// 删除顶层输出参数（递归删除通过 FormItemRecursive 的 emit 处理）
/**
 * 删除 deleteTopLevelItem 对应的数据或交互；作用范围仅限当前组件或模块。
 * @param {*} fullPath 字段完整路径
 * @param {*} propPath 字段校验路径
 */
const deleteTopLevelItem = (fullPath, propPath) => {
    let currentLevel = formData[propPath]
    for (let i = 0; i < fullPath.length - 1; i++) {
        currentLevel = currentLevel[fullPath[i]].children
    }
    const lastIndex = fullPath[fullPath.length - 1]
    currentLevel.splice(lastIndex, 1)
}

// 初始化数据
/**
 * 初始化 initData 对应的数据或交互；作用范围仅限当前组件或模块。
 */
const initData = () => {
    const inputParams = JSON.parse(JSON.stringify(props.data.properties.inputParams || []))
    formData.inputParams = inputParams;
}

watch(
    () => props.data,
    () => {
        initData()
    },
    { immediate: true, deep: true }
)

// 保存验证
/**
 * 校验 validateAndSave 对应的数据或交互；作用范围仅限当前组件或模块。
 */
const validateAndSave = async () => {
    let inputValid = true
    if (dynamicFormRef.value) {
        await dynamicFormRef.value.validate((valid) => { if (!valid) inputValid = false })
    }

    // 保存到 lf
    lf.setProperties(props.data.id, {
        ...props.data.properties,
        ...formData
    })
    if (inputValid) {
        emit('save-success')
    } else {
        emit('save-error')
    }
}

defineExpose({ validateAndSave })
</script>

<style lang="scss" scoped>
.form__container {
    margin: 12px 0;

    :deep(.el-row) {
        align-items: end;

        .el-form-item {
            margin-right: 12px;
        }

        .param-name {
            width: 160px;
        }

        .param-type {
            width: 80px;
        }

        .param-value {
            width: 160px;
        }

    }



    .sub-properties {
        margin-left: 10px;

        .zw {
            margin-left: 15px;

            &::before {
                content: "";
                position: absolute;
                left: 0;
                top: -4px;
                width: 10px;
                border-left: 1px solid gray;
                border-bottom: 1px solid gray;
                border-bottom-left-radius: 4px;
                background-color: transparent;
                height: 24px;
            }
        }
    }

    .gSon-properties {
        margin-left: 10px;

        .zw {
            margin-left: 15px;

            &::before {
                content: "";
                position: absolute;
                left: 0;
                top: -4px;
                width: 10px;
                border-left: 1px solid gray;
                border-bottom: 1px solid gray;
                border-bottom-left-radius: 4px;
                background-color: transparent;
                height: 24px;
            }
        }
    }

    .deleteBtn {
        margin-bottom: 22px;
        cursor: pointer;
    }
}
</style>
