<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import type { Article, ArticleSearchFilter } from '@/model/article'
import RegularPage from '@/components/RegularPage.vue'
import {
  searchArticlesRequest,
  deleteArticlesRequest,
  publishArticlesByIdRequest,
  closeArticlesByIdRequest
} from '@/api/article'
import { searchCategoryListRequest } from '@/api/category'
import type { Category } from '@/model/category'
import type { BaseTableColumns } from 'tdesign-vue-next'
import { useSearchable } from '@/composables/useSearchable'
import ArticleDialog from '@/pages/article/components/ArticleDialog.vue'
import { MessagePlugin } from 'tdesign-vue-next'
const { data, loading, pagination, onPageChange, fetchData } = useSearchable<
  ArticleSearchFilter,
  Article
>(searchArticlesRequest)
const statusArticleListMap = {
  draft: { label: '草稿', theme: 'default' },
  published: { label: '已发布', theme: 'success' },
  closed: { label: '已关闭', theme: 'danger' }
}
const columns: BaseTableColumns = [
  {
    title: '咨询标题',
    colKey: 'title',
    width: 100
  },
  {
    title: '分类',
    colKey: 'categoryName',
    width: 100
  },
  {
    title: '状态',
    colKey: 'status',
    width: 100
  },
  {
    title: '创建时间',
    colKey: 'createdTime',
    width: 100
  },
  {
    title: '操作',
    colKey: 'operation',
    width: 100
  }
]
const articleDialogVisble = ref(false)
const isEdit = ref(false)
const currentTableData = ref<Article | {}>({})
const categoryList = ref<Category[]>([])
onMounted(fetchData)
watch(articleDialogVisble, (newValue) => {
  if (newValue) {
    searchCategoryList()
  }
})
const searchCategoryList = async () => {
  try {
    const res = await searchCategoryListRequest()
    categoryList.value = res
  } catch (error) {
    categoryList.value = []
  }
}
const editClick = (article: Article) => {
  isEdit.value = true
  currentTableData.value = article
  articleDialogVisble.value = true
}
const handleArticleDialogSuccess = () => {
  fetchData()
  articleDialogVisble.value = false
}
const handleArticleDialogClosed = () => {
  isEdit.value = false
  currentTableData.value = {}
}
const toggleArticleStatus = async (article: Article) => {
  if (article.status === 'published') {
    await closeArticlesByIdRequest(article.id)
  } else {
    await publishArticlesByIdRequest(article.id)
  }
  fetchData()
  MessagePlugin.success(`${article.status === 'published' ? '关闭' : '发布'}咨询成功`)
}
const deleteCategoryClick = async (article: Article) => {
  await deleteArticlesRequest(article.id)
  fetchData()
  MessagePlugin.success('删除咨询成功')
}
</script>

<template>
  <RegularPage title="咨询管理">
    <template #right-area>
      <TButton @click="articleDialogVisble = true">创建咨询</TButton>
    </template>
    <TTable
      class="w-full h-full"
      row-key="id"
      height="92%"
      table-layout="auto"
      :data="data"
      :loading="loading"
      :columns="columns"
      cell-empty-content="-"
      :paginationAffixedBottom="true"
      :pagination="{
        total: pagination.total,
        current: pagination.page,
        pageSize: pagination.size,
        onChange: onPageChange
      }"
    >
      <template #categoryName="{ row }">
        {{ row.category.name }}
      </template>
      <template #status="{ row }">
        <t-tag :theme="statusArticleListMap[row.status as keyof typeof statusArticleListMap].theme">
          {{ statusArticleListMap[row.status as keyof typeof statusArticleListMap].label }}
        </t-tag>
      </template>
      <template #operation="{ row }">
        <TSpace :size="1">
          <TButton variant="text" size="small" theme="primary" @click="editClick(row)"
            >编辑</TButton
          >
          <TButton variant="text" size="small" theme="warning" @click="toggleArticleStatus(row)">{{
            row.status === 'published' ? '关闭' : '发布'
          }}</TButton>
          <t-popconfirm
            theme="default"
            content="确认删除此项分类吗"
            @confirm="deleteCategoryClick(row)"
          >
            <TButton variant="text" size="small" theme="danger">删除</TButton>
          </t-popconfirm>
        </TSpace>
      </template>
    </TTable>
    <ArticleDialog
      headerTitle="咨询"
      :isEdit="isEdit"
      :article="currentTableData"
      :categoryList="categoryList"
      v-model:visible="articleDialogVisble"
      @closed="handleArticleDialogClosed"
      @success="handleArticleDialogSuccess"
    ></ArticleDialog>
  </RegularPage>
</template>

<style scoped>
:deep(.t-card__body) {
  flex: 1;
  min-height: 0;
}
</style>
