<template>
  <div class="array-editor">
    <div class="array-container">
      <div 
        v-for="(item, index) in localArray" 
        :key="index"
        class="array-item"
      >
        <value-editor
          v-model:modelValue="localArray[index]"
          @update:modelValue="updateArray"
          :forceOneLevel="forceOneLevel"
          class="array-item-input"
        />
        <ArrowUpOutlined title="上移" @click="upItem(index)" />
        <ArrowDownOutlined title="下移" @click="downItem(index)" />
        <a-popconfirm
          title="确定要删除这个项吗？"
          ok-text="确认"
          cancel-text="取消"
          @confirm="removeItem(index)"
        >
          <a-button 
            type="text" 
            danger 
            class="item-remove"
          >
            <DeleteOutlined title="删除" />
          </a-button>
        </a-popconfirm>
      </div>
      <a-button type="dashed" block @click="addItem">
        <plus-outlined /> 添加项
      </a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { ArrowDownOutlined, ArrowUpOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
import ValueEditor from './ValueEditor.vue';
import { ArrayUtils } from '@imengyu/imengyu-utils';

// 定义props
const props = defineProps<{
  modelValue?: any[];
  /**
   * 这会限制用户只能创建简单的值，而不能嵌套对象或数组。
   * @default false
   */
  forceOneLevel?: boolean;
}>();

const emit = defineEmits<{
  (e: 'update:modelValue', value: any[]): void;
}>();

// 本地数据
const localArray = ref<any[]>([]);

// 监听props变化
watch(
  () => props.modelValue,
  (newValue) => {
    if (newValue) {
      localArray.value = [...newValue];
    } else {
      localArray.value = [];
    }
  },
  { deep: true, immediate: true }
);

// 更新数组
const updateArray = () => {
  emit('update:modelValue', [...localArray.value]);
};

// 添加项
const addItem = () => {
  localArray.value.push('');
  updateArray();
};

// 上移项
const upItem = (index: number) => {
  ArrayUtils.upData(localArray.value, index);
  updateArray();
};

// 下移项
const downItem = (index: number) => {
  ArrayUtils.downData(localArray.value, index);
  updateArray();
};

// 删除项
const removeItem = (index: number) => {
  localArray.value.splice(index, 1);
  updateArray();
};
</script>

<style scoped>
.array-editor {
  width: 100%;
}

.array-container {
  width: 100%;
}

.array-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.array-item-input {
  flex: 1;
  margin-right: 8px;
}
</style>