<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false">
        <!-- 表格 -->
        <ele-pro-table
          ref="tableRef"
          row-key="assetsId"
          :columns="columns"
          :datasource="datasource"
          v-model:selection="selection"
          :customRow="customRow"
          tool-class="ele-toolbar-form"
          :scroll="{ x: 1200 }"
          class="sys-org-table"
          :striped="true"
        >
          <template #toolbar>
            <search
              @search="reload"
              :selection="selection"
              @add="openEdit"
              @remove="removeBatch"
              @advanced="openAdvanced"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'assetsName'">
              <div class="assets-box">
                <a-image
                  :height="45"
                  :width="45"
                  :preview="false"
                  :src="record.assetsIcon"
                  fallback="https://file.wsdns.cn/20230218/550e610d43334dd2a7f66d5b20bd58eb.svg"
                />
                <div class="assets-info">
                  <a
                    class="ele-text-heading"
                    @click="openUrl('/assets/server/detail/' + record.assetsId)"
                  >
                    {{ record.assetsName }}
                  </a>
                  <span class="ele-text-placeholder">
                    {{ record.assetsCode }}
                  </span>
                </div>
              </div>
            </template>
            <template v-if="column.key === 'code'">
              <span class="ele-text-heading">{{ record.code }}</span>
            </template>
            <template v-if="column.key === 'status'">
              <a-badge
                v-if="record.status == '运行中'"
                status="processing"
                :text="record.status"
              />
              <a-badge
                v-if="record.status == '已到期'"
                status="error"
                :text="record.status"
              />
            </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 === 'action'">
              <a-space>
                <a @click="openUrl('/assets/server/detail/' + record.assetsId)"
                  >详情</a
                >
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
    <!-- 编辑弹窗 -->
    <AssetsEdit v-model:visible="showEdit" :data="current" @done="reload" />
  </div>
</template>

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

  defineProps<{
    activeKey?: boolean;
    data?: any;
  }>();

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

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: 'ID',
      dataIndex: 'assetsId',
      width: 80,
      hideInTable: true
    },
    {
      title: '服务器IP',
      dataIndex: 'code',
      align: 'center',
      width: 200,
      key: 'code'
    },
    {
      title: '状态',
      dataIndex: 'status',
      sorter: true,
      width: 120,
      align: 'center',
      key: 'status'
    },
    {
      title: '品牌',
      width: 120,
      align: 'center',
      sorter: true,
      dataIndex: 'brand'
    },
    {
      title: '付费方式',
      dataIndex: 'endTime',
      key: 'endTime',
      align: 'center',
      sorter: true
    },
    {
      title: '所属企业',
      dataIndex: 'companyName',
      width: 280,
      key: 'companyName'
    },
    {
      title: '描述',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      align: 'center',
      fixed: 'right',
      hideInSetting: true
    }
  ]);

  // 表格选中数据
  const selection = ref<Assets[]>([]);
  // 当前编辑数据
  const current = ref<Assets | null>(null);
  // 是否显示资产详情
  // const showInfo = ref(false);
  const active = ref<any>('开发中');
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 是否显示高级搜索
  const showAdvancedSearch = ref(false);

  // 表格数据源
  const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
    // 默认类型
    if (where.keywords == undefined) {
      where.assetsStatus = '开发中';
      where.showExpiration = undefined;
    }
    if (where.assetsStatus == '未签续费') {
      where.assetsStatus = '已上架';
      where.showExpiration = false;
      where.sort = 'expirationTime';
      where.order = 'asc';
    }
    return pageAssets({
      ...where,
      ...orders,
      page,
      limit
    });
  };

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

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

  const expirationTime = (dateTime) => {
    const now = new Date().getTime();
    const expiration = new Date(dateTime).getTime();
    const mss = expiration - now;
    let days = Math.floor(mss / (1000 * 60 * 60 * 24));
    let hours = Math.floor((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    let minutes = Math.floor((mss % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.round((mss % (1000 * 60)) / 1000);
    return days;
  };

  /* 打开高级搜索 */
  const openAdvanced = () => {
    showAdvancedSearch.value = !showAdvancedSearch.value;
  };

  /* 删除单个 */
  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 = () => {
    console.log(selection.value);
    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: () => {
        openUrl('/assets/server/detail/' + record.assetsId);
      }
    };
  };

  // 统计数据
  const conut = ref({
    totalNum: 0,
    totalNum2: 0,
    totalNum3: 0,
    totalNum4: 0,
    totalNum5: 0
  });
  getCount().then((data: any) => {
    conut.value = data;
  });

  reload();
</script>

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

<style lang="less" scoped>
  p {
    line-height: 0.8;
  }
  .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;
  }
  .price-edit {
    padding-right: 5px;
  }
  .comments {
    max-width: 200px;
  }
  .assets-box {
    display: flex;
    .assets-info {
      display: flex;
      margin-left: 5px;
      flex-direction: column;
    }
  }
  .count {
    display: flex;
    .btn {
      margin: 0 12px;
      padding: 5px 16px;
      background-color: #f3f3f3;
      border-radius: 4px;
      cursor: pointer;
      display: flex;
      align-items: center;
      font-size: 15px;
      .divider {
        width: 4px;
        height: 14px;
        border-radius: 8px;
        margin-right: 8px;
        background-color: #c9c9c9;
      }
      .divider-active {
        width: 4px;
        height: 14px;
        border-radius: 8px;
        margin-right: 8px;
        background-color: #16a90b;
      }
      .active {
        color: #16a90b;
      }
    }
  }
</style>
