<template>
  <Panel
    class="vtj-code-factory-list"
    :tools="tools"
    :title="props.label"
    @tool-click="handleToolClick">
    <DataItem
      v-for="item in list"
      :key="item.name"
      :title="item.name"
      :active="current?.name === item.name"
      editable
      clickable
      @edit="handleEdit(item)"
      @click="handleEdit(item)"
      :removable="props.removable"
      @remove="handleRemove(item)"></DataItem>

    <ElEmpty
      v-if="!list.length"
      :image-size="50"
      description="您还没新增数据项"></ElEmpty>
  </Panel>
</template>
<script lang="ts" setup>
import Panel from './Panel.vue';
import DataItem from './DataItem.vue';
import { ElEmpty, ElMessageBox } from 'element-plus';
import { ref } from 'vue';
import { IFile } from '@vtj/engine';

export interface ListItem {
  name: string;
  value: any;
}

export interface Props {
  field: string;
  label: string;
  file: IFile;
  list: ListItem[];
  removable?: boolean;
  addable?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  removable: false,
  addable: false
});

const tools = props.addable
  ? [
      {
        name: 'add',
        icon: 'vtj-icon-plus'
      }
    ]
  : undefined;

const emit = defineEmits(['add', 'edit', 'remove']);

const current = ref();

const handleToolClick = (item: any) => {
  if (item.name === 'add') {
    current.value = null;
    emit('add', props.field);
  }
};

const handleEdit = (item: ListItem) => {
  current.value = item;
  emit('edit', item);
};

const handleRemove = (item: ListItem) => {
  ElMessageBox.confirm('是否确认删除?', '提示', {
    type: 'warning'
  })
    .then(() => {
      emit('remove', item.name);
    })
    .catch((e) => e);
};
</script>
