<template>
  <div class="app-task">
    <!-- 表格 -->
    <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>
        <AppTaskSearch :data="data" @search="reload" @remove="removeBatch" />
      </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.avatar" size="large" />
              </a-badge>
            </div>
            <div class="content" style="display: flex; flex-direction: column">
              <div class="nickname">
                <a-typography-text strong>
                  {{ `${record.nickname}` }}
                </a-typography-text>
                <span class="ele-text-placeholder" style="padding-left: 10px">{{
                  timeAgo(record.createTime)
                }}</span>
              </div>
              <a
                class="ele-text-heading"
                @click="openNew('/oa/task/detail/' + record.taskId)"
              >
                {{ `工单标题：${record.name}` }}
              </a>
              <div class="ele-text-placeholder">{{
                record.appId > 0 ? `项目名称：【${record.appName}】` : ''
              }}</div>
              <div
                class="ele-text-secondary"
                style="display: flex; align-items: center"
              >
                <a-avatar :size="18" :src="record.lastAvatar" />
                <div class="content" style="padding-left: 8px">
                  {{ record.content }}
                </div>
                <span class="ele-text-placeholder" style="padding-left: 10px">{{
                  timeAgo(record.updateTime)
                }}</span>
              </div>
            </div>
            <div class="last-time ele-text-info"> </div>
          </div>
        </template>
        <template v-else-if="column.key === 'status'">
          <a-tag v-if="record.progress === TOBEARRANGED" color="red"
            >待安排</a-tag
          >
          <a-tag v-if="record.progress === PENDING" color="orange"
            >待处理</a-tag
          >
          <a-tag v-if="record.progress === PROCESSING" color="purple"
            >处理中</a-tag
          >
          <a-tag v-if="record.progress === TOBECONFIRMED" color="cyan"
            >待评价</a-tag
          >
          <a-tag v-if="record.progress === COMPLETED" color="green"
            >已完成</a-tag
          >
          <a-tag v-if="record.progress === CLOSED">已关闭</a-tag>
          <div class="ele-text-danger" v-if="record.overdueDays">
            已逾期{{ record.overdueDays }}天
          </div>
        </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>
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref, watch } 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 } from 'ele-admin-pro/es/ele-pro-table/types';
  import { timeAgo } from 'ele-admin-pro';
  import { pageTask, removeTask, removeBatchTask } from '@/api/oa/task';
  import type { Task, TaskParam } from '@/api/oa/task/model';
  import { useUserStore } from '@/store/modules/user';
  import AppTaskSearch from './app-task-search.vue';
  import {
    CLOSED,
    COMPLETED,
    PENDING,
    PROCESSING,
    TOBEARRANGED,
    TOBECONFIRMED
  } from '@/api/oa/task/model/progress';
  import { hasRole } from '@/utils/permission';
  import { openNew } from '@/utils/common';
  import { App } from '@/api/oa/app/model';

  const props = defineProps<{
    appId: number | undefined;
    data: App;
  }>();

  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 }) => {
    // 搜索条件
    // 工单发起人
    if (hasRole('promoter') || hasRole('user')) {
      where.commander = undefined;
      where.userId = userStore.info?.userId;
    }
    // 管理人员
    if (hasRole('superAdmin') || hasRole('admin')) {
      where.commander = undefined;
    }
    // 工单受理人员
    if (hasRole('commander')) {
      where.commander = userStore.info?.userId;
    }
    where.appId = props.appId;
    return pageTask({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 表格列配置
  const columns = ref<any[]>([
    {
      title: '工单号',
      dataIndex: 'taskId',
      align: 'center',
      width: 100
    },
    {
      title: '工单类型',
      dataIndex: 'taskType',
      width: 100
    },
    {
      title: '工单信息',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 120
    }
  ]);

  /* 搜索 */
  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 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);
      });
  };

  /* 批量删除 */
  const removeBatch = () => {
    if (!selection.value?.length) {
      message.error('请至少选择一条数据');
      return;
    }
    if (selection.value?.length) {
      Modal.confirm({
        title: '提示',
        content: '确定要删除选中的记录吗?',
        icon: createVNode(ExclamationCircleOutlined),
        maskClosable: true,
        onOk: () => {
          const hide = message.loading('请求中..', 0);
          removeBatchTask(selection.value.map((d) => d.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);
      }
    };
  };

  watch(
    () => props.appId,
    (appId) => {
      if (appId) {
        reload({ appId });
      }
    },
    { immediate: true }
  );
</script>

<script lang="ts">
  export default {
    name: 'AppTaskIndex'
  };
</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%;
      }
    }
  }
  .nickname {
    .ele-text-heading {
      font-weight: bold;
    }
  }
</style>
