<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(props.item.id, newName.value);
    } else {
      await updateGroupingName(props.item.id, newName.value);
    }
    ElMessage.success('重命名成功');
    handleClose();
    // 传递新名称给父组件
    emit('renamed', newName.value);
  } catch (error) {
    // 错误已在 axios 拦截器中显示，这里不再重复显示
    console.error('重命名失败:', error);
  }
};
</script>
