<script setup>
import { q, m } from "#imports";
import { ref } from "vue";
import { Loading, Notify } from "quasar";
const isExporting = ref(false);
const onExportSchema = async () => {
  isExporting.value = true;
  Loading.show({ message: "\u6B63\u5728\u532F\u51FA Schema..." });
  try {
    const data = await q({
      system: {
        database: {
          exportSchema: true
        }
      }
    });
    const timestamp = (/* @__PURE__ */ new Date()).toISOString().slice(0, 19).replace(/:/g, "-");
    const filename = `schema-${timestamp}.json`;
    const blob = new Blob(
      [data.system.database.exportSchema],
      { type: "application/json;charset=utf-8" }
    );
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.download = filename;
    a.href = url;
    a.click();
    setTimeout(() => URL.revokeObjectURL(url), 1e3);
    Notify.create({
      type: "positive",
      message: "Schema \u532F\u51FA\u6210\u529F\uFF01",
      position: "top"
    });
  } catch (e) {
    Notify.create({
      type: "negative",
      message: "\u532F\u51FA\u5931\u6557\uFF1A" + e.message,
      position: "top"
    });
  } finally {
    Loading.hide();
    isExporting.value = false;
  }
};
const selectedFile = ref(null);
const dryRun = ref(true);
const isImporting = ref(false);
const importResult = ref(null);
const onFileChange = () => {
  importResult.value = null;
};
const clearFile = () => {
  selectedFile.value = null;
  importResult.value = null;
};
const onImportSchema = async () => {
  if (!selectedFile.value) return;
  isImporting.value = true;
  Loading.show({
    message: dryRun.value ? "\u6B63\u5728\u9810\u89BD\u8B8A\u66F4..." : "\u6B63\u5728\u532F\u5165 Schema..."
  });
  try {
    if (dryRun.value) {
      const data = await q({
        system: {
          database: {
            importSchema: {
              __args: { schema: selectedFile.value }
            }
          }
        }
      });
      importResult.value = data.system.database.importSchema;
      Notify.create({
        type: "info",
        message: "\u9810\u89BD\u5B8C\u6210\uFF0C\u8ACB\u6AA2\u8996\u8B8A\u66F4\u5167\u5BB9",
        position: "top"
      });
    } else {
      await m("importDatabaseSchema", { schema: selectedFile.value });
      Notify.create({
        type: "positive",
        message: "Schema \u532F\u5165\u6210\u529F\uFF01",
        position: "top"
      });
      importResult.value = null;
      clearFile();
    }
  } catch (e) {
    Notify.create({
      type: "negative",
      message: "\u64CD\u4F5C\u5931\u6557\uFF1A" + e.message,
      position: "top"
    });
  } finally {
    Loading.hide();
    isImporting.value = false;
  }
};
</script>

<template>
    <l-page title="資料庫 Schema 遷移">
        <div class="row q-col-gutter-md">
            <!-- EXPORT 區塊 -->
            <div class="col-12 col-md-6">
                <l-card>
                    <q-card-section>
                        <div class="text-h6">
                            <q-icon name="sym_o_download" class="q-mr-sm" />
                            匯出 Schema
                        </div>
                    </q-card-section>
                    <q-card-section>
                        <p class="text-grey-7">
                            匯出目前的資料庫 Schema 為 JSON 檔案，可用於備份或遷移至其他環境。
                        </p>
                        <l-btn label="匯出 Schema" icon="sym_o_download" color="primary" :loading="isExporting"
                            :disable="isExporting" @click="onExportSchema" />
                    </q-card-section>
                </l-card>
            </div>

            <!-- IMPORT 區塊 -->
            <div class="col-12 col-md-6">
                <l-card>
                    <q-card-section>
                        <div class="text-h6">
                            <q-icon name="sym_o_upload" class="q-mr-sm" />
                            匯入 Schema
                        </div>
                    </q-card-section>
                    <q-card-section>
                        <p class="text-grey-7">
                            選擇 Schema JSON 檔案進行匯入，建議先使用 Dry Run 預覽變更。
                        </p>

                        <q-file v-model="selectedFile" label="選擇 Schema 檔案 (.json)" accept=".json,application/json"
                            clearable outlined class="q-mb-md" @update:model-value="onFileChange">
                            <template #prepend>
                                <q-icon name="sym_o_attach_file" />
                            </template>
                        </q-file>

                        <l-checkbox v-model="dryRun" label="Dry Run (僅預覽變更，不實際執行)" class="q-mb-md" />

                        <div class="row q-gutter-sm">
                            <l-btn v-if="dryRun" label="預覽變更" icon="sym_o_preview" color="primary"
                                :loading="isImporting" :disable="isImporting || !selectedFile"
                                @click="onImportSchema" />
                            <l-btn v-else label="執行匯入" icon="sym_o_upload" color="negative" :loading="isImporting"
                                :disable="isImporting || !selectedFile" confirm-message="確定要執行 Schema 匯入嗎？此操作將修改資料庫結構。"
                                @click="onImportSchema" />
                        </div>
                    </q-card-section>
                </l-card>
            </div>

            <!-- 結果顯示區塊 -->
            <div v-if="importResult" class="col-12">
                <l-card>
                    <q-card-section>
                        <div class="text-h6">
                            <q-icon name="sym_o_list_alt" class="q-mr-sm" />
                            變更預覽結果
                        </div>
                    </q-card-section>
                    <q-card-section>
                        <pre class="import-result">{{ importResult }}</pre>
                    </q-card-section>
                </l-card>
            </div>
        </div>
    </l-page>
</template>

<style scoped>
.import-result{background-color:#f5f5f5;border-radius:8px;font-size:13px;line-height:1.5;max-height:500px;overflow-x:auto;overflow-y:auto;padding:16px}
</style>
