<template>
  <div class="post-container">
    <h1 class="page-title">发布新帖子</h1>
    <div class="editor-wrapper">
      <form @submit.prevent="submitForm">
        <!-- 标题输入 -->
        <div class="form-row">
          <label>标题</label>
          <input
            v-model="form.title"
            type="text"
            maxlength="50"
            placeholder="请输入标题（3-50个字符）"
            required
          />
        </div>

        <!-- 分类选择 -->
        <div class="form-row">
          <label>分类</label>
          <select v-model="form.categoryId" required>
            <option disabled value="">请选择分类</option>
            <option v-for="cat in categories" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
          </select>
        </div>

        <!-- 图片上传 -->
        <div class="form-row">
          <label>图片</label>
          <input type="file" accept="image/*" @change="onFileChange" />
          <div v-if="form.imagePreview" class="img-preview">
            <img :src="form.imagePreview" alt="预览" />
            <button type="button" @click="removeImage">移除</button>
          </div>
        </div>

        <!-- 内容编辑器 -->
        <div class="form-row">
          <label>内容</label>
          <textarea
            v-model="form.content"
            rows="8"
            placeholder="请输入帖子内容（支持Markdown语法）"
            required
          ></textarea>
        </div>

        <!-- 提交按钮 -->
        <div class="submit-area">
          <button type="submit" :disabled="submitting">
            {{ submitting ? '发布中...' : '立即发布' }}
          </button>
        </div>
      </form>
    </div>

    <!-- 操作反馈 -->
    <div v-if="submitResult.visible" :class="['result-alert', submitResult.type]">
      {{ submitResult.title }}
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

export default {
  setup() {
    const router = useRouter()
    const submitting = ref(false)
    const categories = ref([
      { id: 1, name: '学习' },
      { id: 2, name: '娱乐' },
      { id: 3, name: '二手交易' }
    ])
    const form = ref({
      title: '',
      content: '',
      categoryId: '',
      image: '',
      imagePreview: '',
      status: 0
    })
    const submitResult = ref({
      visible: false,
      type: 'success',
      title: ''
    })

    // 处理图片选择和上传
    const onFileChange = async (e) => {
      const file = e.target.files[0]
      if (!file) return
      // 预览
      form.value.imagePreview = URL.createObjectURL(file)
      // 上传到后端
      const fd = new FormData()
      fd.append('file', file)
      try {
        const res = await request.post('/post/cover', fd, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        if (res.code === 200 && res.data) {
          form.value.image = res.data
        } else {
          showResult('error', res.msg || '图片上传失败')
        }
      } catch (err) {
        showResult('error', '图片上传失败')
      }
    }

    const removeImage = () => {
      form.value.image = ''
      form.value.imagePreview = ''
    }

    // 提交表单
    const submitForm = async () => {
      if (!form.value.title || !form.value.content || !form.value.categoryId) {
        showResult('error', '请填写完整信息')
        return
      }
      if (form.value.title.length < 3 || form.value.title.length > 50) {
        showResult('error', '标题长度需3-50字符')
        return
      }
      if (form.value.content.length < 10) {
        showResult('error', '内容至少10个字符')
        return
      }
      submitting.value = true
      try {
        const postData = {
          title: form.value.title,
          content: form.value.content,
          categoryId: form.value.categoryId,
          image: form.value.image,
          status: form.value.status
        }
        const res = await request.post('/post', postData)
        if (res.code === 200) {
          showResult('success', '帖子发布成功')
          console.log(res.data);
          setTimeout(() => {
            router.push(`/`)
          }, 1200)
        } else {
          showResult('error', res.msg || '发布失败')
        }
      } catch (err) {
        showResult('error', '网络错误')
      } finally {
        submitting.value = false
      }
    }

    const showResult = (type, title) => {
      submitResult.value = { visible: true, type, title }
      setTimeout(() => {
        submitResult.value.visible = false
      }, 2000)
    }

    return {
      form,
      categories,
      submitting,
      submitResult,
      onFileChange,
      removeImage,
      submitForm
    }
  }
}
</script>

<style scoped>
.post-container {
  max-width: 600px;
  margin: 30px auto;
  padding: 30px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.08);
}
.page-title {
  text-align: center;
  margin-bottom: 24px;
  font-size: 1.6em;
  color: #2c3e50;
}
.editor-wrapper {
  padding: 20px;
}
.form-row {
  margin-bottom: 18px;
  display: flex;
  flex-direction: column;
}
.form-row label {
  font-weight: bold;
  margin-bottom: 6px;
}
.form-row input[type="text"],
.form-row select,
.form-row textarea {
  padding: 8px;
  border: 1px solid #dcdcdc;
  border-radius: 4px;
  font-size: 15px;
}
.form-row textarea {
  resize: vertical;
}
.img-preview {
  margin-top: 8px;
  position: relative;
  display: inline-block;
}
.img-preview img {
  max-width: 120px;
  max-height: 120px;
  border-radius: 4px;
  border: 1px solid #eee;
}
.img-preview button {
  position: absolute;
  top: 2px;
  right: 2px;
  background: #f56c6c;
  color: #fff;
  border: none;
  border-radius: 3px;
  padding: 2px 8px;
  cursor: pointer;
  font-size: 12px;
}
.submit-area {
  text-align: center;
  margin-top: 24px;
}
.submit-area button {
  background: #409eff;
  color: #fff;
  border: none;
  padding: 10px 32px;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}
.submit-area button:disabled {
  background: #b3d8ff;
  cursor: not-allowed;
}
.result-alert {
  margin-top: 20px;
  padding: 12px 18px;
  border-radius: 4px;
  font-size: 15px;
  text-align: center;
}
.result-alert.success {
  background: #e1f3d8;
  color: #3a7a1c;
}
.result-alert.error {
  background: #fde2e2;
  color: #c0392b;
}
</style>