<template>
  <div class="article-editor">
    <h2>{{ isEdit ? '编辑文章' : '写文章' }}</h2>
    <el-form :model="form" label-width="80px">
      <el-form-item label="标题">
        <el-input v-model="form.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="form.categoryId" placeholder="选择分类" clearable>
          <el-option v-for="cat in categories" :key="cat.id" :label="cat.name" :value="cat.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="标签">
        <el-select v-model="form.tagIds" multiple placeholder="选择标签（最多5个）" :max-collapse-tags="5">
          <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="内容">
        <div class="editor-wrapper">
          <div v-if="editor" class="toolbar">
            <el-button-group>
              <el-button size="small" @click="editor.chain().focus().toggleBold().run()" :type="editor.isActive('bold') ? 'primary' : ''">B</el-button>
              <el-button size="small" @click="editor.chain().focus().toggleItalic().run()" :type="editor.isActive('italic') ? 'primary' : ''">I</el-button>
              <el-button size="small" @click="editor.chain().focus().toggleHeading({ level: 2 }).run()" :type="editor.isActive('heading', { level: 2 }) ? 'primary' : ''">H2</el-button>
              <el-button size="small" @click="editor.chain().focus().toggleHeading({ level: 3 }).run()" :type="editor.isActive('heading', { level: 3 }) ? 'primary' : ''">H3</el-button>
              <el-button size="small" @click="editor.chain().focus().toggleBulletList().run()" :type="editor.isActive('bulletList') ? 'primary' : ''">列表</el-button>
              <el-button size="small" @click="editor.chain().focus().toggleBlockquote().run()" :type="editor.isActive('blockquote') ? 'primary' : ''">引用</el-button>
              <el-button size="small" @click="editor.chain().focus().setHorizontalRule().run()">分割线</el-button>
            </el-button-group>
          </div>
          <EditorContent :editor="editor" class="editor-content" />
        </div>
      </el-form-item>
      <el-form-item label="摘要">
        <el-input v-model="form.summary" type="textarea" :rows="2" placeholder="文章摘要" />
      </el-form-item>
      <el-form-item label="可见性">
        <el-radio-group v-model="form.visibility">
          <el-radio :value="0">公开</el-radio>
          <el-radio :value="1">私密</el-radio>
          <el-radio :value="2">仅粉丝</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit(false)" :loading="saving">保存草稿</el-button>
        <el-button type="success" @click="handleSubmit(true)" :loading="saving">发布</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useEditor, EditorContent } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
import Placeholder from '@tiptap/extension-placeholder'
import { createArticle, updateArticle, getArticleDetail, getCategories, getTags } from '@/api/article'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const isEdit = computed(() => !!route.params.id)
const saving = ref(false)
const categories = ref([])
const tags = ref([])
const form = ref({
  title: '',
  categoryId: null,
  tagIds: [],
  summary: '',
  visibility: 0,
  allowComment: true,
})

const editor = useEditor({
  extensions: [
    StarterKit,
    Placeholder.configure({ placeholder: '开始写作...' }),
  ],
  content: '',
})

async function loadCategories() {
  const res = await getCategories()
  categories.value = res.data
}

async function loadTags() {
  const res = await getTags()
  tags.value = res.data
}

async function loadArticle() {
  if (!isEdit.value) return
  const res = await getArticleDetail(route.params.id)
  const article = res.data
  form.value.title = article.title
  form.value.categoryId = article.categoryId
  form.value.tagIds = article.tags?.map(t => t.id) || []
  form.value.summary = article.summary
  form.value.visibility = article.visibility
  if (editor.value) {
    editor.value.commands.setContent(article.content || '')
  }
}

async function handleSubmit(publish) {
  if (!form.value.title) {
    ElMessage.warning('请输入标题')
    return
  }
  saving.value = true
  try {
    const data = {
      ...form.value,
      content: editor.value?.getHTML() || '',
      status: publish ? 1 : 0,
    }
    if (isEdit.value) {
      await updateArticle(route.params.id, data)
      ElMessage.success('更新成功')
    } else {
      const res = await createArticle(data)
      ElMessage.success(publish ? '发布成功' : '已保存草稿')
      if (!isEdit.value) {
        router.push(`/app/editor/${res.data}`)
      }
    }
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadCategories()
  loadTags()
  loadArticle()
})

onBeforeUnmount(() => {
  editor.value?.destroy()
})
</script>

<style scoped>
.article-editor { max-width: 900px; }
.editor-wrapper { border: 1px solid #dcdfe6; border-radius: 4px; width: 100%; }
.toolbar { padding: 8px; border-bottom: 1px solid #dcdfe6; background: #fafafa; }
.editor-content { min-height: 400px; padding: 16px; }
.editor-content :deep(.tiptap) { outline: none; min-height: 360px; }
.editor-content :deep(.tiptap p.is-editor-empty:first-child::before) {
  content: attr(data-placeholder);
  float: left;
  color: #adb5bd;
  pointer-events: none;
  height: 0;
}
</style>
