<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="confirmBatch">
            批量确认
          </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="confirm(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 { pageNotices } from '@/api/user/message';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { messageLoading, timeAgo } from 'ele-admin-pro';
  import {
    removeBatchNotice,
    removeNotice,
    updateBatchNotices,
    updateNotice
  } from '@/api/oa/notice';
  import { Notice, NoticeParam } from '@/api/oa/notice/model';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';

  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',
      ellipsis: true
    },
    {
      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 pageNotices({ ...where, ...orders, page, limit });
  };

  /* 确认 */
  const confirm = (row: Notice) => {
    updateNotice({ noticeId: row.noticeId, status: 1 }).then(() => {
      reload();
    });
  };

  /* 删除单个 */
  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 confirmBatch = () => {
    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>
