<template>
  <el-dialog
      :model-value="visible"
      title="选择导入的分类"
      width="400px"
      @close="handleClose"
      :close-on-click-modal="false"
  >
    <el-cascader
        v-model="importGroupId"
        :options="categoryOptions"
        :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'grouping' }"
        clearable
        placeholder="请选择要导入的分类"
        style="width: 100%;"
    ></el-cascader>
    <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 { updateMarkdown } from '@/api/CommonApi.js';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  categoryOptions: {
    type: Array,
    default: () => [],
  },
  fileToImport: {
    type: File,
    default: null,
  }
});

const emit = defineEmits(['update:visible', 'import-success']);

const importGroupId = ref(null);

watch(() => props.visible, (newVal) => {
  if (!newVal) {
    importGroupId.value = null;
  }
});

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

const handleSubmit = () => {
  if (!importGroupId.value) {
    ElMessage.error('请选择要导入的分类');
    return;
  }
  if (!props.fileToImport) {
    ElMessage.error('没有需要导入的文件');
    return;
  }

  const reader = new FileReader();
  reader.onload = async (e) => {
    const content = e.target.result;
    const payload = {
      title: props.fileToImport.name.replace(/\.md$/, ''),
      groupingId: importGroupId.value,
      content: content,
      fileName: props.fileToImport.name,
    };
    try {
      await updateMarkdown(payload);
      ElMessage.success('Markdown 文件导入成功');
      emit('import-success');
      handleClose();
    } catch (error) {
      // 错误已在 axios 拦截器中显示，这里不再重复显示
      console.error('导入失败:', error);
    }
  };
  reader.readAsText(props.fileToImport);
};
</script>
