<template>
  <kuc-table :class-name.camel="['plugin-kuc-table']" :columns="columns" :data="modelValue" />
</template>

<script setup lang="ts">
import type { CachedData, CachedSelectedAppData, FieldsJoinMapping } from '@/types/model';
import { defineProps, inject, computed, reactive, render, h } from 'vue';
import { getFieldsDropdownItems } from '@/js/helper';
import TableCombobox from './TableCombobox.vue';

const props = defineProps<{
  connector: string;
  modelValue: FieldsJoinMapping[];
}>();

const cachedData = inject<CachedData>('cachedData') as CachedData;
const selectedAppData = inject<CachedSelectedAppData>('selectedAppData') as CachedSelectedAppData;
const table = computed(() => selectedAppData.table.table);

const columns = reactive([
  {
    title: '取得元アプリのフィールド',
    field: 'leftField',
    render: (cellData: string, rowData: any, rowIndex: number) => {
      const container = document.createElement('div');
      const vnode = h(TableCombobox, {
        items: getFieldsDropdownItems(selectedAppData.appFields, { subTableCode: table.value, filterType: undefined }),
        modelValue: '',
        selectedAppData,
        'onUpdate:modelValue': (newValue: string) => {
          props.modelValue[rowIndex].leftField = newValue;
        },
      });
      render(vnode, container);
      return container;
    },
  },
  {
    title: '',
    field: 'connector',
    render: () => {
      return props.connector;
    },
  },
  {
    title: 'このアプリのフィールド',
    field: 'rightField',
    render: (cellData: string, rowData: any, rowIndex: number) => {
      const container = document.createElement('div');
      const vnode = h(TableCombobox, {
        items: getFieldsDropdownItems(cachedData.currentAppFields, { filterType: undefined }),
        modelValue: '',
        selectedAppData,
        'onUpdate:modelValue': (newValue: string) => {
          props.modelValue[rowIndex].rightField = newValue;
        },
      });
      render(vnode, container);
      return container;
    },
  },
]);
</script>
