<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, getMeta } from '@/js/helper';
import { isType, type OneOf, type Properties } from '@/js/kintone-rest-api-client';
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: [createEmptyJoinTable()],
});

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 () => {
  nextTick(async () => {
    spinner.value?.close(); // fix bug: kuc-spinner will not auto amount to target HTML element when init loading
    const savedData = kintone.plugin.app.getConfig(props.pluginId);
    loading.value = true;
    cachedData.apps = await loadApps();
    cachedData.currentAppFields = await loadAppFieldsAndLayout();
    if (savedData?.joinTablesForConfig) {
      data.joinTables = JSON.parse(savedData.joinTablesForConfig);
    }
    data.buttonName = savedData?.buttonName || '集約';
    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() {
  const currentAppMeta = cachedData.currentAppFields.fields;
  const convertJoinTables = JSON.parse(JSON.stringify(data.joinTables)) as JoinTable<OneOf | string>[];
  convertJoinTables.forEach((item) => {
    const meta = getMeta(item.meta as Properties, item.table);

    // Process onConditions
    item.onConditions.forEach((condition) => {
      condition.leftField = meta[condition.leftField as string] || condition.leftField;
      condition.rightField = currentAppMeta[condition.rightField as string] || condition.rightField;
    });

    // Process fieldsMapping
    item.fieldsMapping.forEach((mapping) => {
      mapping.leftField = meta[mapping.leftField as string] || mapping.leftField;
      mapping.rightField = currentAppMeta[mapping.rightField as string] || mapping.rightField;
    });

    // Process whereConditions
    item.whereConditions.forEach((condition) => {
      condition.field = meta[condition.field as string] || condition.field;
    });
    delete item.meta;
  });

  data.joinTables.forEach((item) => {
    delete item.meta;
  });

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

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