<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, 'nodeParams')" class="addFormItem">
                    <el-icon :size="14">
                        <Plus />
                    </el-icon>
                </el-button>
            </template>
            <div class="form__container">
                <el-button type="primary" v-if="['AGV_MOVE_TO_POINT', 'ALM'].includes(props.data.properties.action)" size="small" @click="openRobotForm(props.data.properties.action)">获取位置</el-button>
                <el-form :inline="true" :model="formData" :rules="rules" ref="dynamicFormRef" label-position="top"
                    label-width="auto">
                    <div v-for="(property, index) in formData.nodeParams" :key="index">
                        <el-row>
                            <el-form-item :label="index === 0 ? '参数名' : ''" :prop="`nodeParams.${index}.name`"
                                :rules="[{ required: true, message: '请输入参数名', trigger: 'blur' }]">
                                <el-input :disabled="property?.disabled || false" class="param-name"
                                    v-model="property.name" placeholder="请输入" clearable />
                            </el-form-item>
                            <el-form-item :label="index === 0 ? '参数值' : ''" :prop="`nodeParams.${index}.type`">
                                <el-select v-model="property.type" class="param-type" @change="handleTypeChange(index, formData, property.type)">
                                    <el-option label="引用" value="quote" />
                                    <el-option label="输入" value="input" />
                                </el-select>
                                <el-form-item v-if="property.type === 'input'"
                                    :rules="testRule(property)"
                                    :prop="`nodeParams.${index}.input`">
                                    <el-input-number class="param-value" v-if="property.componentType === 'number'"
                                        v-model="property.input" :min="0" :max="property.max || Infinity"
                                        :controls="false" :step-strictly="true" placeholder="请输入" clearable />
                                    <el-select v-model="property.input" class="param-value"
                                        v-else-if="property.componentType === 'select'">
                                        <el-option v-for="item in property.selectOptions" :key="item.value"
                                            :label="item.label" :value="item.value" />
                                    </el-select>
                                    <el-input class="param-value" v-else v-model="property.input" placeholder="请输入"
                                        clearable />
                                </el-form-item>
                                <el-form-item v-if="property.type === 'quote'"
                                    :rules="[{ required: true, message: '请选择参数值', trigger: 'blur' }]"
                                    :prop="`nodeParams.${index}.quote`">
                                    <el-cascader :ref="(el) => { if (el) cascaderRefs[index] = el }"
                                        v-model="property.quote" :checkStrictly="true" :options="quoteOptions"
                                        placeholder="请选择"
                                        @visible-change="(visible) => visibleChange(visible, index, property.quote)"
                                        @change="(value) => cascaderChange(value, index, formData, 'nodeParams')" />
                                </el-form-item>
                            </el-form-item>
                            <el-button :icon="Minus" circle size="small" :disabled="property?.disabled || false"
                                @click="handleDelete(index)" class="deleteBtn" />
                        </el-row>
                    </div>
                </el-form>
            </div>
        </el-collapse-item>

        <!-- 输出参数 -->
        <el-collapse-item name="2" icon-position="left">
            <template #title>
                输出参数
                <el-button :circle="true" size="small" @click="(e) => addFormItem(e, 'outputParams')"
                    class="addFormItem">
                    <el-icon :size="14">
                        <Plus />
                    </el-icon>
                </el-button>
            </template>
            <div class="form__container">
                <el-form :inline="true" :model="formData" label-position="top" label-width="auto" :rules="outputRules"
                    ref="outputFormRef">
                    <FormItemRecursive formType="output" :current-list="formData.outputParams" prop-path="outputParams"
                        :depth="0" :is-first-level="true" :endDepth="2" :parent-path="[]"
                        @delete-item="(path) => deleteTopLevelItem(path, 'outputParams')" />
                </el-form>
            </div>
        </el-collapse-item>
    </el-collapse>

     <el-dialog
        v-model="dialogVisible"
        title="获取位置信息"
        width="360"
    >
        <el-form ref="robotFormRef" :model="robotForm" :rules="robotFormRules"  label-width="auto">
            <el-form-item label="终端ID" prop="terminalId">
                <el-input v-model="robotForm.terminalId" />
            </el-form-item>
            <el-form-item label="设备ID" prop="deviceId">
                <el-input v-model="robotForm.deviceId" />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitRobotForm">确认</el-button>
        </template>
    </el-dialog>
