<template>
  <a-card :bordered="false">
    <!-- 表格 -->
    <ele-pro-table
      ref="tableRef"
      row-key="taskId"
      :columns="columns"
      :datasource="datasource"
      :customRow="customRow"
      tool-class="ele-toolbar-form"
      class="sys-org-table"
    >
      <template #toolbar>
        <search @search="reload" :selection="selection" />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'content'">
          <div class="user-box">
            <div class="user-info">
              <a-badge
                :dot="!record.isRead && record.userId != userStore.info?.userId"
              >
                <a-avatar :src="record.lastAvatar" size="large" />
              </a-badge>
            </div>
            <div class="content" style="display: flex; flex-direction: column">
              <div class="nickname">
                <span class="ele-text-secondary">{{
                  record.lastNickname ? record.lastNickname : '未知'
                }}</span>
                <span class="ele-text-placeholder" style="padding-left: 10px">{{
                  timeAgo(record.updateTime)
                }}</span>
              </div>
              <a
                class="ele-text-heading"
                :href="'/oa/task/detail/' + record.taskId"
                >{{ record.content }}</a
              >
            </div>
            <div class="last-time ele-text-info"> </div>
          </div>
        </template>
        <template v-else-if="column.key === 'status'">
          <a
            v-if="record.commander === userStore.info?.userId"
            @click="openUrl('/oa/task/detail/' + record.taskId)"
            >立即处理</a
          >
          <a v-else @click="getTask(record)">领取任务</a>
        </template>
        <template v-else-if="column.key === 'progress'">
          <a-progress :percent="record.progress * 2" :steps="5" />
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="onDetail(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>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { message } from 'ant-design-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import type { DatasourceFunction } from 'ele-admin-pro/es/ele-pro-table/types';
  import { timeAgo, toDateString } from 'ele-admin-pro';
  import Search from './search.vue';
  import { pageTask, removeTask, updateTask } from '@/api/oa/task';
  import type { Task, TaskParam } from '@/api/oa/task/model';
  import { useUserStore } from '@/store/modules/user';
  import { openUrl } from '@/utils/common';
  import { hasRole } from '@/utils/permission';

  const userStore = useUserStore();
  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);
  const selection = ref<any[]>();
  const status = ref<number>();

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    // 搜索条件
    where.userId = undefined;
    where.progress = 0;
    return pageTask({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 表格列配置
  const columns = ref<any[]>([
    {
      title: '工单号',
      dataIndex: 'taskId',
      align: 'center',
      width: 120
    },
    {
      title: '工单类型',
      dataIndex: 'taskType',
      width: 120
    },
    {
      title: '工单标题',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true
    },
    {
      title: '操作',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 120
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: 150,
      customRender: ({ text }) => toDateString(text, 'MM月dd日 HH:mm')
    }
  ]);

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

  const onDetail = (record?: Task) => {
    window.location.href = 'detail?id=' + record?.taskId;
  };

  const getTask = (item: Task) => {
    item.commander = userStore.info?.userId;
    updateTask(item).then(() => {
      message.success('领取成功');
      reload();
    });
  };

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

  // 是否展现多选按钮及批量删除按钮
  if (hasRole('superAdmin') || hasRole('admin')) {
    selection.value = [];
  }

  /* 自定义行属性 */
  const customRow = (record: Task) => {
    return {
      // 行双击事件
      onDblclick: () => {
        window.open('/oa/task/detail/' + record.taskId);
      }
    };
  };
  //
</script>

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

<style lang="less" scoped>
  .user-box {
    display: flex;
    align-items: center;
    .user-info {
      display: flex;
      flex-direction: column;
      align-items: start;
      margin-right: 7px;
    }
    .last-time {
      margin-left: 12px;
    }
    .content {
      .text {
        max-width: 90%;
      }
    }
  }
</style>
