<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="articleId"
          :columns="columns"
          :height="tableHeight"
          :customRow="customRow"
          :datasource="datasource"
          :parse-data="parseData"
          v-model:selection="selection"
          :scroll="{ x: 800 }"
        >
          <template #toolbar>
            <search
              :selection="selection"
              @search="reload"
              @add="openEdit"
              @remove="removeBatch"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'nickname'">
              <div class="user-box">
                <a-avatar
                  :size="30"
                  :src="`${record.userAvatar}`"
                  style="margin-right: 4px"
                >
                  <template #icon>
                    <UserOutlined />
                  </template>
                </a-avatar>
                <div class="user-info">
                  <span>{{ record.nickname }}</span>
                  <span class="ele-text-placeholder">
                    {{ timeAgo(record.createTime) }}
                  </span>
                </div>
              </div>
            </template>
            <template v-if="column.key === 'files'">
              <div
                class="video"
                v-if="record.video"
                style="
                  background-color: #000000;
                  display: flex;
                  width: 160px;
                  height: 100px;
                  justify-content: center;
                "
              >
                <video :src="record.video" :width="150" :height="100"></video>
              </div>
              <ele-image-upload
                v-model:value="record.thumbnail"
                :limit="9"
                v-else
                disabled="true"
                :preview="false"
                :item-style="{ width: '60px', height: '60px' }"
              />
            </template>
            <template v-if="column.key === 'content'">
              {{ record.content }}
            </template>
            <template v-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>
      </a-card>
      <!-- 编辑弹窗 -->
      <ArticleEdit v-model:visible="showEdit" :data="current" @done="reload" />
    </div>
  </div>
</template>

<!--suppress TypeScriptValidateTypes -->
<script lang="ts" setup>
  import { timeAgo, toTreeData } from 'ele-admin-pro';
  import { createVNode, computed, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import Search from './components/search.vue';
  import ArticleEdit from './components/article-edit.vue';
  import {
    pageArticle,
    removeArticle,
    removeBatchArticle
  } from '@/api/cms/article';
  import type { Article, ArticleParam } from '@/api/cms/article/model';
  import { FILE_SERVER } from '@/config/setting';

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

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    // {
    //   key: 'index',
    //   width: 48,
    //   align: 'center',
    //   fixed: 'left',
    //   hideInSetting: true,
    //   customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    // },
    {
      title: 'ID',
      dataIndex: 'articleId',
      width: 60,
      key: 'articleId'
    },
    {
      title: '会员信息',
      dataIndex: 'nickname',
      width: 240,
      key: 'nickname'
    },
    {
      title: '图片/视频',
      dataIndex: 'files',
      key: 'files'
    },
    {
      title: '这一刻想法',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true
    },
    {
      title: '排序',
      dataIndex: 'sortNumber',
      width: 100,
      sorter: true
    },
    {
      title: '获赞数',
      dataIndex: 'likes',
      width: 100,
      sorter: true
    },
    {
      title: '评论数',
      dataIndex: 'commentNumbers',
      width: 100,
      sorter: true
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      align: 'center',
      hideInSetting: true
    }
  ]);

  // 表格选中数据
  const selection = ref<Article[]>([]);
  // 当前编辑数据
  const current = ref<Article | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    if (filters) {
      where.brand = filters.brand;
    }
    return pageArticle({ ...where, ...orders, page, limit });
  };

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

  // 搜索是否展开
  const searchExpand = ref(false);

  // 表格固定高度
  const fixedHeight = ref(false);

  // 表格高度
  const tableHeight = computed(() => {
    return fixedHeight.value
      ? searchExpand.value
        ? 'calc(100vh - 618px)'
        : 'calc(100vh - 562px)'
      : void 0;
  });

  /* 打开编辑弹窗 */
  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 parseData = (data: any) => {
    return {
      count: data.count,
      list: data.list.map((d) => {
        // 处理图片附件
        if (d.files) {
          d.files = JSON.parse(d.files);
          d.thumbnail = [];
          if (d.files.length > 0) {
            d.files.map((pic, index) => {
              d.thumbnail.push({
                url: pic.url
              });
              // if (pic.url.indexOf('/thumbnail') == -1) {
              //   d.thumbnail.push({
              //     url: pic.url.replace(FILE_SERVER, FILE_SERVER + '/thumbnail')
              //   });
              //   console.log(d);
              // }
            });
          }
        }
        return d;
      })
    };
  };

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

<script lang="ts">
  export default {
    name: 'LoveQIndex'
  };
</script>

<style lang="less" scoped>
  // 文字超出隐藏(两行)
  // 需要设置文字容器的宽度
  .twoline-hide {
    width: 320px;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    white-space: normal;
  }
  .user-box {
    display: flex;
    align-items: center;
    .user-info {
      display: flex;
      flex-direction: column;
      align-items: start;
    }
  }
</style>
