<script lang="ts" setup>
import type {
  OnActionClickParams,
  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,
  exportLicense,
  getLicensePage,
} from '#/api/license/license';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';

const router = useRouter();

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

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

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

/** 申请License */
function onApply(row: LicenseApi.License) {
  formModalApi.setData({ ...row, action: 1 }).open();
}

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

/** 下载License */
async function onDownload(row: LicenseApi.License) {
  const fileName = `${row.fileUrl?.slice(
    Math.max(0, row.fileUrl.lastIndexOf('/') + 1),
    row.fileUrl.lastIndexOf('_'),
  )}.ini`;
  const res = await fetch(row.fileUrl);
  if (!res.ok) {
    message.error($t('license.downloadFailed'));
    return;
  }
  const blob = await res.blob();

  downloadFileFromBlobPart({ fileName, source: blob });
}

/** 编辑License */
function onEdit(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.xls', source: data });
}

/** 表格操作按钮的回调函数 */
function onActionClick({ code, row }: OnActionClickParams<LicenseApi.License>) {
  switch (code) {
    case 'apply': {
      onApply(row);
      break;
    }
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'download': {
      onDownload(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
    case 'generate': {
      onGenerate(row);
      break;
    }
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    collapsed: true,
    collapsedRows: 2,
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(onActionClick),
    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" />

    <Grid :table-title="$t('license.list')">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: $t('ui.actionTitle.create', ['License']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['license:license:create'],
              onClick: onCreate,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['license:license:export'],
              onClick: onExport,
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
