<template>
  <div>
    <ele-pro-table
      ref="tableRef"
      row-key="noticeId"
      :columns="columns"
      :datasource="datasource"
      v-model:selection="selection"
      :scroll="{ x: 600 }"
    >
      <template #toolbar>
        <a-space>
          <a-button type="primary" class="ele-btn-icon" @click="read">
            标记已读
          </a-button>
          <a-button
            danger
            type="primary"
            class="ele-btn-icon"
            @click="removeBatch"
          >
            删除消息
          </a-button>
        </a-space>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'status'">
          <span :class="['ele-text-warning', 'ele-text-info'][record.status]">
            {{ ['未读', '已读'][record.status] }}
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <a-space>
            <!--            <a @click="reply(record)">回复</a>-->
            <!--            <a-divider type="vertical" />-->
            <a-popconfirm
              placement="topRight"
              title="确定要删除此消息吗？"
              @confirm="remove(record)"
            >
              <a class="ele-text-danger">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </ele-pro-table>
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue/es';
  import type { EleProTable } from 'ele-admin-pro/es';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import {
    removeBatchNotice,
    removeNotice,
    updateBatchNotices,
    updateNotice
  } from '@/api/oa/notice';
  import { Notice, NoticeParam } from '@/api/oa/notice/model';
  import { pageLetters } from '@/api/user/message';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { messageLoading, timeAgo } from 'ele-admin-pro';

  const emit = defineEmits<{
    (e: 'update-data'): void;
  }>();

  // 表格实例
  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: '私信内容',
      dataIndex: 'title'
    },
    {
      title: '发送时间',
      dataIndex: 'createTime',
      ellipsis: true,
      width: 140,
      align: 'center',
      customRender: ({ text }) => timeAgo(text)
    },
    {
      title: '状态',
      key: 'status',
      width: 90,
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      align: 'center',
      hideInSetting: true
    }
  ]);

  // 列表选中数据
  const selection = ref<Notice[]>([]);
  // 要修改的数据
  const update = ref<Notice[]>([]);

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

  /* 回复 */
  const reply = (row: Notice) => {
    console.log(row);
    // message.info('点击了回复');
  };

  /* 删除单个 */
  const remove = (row: Notice) => {
    const hide = messageLoading('请求中..', 0);
    removeNotice(row.noticeId)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
        updateUnReadNum();
      })
      .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 = messageLoading('请求中..', 0);
        removeBatchNotice(selection.value.map((d) => d.noticeId))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
            updateUnReadNum();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  /* 标记已读 */
  const read = () => {
    if (!selection.value.length) {
      message.error('请至少选择一条数据');
      return;
    }
    selection.value.forEach((d) => {
      update.value.push({
        noticeId: d.noticeId,
        status: 1
      });
    });
    updateBatchNotices(update.value).then(() => {
      reload();
    });
    updateUnReadNum();
  };

  /* 触发更新未读数量事件 */
  const updateUnReadNum = () => {
    emit('update-data');
  };

  /* 搜索 */
  const reload = (where?: NoticeParam) => {
    selection.value = [];
    tableRef?.value?.reload({ page: 1, where });
  };
</script>
