<script setup>
import { Delete, Plus } from "@element-plus/icons-vue";

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [{ key: "", value: "" }],
  },
  keyPlaceholder: {
    type: String,
    default: "Key",
  },
  valuePlaceholder: {
    type: String,
    default: "Value",
  },
  addLabel: {
    type: String,
    default: "新增一行",
  },
});

const emit = defineEmits(["update:modelValue"]);

function updateRows(nextRows) {
  emit("update:modelValue", nextRows);
}

function updateRow(index, field, value) {
  const nextRows = props.modelValue.map((row, rowIndex) =>
    rowIndex === index ? { ...row, [field]: value } : row
  );
  updateRows(nextRows);
}

function addRow() {
  updateRows([...props.modelValue, { key: "", value: "" }]);
}

function removeRow(index) {
  const nextRows = props.modelValue.slice();
  nextRows.splice(index, 1);
  if (!nextRows.length) {
    nextRows.push({ key: "", value: "" });
  }
  updateRows(nextRows);
}
</script>

<template>
  <div class="kv-editor">
    <div class="kv-editor__head">
      <span class="kv-editor__col">Key</span>
      <span class="kv-editor__col">Value</span>
      <span class="kv-editor__action" aria-hidden="true" />
    </div>

    <div class="kv-editor__list">
      <div v-for="(row, index) in modelValue" :key="index" class="kv-editor__row">
        <el-input :model-value="row.key" :placeholder="keyPlaceholder" @update:model-value="updateRow(index, 'key', $event)" />
        <el-input
          :model-value="row.value"
          :placeholder="valuePlaceholder"
          @update:model-value="updateRow(index, 'value', $event)"
        />
        <el-button circle :icon="Delete" text type="danger" @click="removeRow(index)" />
      </div>
    </div>

    <el-button :icon="Plus" text type="primary" class="kv-editor__add" @click="addRow">
      {{ addLabel }}
    </el-button>
  </div>
</template>
