<template>
  <div class="ele-body">
    <!-- 表格 -->
    <ele-pro-table
      ref="tableRef"
      row-key="projectId"
      :columns="columns"
      :datasource="datasource"
      v-model:selection="selection"
      :scroll="{ x: 800 }"
    >
      <template #toolbar>
        <search @search="reload" @add="openEdit" @remove="removeBatch" />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'projectName'">
          <a-avatar
            class="project-icon"
            :size="36"
            shape="square"
            :src="`https://file.wsdns.cn/${record.projectAvatar}`"
          >
            <template #icon>
              <AntDesignOutlined />
            </template>
          </a-avatar>
          <a-tooltip title="查看详情">
            <a href="#" @click="openInfo(record)">{{ record.projectName }}</a>
          </a-tooltip>
        </template>
        <template v-if="column.key === 'progress'">
          <a-progress :percent="record.progress * 2" :steps="5" />
        </template>
        <template v-if="column.key === 'status'">
          <div v-for="(dict, index) in projectStatus" :key="index">
            <a-tag :color="dict.comments" v-if="dict.value === record.status">{{
              dict.label
            }}</a-tag>
          </div>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="openInfo(record)">详情</a>
            <a-divider type="vertical" />
            <a @click="openEdit(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>

    <!-- 编辑弹窗 -->
    <project-edit v-model:visible="showEdit" :data="current" @done="reload" />
    <!-- 用户详情 -->
    <project-info v-model:visible="showInfo" :data="current" @done="reload" />
  </div>
</template>

<script lang="ts" setup>
  import { computed, createVNode, ref } from 'vue';
  import { message, Modal, SelectProps } from 'ant-design-vue';
  import {
    ExclamationCircleOutlined,
    AntDesignOutlined
  } 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 ProjectEdit from './components/project-edit.vue';
  import ProjectInfo from './components/project-info.vue';
  import { pageProject, removeProject, removeBatchProject } from '@/api/oa/project';
  import type { Project, ProjectParam } from '@/api/oa/project/model';
  import { listDictionaryData } from '@/api/system/dictionary-data';
  import { useUserStore } from '@/store/modules/user';
  import {getDictionaryOptions} from "@/utils/common";

  const userStore = useUserStore();
  const props = defineProps<{
    // 机构 id
    type?: any;
  }>();

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

  // 是否显示资产详情
  const showInfo = ref(false);

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 280,
      ellipsis: true,
      sorter: true
    },
    {
      title: '项目简介',
      dataIndex: 'comments'
    },
    {
      title: '开发进度',
      dataIndex: 'progress',
      key: 'progress',
      sorter: true
    },
    {
      title: '项目地址',
      dataIndex: 'url'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      sorter: true
    },
    {
      title: '排序',
      dataIndex: 'sortNumber',
      sorter: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: true,
      ellipsis: true,
      customRender: ({ text }) => toDateString(text)
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      align: 'center',
      hideInSetting: true
    }
  ]);

  // 表格选中数据
  const selection = ref<Project[]>([]);

  // 当前编辑数据
  const current = ref<Project | null>(null);

  // 当前用户信息
  const loginUser = computed(() => userStore.info ?? {});

  // 是否显示编辑弹窗
  const showEdit = ref(false);

  /* 获取字典数据 */
  const projectStatus = getDictionaryOptions('projectStatus');

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    // 搜索条件
    if (props.type.key === 'my') {
      where.userId = loginUser.value.userId;
    } else if (props.type.key === 'assist') {
      where.userId = loginUser.value.userId;
    } else if (props.type.key === 'all') {
      // 全部客户
    }
    return pageProject({ ...where, ...orders, page, limit });
  };

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

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

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

  /* 删除单个 */
  const remove = (row: Project) => {
    const hide = message.loading('请求中..', 0);
    removeProject(row.projectId)
      .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);
        removeBatchProject(selection.value.map((d) => d.projectId))
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };
</script>

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

<style lang="less" scoped>
  .project-icon {
    margin-right: 10px;
  }
  .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;
  }
</style>
