<template>
  <div class="note-editor-wrapper">
    <el-header class="editor-header">
      <h2 class="editor-title">{{ editData.title }}</h2>
      <div class="actions">
        <el-button type="primary" @click="handleBack">返回</el-button>
        <el-button type="success" @click="save">保存</el-button>
        <div class="save-status">
          <el-icon v-if="saveStatus === '正在输入...'" class="is-loading saving-icon"><Loading /></el-icon>
          <el-icon v-else-if="saveStatus === '保存失败'" class="error-icon"><CircleCloseFilled /></el-icon>
          <el-icon v-else-if="saveStatus === '已保存'" class="success-icon"><CircleCheckFilled /></el-icon>
        </div>
      </div>
    </el-header>
    <div id="vditor-editor" class="vditor" />
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import Vditor from 'vditor';
import 'vditor/dist/index.css';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Loading, CircleCloseFilled, CircleCheckFilled } from '@element-plus/icons-vue';
import { updateMarkdown, uploadImage } from '@/api/CommonApi.js';
import { useUserStore } from '@/stores/user';

const props = defineProps({
  editData: {
    type: Object,
    required: true,
  },
});

const emit = defineEmits(['back', 'update:editData']);

const vditor = ref(null);
const currentId = ref(null);
const isInitialized = ref(false);
const saveStatus = ref('');
const saveTimeout = ref(null);  // 修复：使用 ref 替代 let，确保响应式追踪
const lastSavedContent = ref('');
const isSaving = ref(false);
// 维护当前最新的笔记数据
const currentData = ref({ ...props.editData });
// 保存 beforeunload 事件处理器引用
let handleBeforeUnload = null;

const initVditor = () => {
  if (vditor.value) {
    vditor.value.destroy();
  }

  vditor.value = new Vditor('vditor-editor', {
    height: 'calc(100vh - 120px)',
    mode: 'ir',
    cache: {
      enable: false,
    },
    after: () => {
      isInitialized.value = true;
      if (currentData.value && currentData.value.content) {
        vditor.value.setValue(currentData.value.content);
        lastSavedContent.value = currentData.value.content;
      }
      if (currentData.value && currentData.value.id) {
        currentId.value = currentData.value.id;
      }
      vditor.value.focus();
    },
    input: (value) => {
      if (!isInitialized.value) return;

      // 只有在内容真正改变时才启动定时器
      if (value !== lastSavedContent.value) {
        clearTimeout(saveTimeout.value);
        saveStatus.value = '正在输入...';
        saveTimeout.value = setTimeout(() => {
          if (!isSaving.value && value !== lastSavedContent.value) {
            save(value);
          }
        }, 5000);
      }
    },
    upload: {
      accept: 'image/*',
      handler(files) {
        const file = files[0];
        if (!file) return;

        uploadImage(file).then(res => {
          // 后端返回相对路径，拼接成完整 URL
          const relativeUrl = res.url;
          const baseUrl = import.meta.env.VITE_API_BASE_URL || '';
          // 确保 URL 格式正确，避免双斜杠
          const fullUrl = baseUrl.endsWith('/') && relativeUrl.startsWith('/') 
            ? baseUrl + relativeUrl.substring(1) 
            : baseUrl + relativeUrl;
          vditor.value.insertValue(`![${file.name}](${fullUrl})`);
        }).catch((error) => {
          // 错误已在 axios 拦截器中显示，这里不再重复显示
          console.error('图片上传失败:', error);
        });
      },
    },
  });
};

