<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
            class="input-field"
          />
        </div>

        <!-- 分类选择 -->
        <div class="form-row">
          <label>分类</label>
          <select v-model="form.categoryId" required class="input-field">
            <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>
          <div class="upload-wrapper">
            <!-- 隐藏的文件选择input -->
            <input 
              type="file" 
              accept="image/*" 
              @change="onFileChange" 
              id="image-upload"
              class="hidden-input"
            />
            <!-- 自定义+号按钮 -->
            <label for="image-upload" class="upload-btn">
              <span class="plus-icon">+</span>
            </label>
            <!-- 图片预览 -->
            <div v-if="form.imagePreview" class="img-preview">
              <img :src="form.imagePreview" alt="预览" class="preview-img" />
              <button type="button" @click="removeImage" class="remove-btn">×</button>
            </div>
          </div>
        </div>

        <!-- 匿名发布选项 -->
        <div class="form-row anonymous-option">
          <label class="anonymous-label">
            <input type="checkbox" v-model="form.status" true-value="1" false-value="0" class="anonymous-checkbox" />
            匿名发布
          </label>
        </div>

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

        <!-- 提交按钮 -->
        <div class="submit-area">
          <button type="submit" :disabled="submitting" class="submit-btn">
            {{ 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: '娱乐' },
      { id: 4, 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.image) {
        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', '帖子发布成功')
          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>
.upload-wrapper {
  display: flex;
  align-items: center;
  gap: 15px;
}

.hidden-input {
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}

.upload-btn {
  width: 80px;
  height: 80px;
  border: 2px dashed #ff88aa;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.upload-btn:hover {
  background-color: #fff5f8;
  border-color: #ff6699;
}

.plus-icon {
  font-size: 32px;
  color: #ff88aa;
  font-weight: lighter;
}

.img-preview {
  position: relative;
  display: inline-block;
}

.preview-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid #eee;
}

.remove-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 20px;
  height: 20px;
  background: #ff6699;
  color: white;
  border: none;
  border-radius: 50%;
  padding: 0;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.post-container {
  max-width: 600px;
  margin: 30px auto;
  padding: 30px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.page-title {
  text-align: center;
  margin-bottom: 24px;
  font-size: 1.8em;
  color: #2c3e50;
  border-bottom: 2px solid #ff88aa;
  padding-bottom: 10px;
}

.form-row {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
}

.form-row label {
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.input-field,
.textarea-field {
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 15px;
  transition: border-color 0.3s;
}

.input-field:focus,
.textarea-field:focus {
  outline: none;
  border-color: #ff88aa;
}

.anonymous-option {
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 15px;
}

.anonymous-label {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
}

.anonymous-checkbox {
  width: 18px;
  height: 18px;
  accent-color: #ff88aa;
}

.textarea-field {
  resize: vertical;
  min-height: 150px;
}

.submit-area {
  text-align: center;
  margin-top: 30px;
}

.submit-btn {
  background: #ff88aa;
  color: white;
  border: none;
  padding: 12px 40px;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s;
}

.submit-btn:disabled {
  background: #ffcccc;
  cursor: not-allowed;
}

.submit-btn:hover {
  background: #ff6699;
}

.result-alert {
  margin-top: 20px;
  padding: 15px 20px;
  border-radius: 8px;
  font-size: 15px;
  text-align: center;
}

.result-alert.success {
  background: #e1f3d8;
  color: #3a7a1c;
}

.result-alert.error {
  background: #fde2e2;
  color: #c0392b;
}
</style>