<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { LicenseApi } from '#/api/license/license';

import { useRouter } from 'vue-router';

import { Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart } from '@vben/utils';

import { message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteLicense,
  downloadLicense,
  exportLicense,
  getLicensePage,
} from '#/api/license/license';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import Detail from './modules/detail.vue';
import Form from './modules/form.vue';
import History from './modules/history.vue';
import ImportForm from './modules/import-form.vue';

const router = useRouter();

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [HistoryModal, historyModalApi] = useVbenModal({
  connectedComponent: History,
  destroyOnClose: true,
});

const [DetailModal, detailModalApi] = useVbenModal({
  connectedComponent: Detail,
  destroyOnClose: true,
});

const [ImportModal, importModalApi] = useVbenModal({
  connectedComponent: ImportForm,
  destroyOnClose: true,
});

/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 创建License */
function onCreate() {
  formModalApi.setData({}).open();
}

/** 生成License */
function onGenerate(row: LicenseApi.License) {
  router.push({ name: 'LicenseGenerate', query: { id: row.id } });
}

/** 详情License */
function onDetail(row: LicenseApi.License) {
  detailModalApi.setData(row).open();
}

/** 历史License */
function onHistory(row: LicenseApi.License) {
  historyModalApi.setData(row).open();
}

/** 下载License */
async function onDownload(row: LicenseApi.License) {
  const fileName = `${row.fileUrl?.slice(
    Math.max(0, row.fileUrl.lastIndexOf('/') + 1),
    row.fileUrl.lastIndexOf('_'),
  )}.tar.gz`;

  const hideLoading = message.loading({
    content: '下载中...',
    key: 'action_key_msg',
  });
  try {
    const res = await downloadLicense(row.id);
    const blob = new Blob([res], { type: 'application/tar' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    link.click();
    window.URL.revokeObjectURL(url);
  } finally {
    hideLoading();
  }
}

/** 重新申请License */
function onReapply(row: LicenseApi.License) {
  formModalApi.setData(row).open();
}

/** 删除License */
async function onDelete(row: LicenseApi.License) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.serialNo]),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await deleteLicense(row.id as number);
    hideLoading();
    message.success($t('ui.actionMessage.deleteSuccess', [row.serialNo]));
    onRefresh();
  } catch {
    hideLoading();
  }
}

/** 导出表格 */
async function onExport() {
  const data = await exportLicense(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: 'License.xlsx', source: data });
}

/** 导入用户 */
function handleImport() {
  importModalApi.open();
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    collapsed: true,
    collapsedRows: 2,
    schema: useGridFormSchema(),
    submitOnEnter: true,
  },
  gridOptions: {
    columns: useGridColumns(),
    height: 'auto',
    pagerConfig: {
      enabled: true,
    },
    id: 'license-license-list',
    customConfig: {
      storage: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getLicensePage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: { code: 'query' },
      search: true,
    },
  } as VxeTableGridOptions<LicenseApi.License>,
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="onRefresh" />
    <DetailModal @success="onRefresh" />
    <HistoryModal @success="onRefresh" />
    <ImportModal @success="onRefresh" />
    <Grid :table-title="$t('license.list')">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: $t('license.applyAction', ['License']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['license:license:apply'],
              onClick: onCreate,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['license:license:export'],
              onClick: onExport,
            },
            {
              label: $t('ui.actionTitle.import', ['License']),
              type: 'primary',
              icon: ACTION_ICON.UPLOAD,
              auth: ['license:license:import'],
              onClick: handleImport,
            },
          ]"
        />
      </template>

      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: $t('license.detail'),
              type: 'link',
              auth: ['license:license:query'],
              onClick: onDetail.bind(null, row),
            },
            {
              label: $t('license.generate'),
              type: 'link',
              ifShow: row.status === 1 || row.status === 4,
              auth: ['license:license:generate'],
              onClick: onGenerate.bind(null, row),
            },
            {
              label: $t('license.download'),
              type: 'link',
              ifShow: row.status === 3,
              auth: ['license:license:query'],
              onClick: onDownload.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              auth: ['license:license:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.serialNo]),
                confirm: onDelete.bind(null, row),
              },
            },
          ]"
          :drop-down-actions="[
            {
              label: $t('license.reapply'),
              type: 'link',
              ifShow: row.status === 3,
              auth: ['license:license:reapply'],
              onClick: onReapply.bind(null, row),
            },
            {
              label: $t('license.history'),
              type: 'link',
              ifShow: row.hasHistory,
              auth: ['license:license:query'],
              onClick: onHistory.bind(null, row),
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
