<template>
  <h2 class="settings-heading">{{ $t('config.title') }}</h2>
  <p class="kintoneplugin-desc">{{ $t('config.desc') }}</p>

  <plugin-row class="header-row border">
    <plugin-input v-model="data.buttonName" placeholder="集約" label="集約ボタン名" />
  </plugin-row>

  <div id="main-area" ref="mainArea">
    <plugin-table-area v-for="joinTable in data.joinTables" :table="joinTable" :key="joinTable.id" />
  </div>

  <plugin-row class="footer-row border">
    <kuc-button text="キャンセル" type="normal" @click="cancel" />
    <kuc-button text="保存する" class="save-btn" type="submit" @click="save" />
  </plugin-row>

  <kuc-spinner :container="mainArea" ref="spinner"></kuc-spinner>
</template>
<script setup lang="ts">
import { createEmptyJoinTable, loadApps, loadAppFieldsAndLayout, EMPTY_OPTION, getEmptyOnCondition } from '@/js/helper';
import type { CachedData, FieldsInfo, JoinTable, SavedData } from '@/types/model';
import type { Spinner } from 'kintone-ui-component';

import { onMounted, watch, provide, reactive, ref, shallowRef, nextTick } from 'vue';

const props = defineProps<{ pluginId: string }>();
const loading = ref(false);
const data: SavedData = reactive({
  buttonName: '',
  joinTables: [] as JoinTable[],
});

const cachedData: CachedData = reactive({
  apps: [EMPTY_OPTION],
  currentAppFields: { fields: {}, layout: [] } as FieldsInfo,
});

provide('savedData', data);
provide('cachedData', cachedData);

const mainArea = shallowRef<HTMLElement | null>(null);
const spinner = shallowRef<Spinner | null>(null);

onMounted(async () => {
  spinner.value?.close(); // 修复不自动挂载到节点的 bug
  const savedData = kintone.plugin.app.getConfig(props.pluginId);
  // TODO
  data.buttonName = savedData?.buttonName || '集約';
  data.joinTables = savedData?.joinTables ? JSON.parse(savedData.joinTables) : [createEmptyJoinTable()];
  nextTick(async () => {
    loading.value = true;
    cachedData.apps = await loadApps();
    cachedData.currentAppFields = await loadAppFieldsAndLayout();
    loading.value = false;
  });
});

watch(loading, (load) => {
  load ? spinner.value?.open() : spinner.value?.close();
});

watch(
  () => data.joinTables.length,
  (newLength) => {
    if (newLength === 1) {
      data.joinTables[0].onConditions = [getEmptyOnCondition()];
    }
  },
);

function save() {
  kintone.plugin.app.setConfig({
    buttonName: data.buttonName,
    joinTables: JSON.stringify(data.joinTables || []),
  });
}

function cancel() {
  window.location.href = `../../${kintone.app.getId()}/plugin/`;
}
</script>
