<template>
  <div class="forum-container">
    <!-- 顶部搜索和发帖区域 -->
    <div class="top-area">
      <el-input
        placeholder="搜索帖子..."
        v-model="searchText"
        class="search-input"
        prefix-icon="el-icon-search"
        @input="handleSearch"
      >
      </el-input>
      <el-button type="primary" @click="handleCreatePost">发布新帖</el-button>
    </div>

    <!-- 分类标签页 -->
    <el-tabs v-model="activeCategory" @tab-click="handleCategoryChange">
      <el-tab-pane
        v-for="category in categories"
        :key="category.id"
        :label="category.name"
        :name="category.id.toString()"
      >
      </el-tab-pane>
    </el-tabs>

    <!-- 帖子列表 -->
    <div class="post-list">
      <el-card v-for="post in posts" :key="post.id" class="post-card">
        <div class="post-header">
          <div class="post-info">
            <h3 class="post-title" @click="viewPost(post.id)">
              {{ post.title }}
            </h3>
            <div class="post-meta">
              <span class="author">
                <i class="el-icon-user"></i>
                {{ post.userName }}
              </span>
              <span class="time">
                <i class="el-icon-time"></i>
                {{ post.createTime | formatDate }}
              </span>
              <el-tag size="small" type="info">{{ post.categoryName }}</el-tag>
            </div>
          </div>
          <div class="post-stats">
            <span class="stat-item">
              <i class="el-icon-view"></i>
              {{ post.viewCount }}
            </span>
            <span class="stat-item">
              <i class="el-icon-thumb"></i>
              {{ post.likeCount }}
            </span>
            <span class="stat-item">
              <i class="el-icon-chat-dot-round"></i>
              {{ post.replyCount }}
            </span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分页器 -->
    <div class="pagination-area">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 发帖对话框 -->
    <el-dialog title="发布新帖" :visible.sync="dialogVisible" width="50%">
      <el-form
        :model="newPost"
        :rules="rules"
        ref="postForm"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="newPost.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="newPost.categoryId" placeholder="请选择分类">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            v-model="newPost.content"
            :rows="6"
            placeholder="请输入帖子内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPost">发 布</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCategories, getPosts, createPost } from "@/api/forum";
import { debounce } from "lodash";
export default {
  name: "Forum",
  data() {
    return {
      searchText: "",
      activeCategory: "all",
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      categories: [],
      posts: [],
      newPost: {
        title: "",
        categoryId: "",
        content: "",
        userId: this.$store.state.user.userId
          ? this.$store.state.user.userId
          : window.localStorage.getItem("userId"),
      },
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          {
            min: 3,
            max: 50,
            message: "长度在 3 到 50 个字符",
            trigger: "blur",
          },
        ],
        categoryId: [
          { required: true, message: "请选择分类", trigger: "change" },
        ],
        content: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { min: 10, message: "内容不能少于10个字符", trigger: "blur" },
        ],
      },
    };
  },
  mounted() {
    // 初始化 Quill 编辑器
    this.quill = new Quill(this.$refs.editorContainer, {
      theme: "snow", // 使用 snow 主题
      placeholder: "请输入帖子内容", // 设置占位符
      modules: {
        toolbar: [
          [{ header: "1" }, { header: "2" }, { font: [] }],
          [{ list: "ordered" }, { list: "bullet" }],
          ["bold", "italic", "underline"],
          ["link"],
          [{ align: [] }],
          ["clean"],
        ],
      },
    });
  },
  created() {
    this.fetchCategories();
    this.fetchPosts();
  },
  methods: {
    // 获取分类列表
    async fetchCategories() {
      try {
        const res = await getCategories();
        if (res.status === 200) {
          this.categories = [{ id: "", name: "全部" }, ...res.data];
        } else {
          this.$message.error(res.message || "获取分类失败");
        }
      } catch (error) {
        this.$message.error("获取分类失败");
      }
    },

    // 获取帖子列表
    async fetchPosts() {
      try {
        const params = {
          page: this.currentPage,
          size: this.pageSize,
          categoryId:
            this.activeCategory !== "all" ? this.activeCategory : null,
          searchText: this.searchText || null,
        };

        const res = await getPosts(params);
        if (res.status === 200) {
          this.posts = res.data.records;
          this.total = res.data.total;
        } else {
          this.$message.error(res.message || "获取帖子列表失败");
        }
      } catch (error) {
        this.$message.error("获取帖子列表失败");
      }
    },

    // 处理分类切换
    handleCategoryChange(tab) {
      this.currentPage = 1;
      this.fetchPosts();
    },

    // 处理搜索
    handleSearch: _.debounce(function () {
      this.currentPage = 1;
      this.fetchPosts();
    }, 300),

    // 处理分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchPosts();
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchPosts();
    },

    // 查看帖子详情
    viewPost(id) {
      this.$router.push(`/post/${id}`);
    },

    // 创建帖子
    handleCreatePost() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.postForm.resetFields();
      });
    },

    // 提交帖子
    async submitPost() {
      this.$refs.postForm.validate(async (valid) => {
        if (valid) {
          try {
            // 调用 createPost 函数，传入表单数据
            const res = await createPost(this.newPost);

            if (res.status === 200) {
              this.$message.success("发布成功");
              this.dialogVisible = false;
              this.fetchPosts();
            } else {
              this.$message.error(res.message || "发布失败");
            }
          } catch (error) {
            this.$message.error("发布失败");
          }
        }
      });
    },
  },
};
</script>

<style scoped>
.forum-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.top-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
  margin-right: 20px;
}

.post-list {
  margin-top: 20px;
}

.post-card {
  margin-bottom: 15px;
  cursor: pointer;
  transition: all 0.3s;
}

.post-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.post-info {
  flex: 1;
}

.post-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #303133;
}

.post-title:hover {
  color: #409eff;
}

.post-meta {
  font-size: 13px;
  color: #909399;
  margin-bottom: 8px;
}

.post-meta > span {
  margin-right: 15px;
}

.post-meta i {
  margin-right: 4px;
}

.post-tags {
  margin-top: 8px;
}

.tag {
  margin-right: 8px;
}

.post-stats {
  display: flex;
  align-items: center;
}

.stat-item {
  margin-left: 20px;
  font-size: 13px;
  color: #909399;
}

.stat-item i {
  margin-right: 4px;
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
