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

import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { useAccess } from '@vben/access';
import { Page } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';

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

import { generateLicense, getLicense } from '#/api/license/license';
import { useDescription } from '#/components/description';
import { $t } from '#/locales';

import { useDetailSchema } from '../data';

const { hasAccessByCodes } = useAccess();

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const formData = ref<LicenseApi.License>();

const [Description] = useDescription({
  componentProps: {
    bordered: true,
    column: 1,
    class: 'mx-4',
  },
  schema: useDetailSchema(),
});

/** 获取详情数据 */
async function getDetail(id: any) {
  if (!id) {
    return;
  }
  loading.value = true;
  try {
    formData.value = await getLicense(id);
  } finally {
    loading.value = false;
  }
}

const tabs = useTabs();
/** 返回列表 */
function close() {
  tabs.closeCurrentTab();
  router.push('/license');
}

/** 生成文件 */
async function onGenerate() {
  if (!formData.value?.id) {
    return;
  }
  const hideLoading = message.loading({
    content: $t('license.generating'),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await generateLicense(formData.value.id);
    hideLoading();
    await getDetail(formData.value.id);

    // 确认是否下载该文件
    // confirm({
    //   title: $t('license.generateSuccess'),
    //   content: $t('license.isDownload', [fileName]),
    //   confirmText: $t('license.download'),
    //   cancelText: $t('common.cancel'),
    // }).then(async () => {
    //   const res = await fetch(response);
    //   if (!res.ok) {
    //     message.error($t('license.downloadFailed'));
    //     return;
    //   }
    //   const blob = await res.blob();

    //   downloadFileFromBlobPart({ fileName, source: blob });
    // });
    message.success($t('license.generateSuccess'));
  } finally {
    hideLoading();
  }
}

// 初始化
getDetail(route.query.id);
</script>

<template>
  <Page auto-content-height v-loading="loading">
    <div class="bg-card flex h-[100%] flex-col rounded-md p-4">
      <div class="flex-1 overflow-auto py-4">
        <Description :data="formData" :label-style="{ width: '250px' }" />
      </div>
      <div class="mt-4 flex justify-center space-x-2">
        <Button @click="close"> {{ $t('common.back') }}</Button>
        <Button
          v-if="
            hasAccessByCodes(['license:license:generate']) &&
            formData?.status === 1
          "
          type="primary"
          :loading="loading"
          @click="onGenerate"
        >
          {{ $t('license.generate') }}
        </Button>
      </div>
    </div>
  </Page>
</template>
