<template>
  <el-dialog
      :model-value="visible"
      :title="title"
      width="400px"
      @close="handleClose"
      :close-on-click-modal="false"
  >
    <div v-if="note">
      <p>您确定要将笔记 <strong>"{{ note.title }}"</strong> {{ note.isPrivate === 1 ? '设为公开' : '设为私密' }}吗？</p>
      <div class="privacy-explanation">
        <el-icon><InfoFilled /></el-icon>
        <span>{{ explanation }}</span>
      </div>
    </div>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed } from 'vue';
import { ElMessage } from 'element-plus';
import { updateMarkdown } from '@/api/CommonApi.js';
import { InfoFilled } from '@element-plus/icons-vue';

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

const emit = defineEmits(['update:visible', 'privacy-changed']);

const title = computed(() => {
  if (!props.note) return '';
  return props.note.isPrivate === 1 ? '设为公开笔记' : '设为私密笔记';
});

const explanation = computed(() => {
  if (!props.note) return '';
  return props.note.isPrivate === 1 ? '公开笔记：所有用户都可以查看内容' : '私密笔记：只有登录用户才能查看内容';
});

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

const handleSubmit = async () => {
  if (!props.note) return;

  try {
    const newPrivacyStatus = props.note.isPrivate === 1 ? 0 : 1;
    const payload = {
      ...props.note,
      isPrivate: newPrivacyStatus,
    };

    const updatedFile = await updateMarkdown(payload);
    ElMessage.success(`笔记已${newPrivacyStatus === 1 ? '设为私密' : '设为公开'}`);
    emit('privacy-changed', updatedFile);
    handleClose();
  } catch (error) {
    // 错误已在 axios 拦截器中显示，这里不再重复显示
    console.error('修改笔记状态失败:', error);
  }
};
</script>

<style scoped>
.privacy-explanation {
  margin-top: 1rem;
  padding: 0.75rem;
  background-color: #f4f4f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #909399;
}
.dark-theme .privacy-explanation {
  background-color: #2c2c3e;
  color: #a9a9a9;
}
</style>
