<template>
    <div class="space-y-3">
        <div class="flex items-center justify-between beautify">
            <label class="text-sm font-medium text-gray-700">输入变量</label>
            <ElButton @click="addVariable" class="p-1  rounded bg-gray-100 transition-colors" title="添加变量">
                <Icon icon="lucide:plus" :height="16" :width="16" class="text-gray-600" />
            </ElButton>
        </div>

        <div class="space-y-2">
            <div v-for="(variable, index) in variables" :key="variable.name" class="flex items-center gap-2 group">
                <ElInput v-model="variable.id" type="text" placeholder="变量名"
                    class="w-1/3 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    @input="handleVariableChange" />
                <ElInput class="w-1/3" v-model="variable.name" placeholder="设置变量值" />

                <ElButton @click="removeVariable(index)"
                    class="w-1/3 p-1 opacity-50 group-hover:opacity-100 hover:bg-red-50 rounded transition-all"
                    title="删除变量">
                    <Icon icon="lucide:trash-2" :height="16" :width="16" class="text-red-500" />
                </ElButton>
            </div>

            <div v-if="variables.length === 0" class="text-sm text-gray-400 text-center py-4">
                <Icon icon="lucide:variable" :height="24" :width="25"></Icon>
                <p class="m-1">暂无输入变量</p>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { Icon } from '@iconify/vue'

interface Variable {
    name: string
    id: string
}

interface Props {
    modelValue: Variable[]
}

interface Emits {
    (e: 'update:modelValue', value: Variable[]): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const variables = ref<Variable[]>(props.modelValue || [])

watch(
    () => props.modelValue,
    (newVal) => {
        variables.value = newVal || []
    }
)
// 添加变量
const addVariable = () => {
    const newVariable: Variable = {
        id: '',
        name: ''
    }
    variables.value.push(newVariable)
    handleVariableChange()
}

// 删除变量
const removeVariable = (index: number) => {
    variables.value.splice(index, 1)
    handleVariableChange()
}

const handleVariableChange = () => {
    emit('update:modelValue', variables.value)
}
</script>

<style lang="less" scoped>
.beautify {
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
}
</style>
