<template>
  <plugin-row class="table-area flex-row border">
    <div class="table-main-area">
      <plugin-row>
        <plugin-dropdown :disabled="false" label="取得元アプリ" :items="apps" v-model="table.app" @change="selectApp" />
      </plugin-row>
      <plugin-row>
        <plugin-dropdown
          :disabled="selectedAppData.loading"
          label="テーブル"
          :items="tableOptions"
          v-model="table.table"
          @change="selectTable"
        />
      </plugin-row>
      <plugin-row class="flex-row" v-if="isJoinConditionShown(table)">
        <plugin-label label="連結条件" />
        <plugin-table-connect-row connector="=" v-model="table.onConditions" />
      </plugin-row>
      <plugin-row class="flex-row">
        <plugin-label label="取得フィールド" />
        <plugin-table-connect-row connector="→" v-model="table.fieldsMapping" />
      </plugin-row>
      <plugin-row class="flex-row">
        <plugin-label label="絞込条件" />
        <plugin-table-condition-row v-model="table.whereConditions" />
      </plugin-row>
    </div>
    <div class="table-action-area">
      <plugin-table-action-icon-group :can-delete="savedData.joinTables.length > 1" :table-id="table.id" />
    </div>
  </plugin-row>
</template>

<script setup lang="ts">
import {
  EMPTY_OPTION,
  getTableFieldsDropdownItems,
  loadAppFieldsAndLayout,
  resetConditions,
  resetTable,
} from '@/js/helper';
import { types } from '@/js/kintone-rest-api-client';
import type { CachedData, CachedSelectedAppData, FieldsInfo, JoinTable, SavedData } from '@/types/model';
import type { KucEvent } from '@/types/my-kintone';
import { computed, inject, provide, reactive, ref, watch } from 'vue';

const savedData = inject<SavedData>('savedData') as SavedData;
const cachedData = inject<CachedData>('cachedData') as CachedData;

const props = defineProps<{ table: JoinTable }>();
const apps = computed(() => cachedData.apps);
const tableOptions = ref([EMPTY_OPTION]);
const loading = ref(true);

const selectedAppData: CachedSelectedAppData = reactive({
  appFields: { fields: {}, layout: [] } as FieldsInfo,
  table: props.table,
  loading: false,
});
provide('selectedAppData', selectedAppData);

const selectApp = async (e: KucEvent) => {
  loading.value = true;
  const fields = await loadAppFieldsAndLayout(e.detail.value);
  tableOptions.value = getTableFieldsDropdownItems(fields, types.SUBTABLE);
  resetTable(props.table);
  selectedAppData.appFields = fields;
  loading.value = false;
};

const selectTable = (e: KucEvent) => {
  resetConditions(props.table);
};

watch(
  () => !props.table.app || loading.value,
  (val) => {
    selectedAppData.loading = val;
  },
);

const isJoinConditionShown = (table: JoinTable) => {
  return savedData.joinTables[0].id !== table.id;
};
</script>
