<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="assetsId"
          :columns="columns"
          :height="tableHeight"
          :datasource="datasource"
          v-model:selection="selection"
          :customRow="customRow"
          :scroll="{ x: 1200 }"
        >
          <template #toolbar>
            <search
              :selection="selection"
              @search="reload"
              @add="openEdit"
              @remove="removeBatch"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'customer'">
              {{ record.nickname }}
            </template>
            <template v-if="column.key === 'name'">
              <a-tooltip title="查看详情">
                {{ record.name }}
              </a-tooltip>
            </template>
            <template v-if="column.key === 'code'">
              <a-tooltip title="服务器公网IP">
                {{ record.code }}
              </a-tooltip>
            </template>
            <template v-if="column.key === 'status'">
              <a-tag :color="record.status === '正常' ? 'green' : 'red'">
                {{ record.status }}
              </a-tag>
            </template>
            <template v-if="column.key === 'comments'">
              <a-tooltip :title="record.comments" placement="topLeft">
                {{ record.comments }}
              </a-tooltip>
            </template>
            <template v-if="column.key === 'endTime'">
              <div class="ele-text-info">{{
                toDateString(record.startTime, 'yyyy-MM-dd')
              }}</div>
              <div v-html="getEndTime(record.endTime)"></div>
            </template>
            <template v-if="column.key === 'createTime'">
              <a-tooltip :title="`${toDateString(record.createTime)}`">
                {{ timeAgo(record.createTime) }}
              </a-tooltip>
            </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>
      </a-card>
      <!-- 编辑弹窗 -->
      <assets-edit v-model:visible="showEdit" :data="current" @done="reload" />
    </div>
  </div>
</template>

<!--suppress TypeScriptValidateTypes -->
<script lang="ts" setup>
  import { timeAgo } from 'ele-admin-pro';
  import { createVNode, computed, ref } 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,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { toDateString } from 'ele-admin-pro';
  import Search from './components/search.vue';
  import AssetsEdit from './components/assets-edit.vue';
  import { pageAssets, removeAssets, removeBatchAssets } from '@/api/oa/assets';
  import type { Assets, AssetsParam } from '@/api/oa/assets/model';
  import { getEndTime } from '@/utils/common';

  // 表格实例
  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: 'name',
      key: 'name'
    },
    {
      title: '服务器IP',
      dataIndex: 'code',
      key: 'code'
    },
    {
      title: '品牌',
      dataIndex: 'brand'
    },
    {
      title: '所属企业',
      dataIndex: 'companyName',
      key: 'companyName'
    },
    // {
    //   title: '备注',
    //   dataIndex: 'comments',
    //   key: 'comments',
    //   ellipsis: true
    // },
    {
      title: '有效期',
      dataIndex: 'endTime',
      key: 'endTime',
      sorter: true
    },
    {
      title: '状态',
      dataIndex: 'status',
      sorter: true,
      key: 'status'
    },
    {
      title: '排序',
      dataIndex: 'sortNumber',
      sorter: true,
      hideInTable: true
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: true,
      ellipsis: true,
      hideInTable: true,
      customRender: ({ text }) => toDateString(text)
    }
    // {
    //   title: '操作',
    //   key: 'action',
    //   width: 200,
    //   align: 'center',
    //   hideInSetting: true
    // }
  ]);

  // 表格选中数据
  const selection = ref<Assets[]>([]);
  // 当前编辑数据
  const current = ref<Assets | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    return pageAssets({ ...where, ...orders, page, limit });
  };

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

  // 搜索是否展开
  const searchExpand = ref(false);

  // 表格固定高度
  const fixedHeight = ref(false);

  // 表格高度
  const tableHeight = computed(() => {
    return fixedHeight.value
      ? searchExpand.value
        ? 'calc(100vh - 618px)'
        : 'calc(100vh - 562px)'
      : void 0;
  });

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

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

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

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

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

<style lang="less" scoped>
  .user-box {
    display: flex;
    align-items: center;
    .user-info {
      display: flex;
      flex-direction: column;
      align-items: start;
    }
  }
</style>
