<template>
  <!-- 表格 -->
  <ele-pro-table
    ref="tableRef"
    row-key="articleId"
    :columns="columns"
    :datasource="datasource"
    v-model:selection="selection"
    :customRow="customRow"
    height="calc(100vh - 290px)"
    tool-class="ele-toolbar-form"
    :scroll="{ x: 800 }"
    tools-theme="default"
    bordered
    class="sys-category-table"
  >
    <template #toolbar>
      <article-search
        :selection="selection"
        @search="reload"
        @add="openEdit()"
        @remove="removeBatch"
      />
    </template>
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'title'">
        <a-tooltip :title="`文章预览 ${record.articleId}`">
          <a href="#" @click="openInfo(record)">{{ record.title }}</a>
        </a-tooltip>
      </template>
      <template v-if="column.key === 'image'">
        <a-image
          :width="45"
          v-if="record.image"
          :src="FILE_THUMBNAIL + record.image"
          :preview="false"
        />
      </template>
      <template v-if="column.key === 'status'">
        <a-tag
          v-if="record.status === 0"
          color="green"
          @click="(checked: boolean) => editStatus(record.status, record)"
          >显示</a-tag
        >
        <a-tag
          v-if="record.status === 1"
          color="red"
          @click="(checked: boolean) => editStatus(record.status, record)"
          >隐藏</a-tag
        >
      </template>
      <template v-if="column.key === 'comments'">
        <a-tooltip :title="record.comments" placement="topLeft">
          {{ record.comments }}
        </a-tooltip>
      </template>
      <template v-if="column.key === 'nickname'">
        <a-tooltip
          :title="`${record.nickname} ${toDateString(record.createTime)}`"
        >
          <a-avatar :src="record.userAvatar" size="small" />
          {{ timeAgo(record.createTime) }}
        </a-tooltip>
      </template>
      <template v-if="column.key === 'createTime'">
        <a-tooltip :title="`${toDateString(record.createTime)}`">
          <span>{{ timeAgo(record.createTime) }}</span>
        </a-tooltip>
      </template>
      <template v-else-if="column.key === 'action'">
        <a-space>
          <a @click="openEdit(record)">修改</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定要删除此文章吗？" @confirm="remove(record)">
            <a class="ele-text-danger">删除</a>
          </a-popconfirm>
        </a-space>
      </template>
    </template>
  </ele-pro-table>
  <!-- 编辑弹窗 -->
  <article-edit
    :data="current"
    v-model:visible="showEdit"
    :category-list="categoryList"
    :category-id="categoryId"
    @done="reload"
  />
  <!-- 文章预览 -->
  <article-info v-model:visible="showInfo" :data="current" @done="reload" />
</template>

<script lang="ts" setup>
  import { createVNode, ref, watch } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { toDateString } from 'ele-admin-pro';
  import ArticleSearch from './components/article-search.vue';
  import ArticleEdit from './components/article-edit.vue';
  import ArticleInfo from './components/article-info.vue';
  import { timeAgo } from 'ele-admin-pro';
  import {
    pageArticle,
    removeArticle,
    removeBatchArticle,
    updateArticleStatus
  } from '@/api/cms/article';
  import type { Article, ArticleParam } from '@/api/cms/article/model';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { FILE_THUMBNAIL } from '@/config/setting';
  // import router from '@/router';
  import { ArticleCategory } from '@/api/cms/category/model';

  const props = defineProps<{
    // 文章 id
    categoryId?: number;
    // 全部分类
    categoryList: ArticleCategory[];
  }>();

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  // 表格选中数据
  const selection = ref<Article[]>([]);
  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      title: '文章标题',
      dataIndex: 'title',
      width: 280,
      key: 'title'
    },
    {
      title: '封面图',
      dataIndex: 'image',
      key: 'image',
      align: 'center'
    },
    {
      title: '点击',
      dataIndex: 'actualViews',
      sorter: true
    },
    // {
    //   title: '备注',
    //   dataIndex: 'comments',
    //   key: 'comments',
    //   ellipsis: true
    // },
    {
      title: '排序',
      dataIndex: 'sortNumber',
      sorter: true
    },
    {
      title: '状态',
      key: 'status',
      filters: [
        {
          text: '显示',
          value: 0
        },
        {
          text: '隐藏',
          value: 1
        }
      ],
      filterMultiple: false,
      align: 'center'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: true,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text)
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      align: 'center',
      hideInSetting: true
    }
  ]);

  // 当前编辑数据
  const current = ref<Article | null>(null);
  // 是否显示文章详情
  const showInfo = ref(false);
  // 是否显示编辑弹窗
  const showEdit = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    if (props.categoryId) {
      where.categoryId = props.categoryId;
    }
    // 按条件排序
    if (filters) {
      where.virtualViews = filters.virtualViews;
      where.actualViews = filters.actualViews;
      where.sortNumber = filters.sortNumber;
      where.status = filters.status;
    }
    return pageArticle({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  /* 搜索 */
  const reload = (where?: ArticleParam) => {
    selection.value = [];
    tableRef?.value?.reload({ where: where });
  };

  /* 打开用户详情弹窗 */
  const openInfo = (row?: Article) => {
    console.log(row);
    current.value = row ?? null;
    showInfo.value = true;
    // 跳转文章详情页
    // router.push({
    //   path: '/content/detail',
    //   query: { articleId: row?.articleId }
    // });
  };

  /* 打开编辑弹窗 */
  const openEdit = (row?: Article) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /* 删除单个 */
  const remove = (row: Article) => {
    const hide = message.loading('请求中..', 0);
    removeArticle(row.articleId)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 批量删除 */
  const removeBatch = () => {
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的记录吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = message.loading('请求中..', 0);
        removeBatchArticle(selection.value.map((d) => d.articleId))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  /* 修改文章状态 */
  const editStatus = (checked: boolean, row: Article) => {
    const status = checked ? 0 : 1;
    updateArticleStatus(row.articleId, status)
      .then((msg) => {
        row.status = status;
        message.success(msg);
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  /* 自定义行属性 */
  const customRow = (record: Article) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openEdit(record);
      }
    };
  };

  // 监听文章 id 变化
  watch(
    () => props.categoryId,
    () => {
      reload();
    }
  );
</script>

<style lang="less" scoped>
  .sys-category-table :deep(.ant-table-body) {
    overflow: auto !important;
    overflow: overlay !important;
  }

  .sys-category-table :deep(.ant-table-pagination.ant-pagination) {
    padding: 0 4px;
    margin-bottom: 0;
  }
</style>
