<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 { downloadFileFromBlobPart } from '@vben/utils';

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

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

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 importCustomer(data.file, data.updateSupport);
      // 关闭并提示
      await modalApi.close();
      emit('success');
      let failuresMsg: any;
      if (result.creates && result.creates.length > 0) {
        failuresMsg = h(
          'div',
          {
            style: {
              color: 'green',
            },
          },
          [failuresMsg, `新增成功：${result.creates.join('，')}`],
        );
      }
      if (result.updates && result.updates.length > 0) {
        failuresMsg = h(
          'div',
          {
            style: {
              color: 'blue',
            },
          },
          [failuresMsg, `更新成功：${result.updates.join('，')}`],
        );
      }
      for (const key in result.failures) {
        failuresMsg = h(
          'div',
          {
            style: {
              color: 'red',
            },
          },
          [failuresMsg, `导入失败：${key}，失败原因：${result.failures[key]}`],
        );
      }
      message.info(failuresMsg, 10);
    } finally {
      modalApi.unlock();
    }
  },
});

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

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

<template>
  <Modal title="导入客户" class="w-1/3">
    <Form class="mx-4">
      <template #file>
        <div class="w-full">
          <UploadDragger
            :max-count="1"
            accept=".xls,.xlsx"
            :before-upload="beforeUpload"
          >
            <p class="ant-upload-drag-icon">
              <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>
