<template>
  <el-dialog
      :model-value="visible"
      title="重命名"
      width="400px"
      @close="handleClose"
      :close-on-click-modal="false"
  >
    <el-input v-model="newName" placeholder="请输入新名称" @keyup.enter="handleSubmit"></el-input>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { updateMarkdownTitle, updateGroupingName } from '@/api/CommonApi.js';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  item: {
    type: Object,
    default: () => null,
  },
});

const emit = defineEmits(['update:visible', 'renamed']);

const newName = ref('');

watch(() => props.item, (newItem) => {
  if (newItem) {
    newName.value = newItem.type === 'file' ? newItem.title : newItem.grouping;
  }
});

const handleClose = () => {
  emit('update:visible', false);
};

const handleSubmit = async () => {
  if (!newName.value.trim()) {
    ElMessage.error('名称不能为空');
    return;
  }
  try {
    if (props.item.type === 'file') {
      await updateMarkdownTitle({ id: props.item.id, title: newName.value });
    } else {
      await updateGroupingName({ id: props.item.id, grouping: newName.value });
    }
    ElMessage.success('重命名成功');
    emit('renamed');
    handleClose();
  } catch (error) {
    ElMessage.error('重命名失败: ' + error.message);
  }
};
</script>
