<template>
  <w-dialog ref="dialogRef" :title="$t('re.resources.designer.testCase.grid.tools.upload')" width="600px" :can-maximize="false">
    <q-form action="post">
      <div class="row py-1">
        <div class="col-1"></div>
        <div class="col-10">
          <q-file ref="fileRef" v-model="modelValue.file" :label="$t('file.single.tip')" dense outlined clearable counter accept=".xlsx">
            <template #prepend>
              <q-icon name="cloud_upload" />
            </template>
          </q-file>
        </div>
        <div class="col-1"></div>
      </div>
      <div class="row py-1">
        <div class="col-1"></div>
        <div class="col-10 row justify-center q-gutter-md py-2">
          <q-btn icon="bi-database-up" :label="$t('import')" color="primary" no-caps @click="importData"></q-btn>
        </div>
        <div class="col-1"></div>
      </div>
    </q-form>
  </w-dialog>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue';
import { Environment, Downloader } from 'platform-core';

const emit = defineEmits<{
  (e: 'afterImported', evt: Event): void;
}>();

const dialogRef = ref();
const modelValue = reactive({
  file: undefined,
});
const fileRef = ref();

const importData = () => {
  Downloader.post(
    Environment.apiContextPath('/api/re/testCase/upload'),
    {
      file: fileRef.value.nativeEl.files[0],
    },
    {
      loading: true,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    },
  ).then(() => {
    close();
  });
};

const open = () => {
  modelValue.file = undefined;
  dialogRef.value.show();
};

const close = () => {
  dialogRef.value.hide();
};

defineExpose({
  open,
  close,
});
</script>
