<script lang="ts" setup>
import type { FileType } from 'ant-design-vue/es/upload/interface';

import { h } from 'vue';

import { useVbenModal } from '@vben/common-ui';
// import { InboxOutlined } from '@vben/icons';
import { downloadFileFromBlobPart } from '@vben/utils';

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

import { useVbenForm } from '#/adapter/form';
import { importLicense, importTemplate } from '#/api/license/license';

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

const emit = defineEmits(['success']);

const [Form, formApi] = useVbenForm({
  commonConfig: {
    formItemClass: 'col-span-2',
    labelWidth: 120,
  },
  layout: 'horizontal',
  schema: useImportFormSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    // 提交表单
    const data = await formApi.getValues();
    try {
      const result = await importLicense(data.file, data.updateSupport);
      // 关闭并提示
      await modalApi.close();
      emit('success');
      let failuresMsg: any;
      const createsLength = result.creates ? result.creates.length : 0;
      const updatesLength = result.updates ? result.updates.length : 0;
      const total = result.total || 0;
      const failuresLength = total - createsLength - updatesLength;
      const resultMsg = `总共${total}条，新增成功${createsLength}条, 更新成功${updatesLength}条, 导入失败${failuresLength}条`;

      failuresMsg = h(
        'div',
        {
          style: {
            color: 'blue',
          },
        },
        [failuresMsg, resultMsg],
      );
      for (const key in result.failureMap) {
        failuresMsg = h(
          'div',
          {
            style: {
              color: 'red',
              overflowY: 'auto',
              maxHeight: '600px',
            },
          },
          [failuresMsg, `导入失败SN（${key}）：${result.failureMap[key]}`],
        );
      }
      notification.open({
        message: '导入结果',
        description: failuresMsg,
        style: {
          color: failuresLength > 0 ? 'red' : 'green',
        },
        duration: 0,
      });
    } finally {
      modalApi.unlock();
    }
  },
});

/** 上传前 */
function beforeUpload(file: FileType) {
  formApi.setFieldValue('file', file);
  return false;
}

/** 下载模版 */
async function handleDownload() {
  const data = await importTemplate();
  downloadFileFromBlobPart({ fileName: 'License导入模板.xlsx', source: data });
}
</script>

<template>
  <Modal title="导入License" class="w-1/3">
    <Form class="mx-4">
      <template #file>
        <div class="w-full">
          <UploadDragger
            :max-count="1"
            accept=".xls,.xlsx"
            :before-upload="beforeUpload"
          >
            <!-- <Button type="primary"> 选择 Excel 文件 </Button> -->
            <p class="ant-upload-drag-icon">
              <!-- <InboxOutlined /> -->
              <span class="icon-[ep--upload-filled] size-12"></span>
            </p>

            <p class="ant-upload-text">点击或拖拽Excel文件上传</p>
          </UploadDragger>
        </div>
      </template>
    </Form>
    <template #prepend-footer>
      <div class="flex flex-auto items-center">
        <Button @click="handleDownload"> 下载导入模板 </Button>
      </div>
    </template>
  </Modal>
</template>
