<template>
  <q-form action="post">
    <div class="row py-1">
      <div class="col-3"></div>
      <div class="col-6">
        <w-select
          v-model="formDataRef.datasource"
          :label="$t('developer.backend.export.liquibase.datasource')"
          :options="datasourceOptionsRef"
          style="width: 100%"
        ></w-select>
      </div>
      <div class="col-3"></div>
    </div>
    <div class="row py-1">
      <div class="col-3"></div>
      <div class="col-6">
        <q-file ref="fileRef" v-model="formDataRef.file" :label="$t('file.multiple.tip')" multiple dense outlined clearable counter accept=".csv">
          <template #prepend>
            <q-icon name="cloud_upload" />
          </template>
        </q-file>
      </div>
      <div class="col-3"></div>
    </div>
    <div class="row py-1">
      <div class="col-3"></div>
      <div class="col-6">
        <w-checkbox v-model="formDataRef.deleteFirst" :label="$t('developer.backend.import.liquibase.deleteFirst')" style="width: 100%"></w-checkbox>
      </div>
      <div class="col-3"></div>
    </div>
    <div class="row py-1">
      <div class="col-3"></div>
      <div class="col-6 row justify-center q-gutter-md py-2">
        <w-progress-btn
          ref="progressBtnRef"
          icon="bi-database-up"
          :label="$t('import')"
          data-url="/api/jdbc/data/traceImporterExecuteProgress"
          @click="importData"
        ></w-progress-btn>
      </div>
      <div class="col-3"></div>
    </div>
  </q-form>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, onUpdated } from 'vue';
import { useI18n } from 'vue-i18n';
import { axios, Environment, DialogManager } from 'platform-core';

const { t } = useI18n();

const progressBtnRef = ref();
const datasourceOptionsRef = ref([]);
const formDataRef = reactive({
  datasource: undefined,
  file: undefined,
  deleteFirst: false,
});
const fileRef = ref();

const importData = () => {
  DialogManager.confirm(t('developer.backend.import.liquibase.import.tip'), () => {
    axios
      .post(
        Environment.apiContextPath('/api/jdbc/data/importData'),
        {
          datasource: formDataRef.datasource,
          deleteFirst: formDataRef.deleteFirst,
          files: fileRef.value.nativeEl.files,
        },
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        },
      )
      .then(() => {
        progressBtnRef.value.start();
      });
  });
};

const loadDatasource = () => {
  axios.get(Environment.apiContextPath('/api/system/datasource?pageable=false&sortBy=name')).then((response) => {
    const data = response?.data.content;
    const datasourceOptions = [];
    if (data && data.length > 0) {
      for (let item of data) {
        datasourceOptions.push({ label: item.name, value: item.name });
      }
    }
    datasourceOptionsRef.value = datasourceOptions;
  });
};

onMounted(() => {
  loadDatasource();
});
</script>