const save = async (value) => {
  if (isSaving.value) return;

  // 修复：添加空值检查
  if (!vditor.value) {
    console.warn('编辑器未初始化');
    return;
  }

  clearTimeout(saveTimeout.value);
  const content = typeof value === 'string' ? value : vditor.value?.getValue() || '';

  if (content === lastSavedContent.value && currentId.value) {
    return;
  }

  isSaving.value = true;
  try {
    saveStatus.value = '正在保存...';

    // 确保groupingId不会丢失：优先使用currentData中的值
    const groupingId = currentData.value.groupingId || props.editData.groupingId;

    // 将ID转为字符串以避免JavaScript精度丢失
    const idString = currentId.value ? String(currentId.value) : (currentData.value.id ? String(currentData.value.id) : null);
    const groupingIdString = groupingId ? String(groupingId) : null;

    const payload = {
      id: idString,
      content: content,
      title: currentData.value.title || props.editData.title,
      groupingId: groupingIdString,
      fileName: currentData.value.fileName || props.editData.fileName,
      isPrivate: currentData.value.isPrivate !== undefined ? currentData.value.isPrivate : props.editData.isPrivate
    };

    const response = await updateMarkdown(payload);

    if (response && response.id) {
      currentId.value = response.id;
      lastSavedContent.value = content;

      // 使用后端返回的数据，但确保groupingId不会丢失
      // 注意：后端返回的ID是字符串，保持字符串格式避免精度丢失
      const updatedFile = {
        ...response,
        content: content,
        // 如果后端返回的groupingId为空，使用原来的值（保持字符串格式）
        groupingId: response.groupingId || groupingIdString,
        groupingName: response.groupingName || currentData.value.groupingName
      };

      // 更新currentData为最新数据
      currentData.value = updatedFile;
      emit('update:editData', updatedFile);
      saveStatus.value = '已保存';

      // 2秒后清除成功状态
      setTimeout(() => {
        if (saveStatus.value === '已保存') {
          saveStatus.value = '';
        }
      }, 2000);
    }
  } catch (error) {
    saveStatus.value = '保存失败';
    // 错误已在 axios 拦截器中显示，这里不再重复显示
    console.error('保存失败:', error);
  } finally {
    isSaving.value = false;
  }
};

const handleBack = async () => {
  // 清除定时器，防止返回后继续保存
  clearTimeout(saveTimeout.value);

  const content = vditor.value ? vditor.value.getValue() : '';
  const hasChanges = content !== lastSavedContent.value;

  // ADMIN 角色自动保存未保存的内容
  const userStore = useUserStore();
  if (hasChanges && !isSaving.value && userStore.userInfo?.role === 'ADMIN') {
    await save(content);
  }

  // 确保groupingId不会丢失（保持字符串格式）
  const groupingId = currentData.value.groupingId || props.editData.groupingId;
  const groupingName = currentData.value.groupingName || props.editData.groupingName;

  // 修复：普通用户有未保存内容时，返回最后保存的内容
  const finalContent = (hasChanges && userStore.userInfo?.role !== 'ADMIN')
    ? lastSavedContent.value
    : content;

  const returnData = {
    ...currentData.value,
    ...props.editData,
    id: currentId.value ? String(currentId.value) : (currentData.value.id ? String(currentData.value.id) : null),
    content: finalContent,
    groupingId: groupingId ? String(groupingId) : null,
    groupingName: groupingName
  };

  emit('back', returnData);
};

onMounted(() => {
  initVditor();

  // 页面刷新时提示用户保存
  handleBeforeUnload = (e) => {
    const content = vditor.value ? vditor.value.getValue() : '';
    if (content !== lastSavedContent.value && !isSaving.value) {
      e.preventDefault();
      e.returnValue = '您有未保存的内容，确定要离开吗？';
      return '您有未保存的内容，确定要离开吗？';
    }
  };

  window.addEventListener('beforeunload', handleBeforeUnload);
});

onBeforeUnmount(() => {
  // 清理定时器
  if (saveTimeout.value) {
    clearTimeout(saveTimeout.value);
    saveTimeout.value = null;
  }
  // 清理编辑器
  if (vditor.value) {
    vditor.value.destroy();
    vditor.value = null;
  }
  // 移除页面刷新提示
  if (handleBeforeUnload) {
    window.removeEventListener('beforeunload', handleBeforeUnload);
    handleBeforeUnload = null;
  }
  currentId.value = null;
  isInitialized.value = false;
});

watch(() => props.editData, (newVal, oldVal) => {
  if (vditor.value && isInitialized.value && newVal && newVal.id !== oldVal?.id) {
    // 更新currentData为最新的props数据
    currentData.value = { ...newVal };
    vditor.value.setValue(newVal.content || '');
    lastSavedContent.value = newVal.content || '';
    currentId.value = newVal.id;
    saveStatus.value = '';
  }
}, { deep: true });

</script>

<style scoped>
.note-editor-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  border-bottom: 1px solid #dcdfe6;
}

.editor-title {
  margin: 0;
  font-size: 20px;
}

.actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.save-status {
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.saving-icon {
  font-size: 20px;
  color: #409eff;
}

.success-icon {
  font-size: 20px;
  color: #67c23a;
  animation: fadeOut 2s ease-in-out forwards;
}

.error-icon {
  font-size: 20px;
  color: #f56c6c;
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  80% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}

.vditor {
  flex-grow: 1;
  border: none;
}
</style>