<template>
  <div>
    <q-toolbar class="q-gutter-md py-2">
      <q-select
        v-model="valueReactive.datasource"
        :label="$t('developer.backend.sql.datasource')"
        outlined
        dense
        emit-value
        map-options
        :options="datasourceOptionsRef"
        style="width: 200px"
        @update:model-value="
          (value) => {
            datasourceChanged(value);
          }
        "
      ></q-select>
      <q-select
        v-model="valueReactive.schema"
        :label="$t('developer.backend.sql.schema')"
        outlined
        dense
        emit-value
        map-options
        :options="schemaOptionsRef"
        style="width: 200px"
        @update:model-value="
          (value) => {
            schemaChanged(valueReactive.datasource, value);
          }
        "
      ></q-select>
      <q-space />
      <q-btn :label="$t('developer.backend.sql.action.execute')" no-caps outline icon="bi-lightning" />
      <q-btn :label="$t('developer.backend.sql.action.executeAll')" no-caps outline icon="bi-play" />
      <q-btn
        :label="$t('developer.backend.sql.action.import')"
        no-caps
        outline
        icon="bi-filetype-xlsx"
        @click="
          () => {
            importExcelDialogRef.open();
          }
        "
      />
    </q-toolbar>
    <div class="px-3">
      <w-code-mirror label="SQL" :rows="10" lang="sql"></w-code-mirror>
    </div>
    <ImportExcel ref="importExcelDialogRef"></ImportExcel>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, onUpdated } from 'vue';
import { useI18n } from 'vue-i18n';
import { axios, Environment, DialogManager, Downloader } from 'platform-core';
import ImportExcel from './import-excel/ImportExcel.vue';

const datasourceOptionsRef = ref([]);
const schemaOptionsRef = ref([]);
const importExcelDialogRef = ref();

const valueReactive = reactive({
  datasource: undefined,
  schema: undefined,
  sql: undefined,
});

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;
  });
};

const datasourceChanged = (datasource: string) => {
  datasource = datasource || '';
  axios.get(Environment.apiContextPath('/api/jdbc/metadata/getSchemas?datasource=' + datasource)).then((response) => {
    const data = response?.data;
    const schemaOptions = [];
    if (data && data.length > 0) {
      for (let item of data) {
        schemaOptions.push({ label: item.name, value: item.name });
      }
    }
    schemaOptionsRef.value = schemaOptions;
  });
};

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