</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'
import { getArmStatus } from '@/api/device/flow'
import { de } from 'element-plus/es/locale/index.mjs'

const props = defineProps({
    data: Object
})

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

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

const rules = reactive({})
const outputRules = reactive({})
const dynamicFormRef = ref()
const outputFormRef = ref()
const activeNames = ref(['1', '2'])

// 使用共享的 quote 逻辑
const { quoteOptions, cascaderRefs, handleTypeChange, cascaderChange, visibleChange } = useQuote(props.data.id)

// 添加表单项
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)
}

// 删除输入参数（非递归）
const handleDelete = (index) => {
    formData.nodeParams.splice(index, 1)
}

// 删除顶层输出参数（递归删除通过 FormItemRecursive 的 emit 处理）
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)
}

// 初始化数据
const initData = () => {
    const nodeParams = JSON.parse(JSON.stringify(props.data.properties.nodeParams || []))
    const outputParams = JSON.parse(JSON.stringify(props.data.properties.outputParams || []))
    formData.nodeParams = nodeParams;
    formData.outputParams = outputParams;
}

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

// 保存验证
const validateAndSave = async () => {
    let inputValid = true
    let outputValid = true
    if (dynamicFormRef.value) {
        await dynamicFormRef.value.validate((valid) => { if (!valid) inputValid = false })
    }
    if (outputFormRef.value) {
        await outputFormRef.value.validate((valid) => { if (!valid) outputValid = false })
    }

    // 保存到 lf
    lf.setProperties(props.data.id, {
        ...props.data.properties,
        ...formData
    })

    if (inputValid && outputValid) {
        emit('save-success')
    } else {
        emit('save-error')
    }
}

const dialogVisible = ref(false)
const robotFormRef = ref(null)
const robotFormRules = reactive({
    terminalId: [{ required: true, message: '终端ID不能为空', trigger: 'blur' }],
    deviceId: [{ required: true, message: '设备ID不能为空', trigger: 'blur' }]
})
const robotForm = reactive({
    deviceId: '',
    terminalId: ''
})

const testRule = (property) => {
    if (property?.name === 'acceleration') {
        return [
            { required: true, message: '请输入参数值', trigger: 'blur' },
            { validator: () => {
                if (formData.nodeParams.find(param => param.name === 'acceleration')?.input > formData.nodeParams.find(param => param.name === 'velocity')?.input) {
                    return Promise.resolve()
                } else {
                    return Promise.reject(new Error('加速度必须大于速度'))
                }
            }, trigger: 'blur' }
        ]

    }
    return [{ required: property?.required ?? true, message: '请输入参数值', trigger: 'blur' }]
}

const robotFormAction = ref()

const submitRobotForm = () => {
    if (robotFormAction.value === 'AGV_MOVE_TO_POINT') {
        
    } else if (robotFormAction.value === 'ALM') {
        robotFormRef.value.validate(async (valid) => {
            if (valid) {
                try {
                    const response = await getArmStatus({ deviceId: robotForm.deviceId, terminalId: robotForm.terminalId })
                    if (response && response.data) {
                        dialogVisible.value = false
                        const { x, y, z, rx, ry, rz } = response.data
                        const testMap = {
                            x: x,
                            y: y,
                            z: z,
                            rx: rx,
                            ry: ry,
                            rz: rz,
                            deviceId: robotForm.deviceId
                        }
                        // 将获取到的位置信息设置到 formData 中
                        formData.nodeParams.forEach(param => {
                            if (testMap.hasOwnProperty(param.name)) {
                                param.input = testMap[param.name]
                            }
                        })
                    }
                } catch (error) {
                    console.error('获取位置信息失败:', error)
                }
            }
        })
    }
}

const openRobotForm = (action) => {
    dialogVisible.value = true
    robotFormAction.value = action
}

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>