<template>
  <div class="ele-body">
    <!-- 表格 -->
    <ele-pro-table
      ref="tableRef"
      row-key="taskId"
      :columns="columns"
      :datasource="datasource"
      v-model:selection="selection"
      :customRow="customRow"
      :scroll="{ x: 1200 }"
      tool-class="ele-toolbar-form"
      class="sys-org-table"
    >
      <template #toolbar>
        <search
          @search="reload"
          :selection="selection"
          @add="openEdit"
          @remove="removeBatch"
        />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'name'">
          <a-tooltip title="查看详情">
            <span href="#">{{ record.name }}</span>
          </a-tooltip>
          <!--          <div class="ele-text-placeholder">{{ record.comments }}</div>-->
        </template>
        <template v-if="column.key === 'progress'">
          <template v-for="(item, index) in taskProgress" :key="index">
            <a-badge
              :dot="
                record.isRead === 0 && loginUser.userId !== record.lastReadUser
              "
              v-if="Number(item.value) === Number(record.progress)"
            >
              <a-tag v-if="record.status === 0" color="orange">
                {{ item.label }}
              </a-tag>
              <a-tag v-if="record.status === 1" color="green">
                {{ item.label }}
              </a-tag>
            </a-badge>
          </template>
        </template>
        <template v-if="column.key === 'taskType'">
          <div v-for="(d, i) in JSON.parse(taskType)" :key="i">
            <span v-if="d.value === record.taskType">{{ d.value }}</span>
          </div>
        </template>
        <template v-if="column.key === 'status'">
          <a-tag v-if="record.progress === 0" color="red">待处理</a-tag>
          <a-tag v-if="record.progress === 1" color="green">已完成</a-tag>
          <a-tag v-if="record.progress === 2" color="purple">已回复</a-tag>
        </template>
        <template v-if="column.key === 'promoter'">
          <div class="user-box">
            <a-tooltip :title="`ID:${record.promoter}`">
              <a-avatar
                :size="30"
                :src="`${record.promoterAvatar}`"
                style="margin-right: 4px"
              >
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
            </a-tooltip>
            <div class="user-info" @click="onPromoter(record)">
              <span>{{ record.promoterAlias }}</span>
              <span class="ele-text-placeholder">
                {{ record.promoterName }}
              </span>
            </div>
          </div>
        </template>
        <template v-if="column.key === 'commander'">
          <div class="user-box" v-if="record.commander">
            <a-tooltip :title="`ID:${record.commander}`">
              <a-avatar
                :size="30"
                :src="`${record.commanderAvatar}`"
                style="margin-right: 4px"
              >
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
            </a-tooltip>
            <div class="user-info" @click="onCommander(record)">
              <span>{{ record.commanderAlias }}</span>
              <span class="ele-text-placeholder">
                {{ record.commanderName }}
              </span>
            </div>
          </div>
          <a-tag v-if="record.commander === 0" color="red">工单退回</a-tag>
        </template>
        <template v-if="column.key === 'createTime'">
          <a-tooltip :title="`${toDateString(record.createTime)}`">
            <span class="ele-text-placeholder">
              {{ timeAgo(record.createTime) }}
            </span>
          </a-tooltip>
        </template>
        <template v-if="column.key === 'updateTime'">
          <div class="user-box">
            <a-tooltip :title="`ID:${record.lastReadUser}`">
              <a-avatar
                :size="30"
                v-if="record.lastReadUser > 0"
                :src="`${record.lastAvatar}`"
                style="margin-right: 4px"
              >
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
            </a-tooltip>
            <div class="user-info">
              <span class="ele-text-placeholder">
                {{ record.lastNickname }}
              </span>
              <span class="ele-text-placeholder">
                {{ timeAgo(record.updateTime) }}
              </span>
            </div>
          </div>
        </template>
        <template v-if="column.key === 'users'">
          <a-space>
            <ele-avatar-list :data="record.users" :size="22" />
          </a-space>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button @click="openInfo(record)">处理</a-button>
          </a-space>
        </template>
      </template>
    </ele-pro-table>
    <!-- 编辑弹窗 -->
    <TaskEdit v-model:visible="showEdit" :data="current" @done="reload" />
    <!-- 用户详情 -->
    <TaskInfo v-model:visible="showInfo" :data="current" @done="reload" />
    <!-- 成员管理 -->
    <TaskUser v-model:visible="showUsers" :data="current" @done="reload" />
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref, computed, watch } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import {
    UserOutlined,
    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 { toDateString } from 'ele-admin-pro';
  import Search from './components/search.vue';
  import TaskEdit from './components/task-edit.vue';
  import TaskInfo from './components/task-info.vue';
  import { pageTask, removeTask, removeBatchTask } from '@/api/oa/task';
  import { timeAgo } from 'ele-admin-pro';
  import type { Task, TaskParam } from '@/api/oa/task/model';
  import TaskUser from '@/views/oa/task/components/task-user.vue';
  import { getDictionaryOptions } from '@/utils/common';
  import { useUserStore } from '@/store/modules/user';

  const userStore = useUserStore();
  // 当前用户信息
  const loginUser = computed(() => userStore.info ?? {});
  const taskType = localStorage.getItem('taskType');
  const props = defineProps<{
    // 机构 id
    data?: any;
  }>();

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

  // 表格选中数据
  const selection = ref<Task[]>([]);
  // 当前编辑数据
  const current = ref<Task | null>(null);
  // const users = ref()
  // 获取字典数据
  const taskProgress = getDictionaryOptions('taskProgress');
  const filters = getDictionaryOptions('taskType');

  // 是否显示资产详情
  const showInfo = ref(false);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  const showUsers = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    if (filters) {
      where.progress = filters.progress;
      where.taskSource = filters.taskSource;
      where.taskType = filters.taskType;
      where.status = filters.status;
    }
    // 搜索条件
    if (props.data.key) {
      where.status = props.data.key;
      // where.userId = loginUser.value.userId;
    }
    return pageTask({
      ...where,
      ...orders,
      page,
      limit
    });
  };

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    // {
    //   key: 'index',
    //   width: 48,
    //   align: 'center',
    //   fixed: 'left',
    //   hideInSetting: true,
    //   customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    // },
    {
      title: '操作',
      key: 'action',
      width: 100,
      align: 'center',
      fixed: 'left',
      hideInSetting: true
    },
    {
      title: '工单号',
      dataIndex: 'taskId',
      width: 80,
      align: 'center',
      key: 'taskId'
    },
    {
      title: '工单标题',
      dataIndex: 'name',
      width: 280,
      key: 'name',
      ellipsis: true
    },
    {
      title: '工单类型',
      dataIndex: 'taskType',
      key: 'taskType',
      width: 100,
      align: 'center',
      filters: filters.value
    },
    {
      title: '关联应用',
      dataIndex: 'appName',
      key: 'appName',
      width: 130
    },
    {
      title: '发起人',
      width: 160,
      dataIndex: 'promoter',
      key: 'promoter'
    },
    {
      title: '受理人',
      dataIndex: 'commander',
      key: 'commander',
      width: 160,
      hideInSetting: true
    },
    {
      title: '工单状态',
      dataIndex: 'progress',
      key: 'progress',
      width: 130,
      align: 'center',
      filters: taskProgress.value
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: true,
      width: 140,
      align: 'center',
      ellipsis: true,
      customRender: ({ text }) => toDateString(text)
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      sorter: true,
      width: 140,
      align: 'center',
      ellipsis: true,
      customRender: ({ text }) => toDateString(text)
    }
  ]);

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

  /* 打开编辑弹窗 */
  const openEdit = (row?: Task) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /* 打开用户详情弹窗 */
  const openInfo = (row?: Task) => {
    current.value = row ?? null;
    showInfo.value = true;
  };

  const onPromoter = (row?: Task) => {
    reload({
      promoter: row?.promoter
    });
  };

  const onCommander = (row?: Task) => {
    reload({
      commander: row?.commander
    });
  };

  /* 删除单个 */
  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;
    }
    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);
          });
      }
    });
  };

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

  watch(
    () => props.data,
    (visible) => {
      console.log(visible);
      if (visible) {
        if (props.data) {
          reload();
        } else {
        }
      }
    }
  );
</script>

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

<style lang="less" scoped>
  .sys-org-table :deep(.ant-table-body) {
    overflow: auto !important;
    overflow: overlay !important;
  }

  .sys-org-table :deep(.ant-table-pagination.ant-pagination) {
    padding: 0 4px;
    margin-bottom: 0;
  }
  .user-box {
    display: flex;
    align-items: center;
    .user-info {
      display: flex;
      flex-direction: column;
      align-items: start;
    }
  }
</style>
