<template>
  <el-row>
    <el-col :span="24">
      <el-row class="mb-4">
        <el-col :span="12">
          <el-button type="primary" @click="router.push({
            path: '/content/editArticle'
          })">新增</el-button>
          <el-button @click="handleManageCategories">版块设置</el-button>
        </el-col>
        <el-col :span="12" class="text-right">
          <div class="w-80 inline-flex item-center">
            <el-input
              v-model="query.title"
              class="flex-1"
              placeholder="请输入标题"
              @keyup.enter.native="handleSearch"
            />
            <el-button type="primary" class="ml-4" @click="handleSearch"
              >搜索</el-button
            >
          </div>
        </el-col>
      </el-row>
      <el-table :data="list" class="my-2">
        <el-table-column prop="title" label="标题"></el-table-column>
        <el-table-column label="所属版块">
          <template #default="{ row }">
            {{  row.modules ? row.modules.map(v => v.name).join() : row.modules }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间"></el-table-column>
        <el-table-column prop="sort" label="排序(数字越大越排在前)">
          <template #default="{ row }">
            <el-input
              v-model.number="row.sort"
              type="number"
              @blur="updateSort(row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" link @click="router.push({
              path: '/content/editArticle',
              query: {
                id: row.id
              }
            })"
              >编辑</el-button
            >
            <el-button type="danger" link @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="mt-4 justify-end"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="query.pageSize"
        :current-page="query.page"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-col>
    <el-dialog title="版块设置" v-model="category.visible" width="90%">
      <el-form
        v-model="category.form"
        label-position="left"
        class="tag-category-form"
      >
        <el-form-item label="新增版块">
          <div class="flex items-center">
            <el-input
              v-model.trim="category.form.name"
              class="flex-1 mr-4"
              placeholder="版块名称（限制30字符）"
              maxlength="30"
              clearable
            ></el-input>
            <el-button
              type="primary"
              :disabled="!category.form.name"
              @click="handleCreateCategory"
              >确定添加</el-button
            >
          </div>
        </el-form-item>
      </el-form>

      <el-divider></el-divider>
      <!--
      <div class="flex justify-end">
        <div class="w-80 flex items-center">
          <el-input
            v-model.trim="category.query.key"
            class="mr-4"
            placeholder="标签类别名称或编号"
            clearable
            @keyup.enter="handleCategorySearch"
          ></el-input>
          <el-button type="primary" @click="handleCategorySearch"
            >搜索</el-button
          >
        </div>
      </div> -->

      <!-- 第四行：标签类别列表 -->
      <el-table :data="category.list" class="w-100 mt-5">
        <el-table-column prop="sn" label="版块编号"></el-table-column>
        <el-table-column prop="name" label="版块名称">
          <template #default="{ row }">
            <el-input
              v-model="row.name"
              placeholder="请输入版块名称"
              @blur="handleEditCategory(row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="用途备注">
          <template #default="{ row }">
            <el-input
              v-model="row.purpose"
              placeholder="请输入版用途备注"
              @blur="handleEditCategory(row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="danger" @click="handleDeleteCategory(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 第五行：分页 -->
      <el-pagination
        class="justify-end mt-4"
        :current-page="category.query.page"
        :page-size="category.query.pageSize"
        :total="category.total"
        background
        layout="total, prev, pager, next, jumper"
        @current-change="handleCategoryPageChange"
      ></el-pagination>
    </el-dialog>
  </el-row>
</template>

<script setup>
import { ref } from "vue";
import { request } from "@/utils/http";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";

const [route, router] = [useRoute(), useRouter()];
const list = ref([]);
const query = ref({
  title: "",
  page: 1,
  pageSize: 10
});
const total = ref(0);

const category = ref({
  visible: false,
  form: {
    id: 0,
    sn: "",
    name: ""
  },
  query: {
    name: "",
    page: 1,
    pageSize: 10
  },
  list: [],
  total: 0
});

const handleCreateCategory = async () => {
  await request.post(
    "/articleService/module",
    {
      name: category.value.form.name
    }
  );
  ElMessage.success("添加成功");
  category.value.form = {
    id: 0,
    sn: "",
    name: ""
  };
  fetchCategories();
};

const handleCategorySearch = () => {
  category.value.query.page = 1;
  fetchCategories();
};

const handleCategoryPageChange = page => {
  category.value.query.page = page;
  fetchCategories();
};

const handleEditCategory = async row => {
  if (row.name == row.originName && row.purpose == row.originPurpose) return;
  await request.post("/articleService/module/update", {
    id: row.id,
    name: row.name,
    purpose: row.purpose
  });
  ElMessage.success("修改成功");
  fetchCategories();
};

const handleDeleteCategory = async id => {
  ElMessageBox.confirm("确认删除该标签类别吗？", "提示").then(async () => {
    await request.post("/articleService/module/delete", { id });
    ElMessage.success("删除成功");
    fetchCategories();
  });
};

const fetchCategories = async () => {
  const { data } = await request.get("/articleService/module/paginate", {
    params: category.value.query
  });
  category.value.list = data.list.map(item => {
    item.originName = item.name;
    item.originPurpose = item.purpose;
    return item;
  });
  category.value.total = data.total;
};

const handleManageCategories = () => {
  fetchCategories();
  category.value.visible = true;
};

const handleSearch = () => {
  query.value.page = 1;
  fetchArticle();
};

const tagEditRef = ref();
const handleAddTag = () => {
  tagEditRef.value.openDialog({
    id: 0
  });
};

const handleEditTag = row => {
  tagEditRef.value.openDialog({ ...row });
};

const updateSort = async row => {
  await request.post(`/articleService/article/update`, {
    ...row,
    moduleIds: (row.modules || []).map(v => v.id)
  })

  ElMessage.success("操作成功");
  fetchArticle();
};

const handleEditTagSave = () => {
  fetchArticle();
};

const handleSizeChange = size => {
  query.value.pageSize = size;
  fetchArticle();
};

const handleCurrentChange = page => {
  query.value.page = page;
  fetchArticle();
};

const handleDelete = async row => {
  ElMessageBox.confirm("是否确定删除？", "提示").then(async () => {
    await request.post(`/articleService/article/delete`, {
      id: row.id
    });
    ElMessage.success("操作成功");
    fetchArticle();
  });
};

const fetchArticle = async () => {
  const { data } = await request.get("/articleService/article/paginate", {
    params: { ...query.value }
  });
  list.value = data.list.map(v => ({
    ...v,
    originSort: v.sort
  }));
  total.value = data.total;
};

fetchArticle();
</script>

<style scoped>
/* 样式代码 */
</style>
