<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 :disabled="!canSave" text="保存する" class="save-btn" type="submit" @click="save" />
  </plugin-row>

  <kuc-spinner :container="mainArea" ref="spinner"></kuc-spinner>
  <error-dialog :message="errMessage" :show="showError" @update:show="(value) => showError = value"></error-dialog>
</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 canSave = ref(true);
const data: SavedData = reactive({
  buttonName: '',
  joinTables: [createEmptyJoinTable()],
});
const showError = ref(false);
const errMessage = ref("");

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

provide('savedData', data);
provide('canSave', (data: boolean) => {
  canSave.value = 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) {
      const newJoinTables = JSON.parse(savedData.joinTablesForConfig);
      data.joinTables.length = 0;
      data.joinTables.push(...newJoinTables);
    }
    data.buttonName = savedData?.buttonName || '集約';
    loading.value = false;
  });
});

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

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

/**
 * 保存データのバリデーション関数
 */
function validate(data: SavedData<string>): boolean {
  // ボタン名が空の場合、エラーを表示
  if (!data.buttonName.trim()) {
    errMessage.value = 'ボタン名を入力してください。';
    return false;
  }

  for (const joinTable of data.joinTables) {
    // 取得元アプリが空の場合、エラーを表示
    if (!joinTable.app.trim()) {
      errMessage.value = '取得元アプリを指定してください。';
      return false;
    }

    // 取得フィールドのマッピングが1つ未満の場合、エラーを表示
    if (
      joinTable.fieldsMapping.length < 1 ||
      !joinTable.fieldsMapping[0].leftField?.trim() ||
      !joinTable.fieldsMapping[0].rightField?.trim()
    ) {
      errMessage.value = '取得フィールドを1つ以上設定してください。';
      return false;
    }
  }

  return true;
}

function save() {
  if(!validate(data)){
    showError.value=true;
    return;
  }
  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);
    if (!meta) return;

    // 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>
