<template>
  <w-dialog ref="dialogRef" :title="title" :width="width" :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="fileInputLabel" dense outlined clearable counter :accept="fileInputAccept">
            <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="actionButtonLabel" 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 { $t, axios, Environment } from 'platform-core';

const props = defineProps({
  title: { type: String, default: 'Import Dialog' },
  width: { type: String, default: '600px' },
  fileInputLabel: { type: String, default: 'Please select a file' },
  fileInputAccept: { type: String, default: '*' },
  actionUrl: { type: String, default: undefined },
  actionButtonLabel: { type: String, default: 'Import' },
});

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

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

const importData = () => {
  axios
    .post(
      props.actionUrl,
      {
        file: fileRef.value.nativeEl.files[0],
      },
      {
        loading: true,
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      },
    )
    .then(() => {
      close();
      emit('afterImported');
    });
};

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

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

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