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

<script setup lang="ts">
import type { CachedData, CachedSelectedAppData, SavedData, WhereCondition } from '@/types/model';
import { defineProps, defineEmits, inject, computed, ref, reactive, render, h, watch, onMounted } from 'vue';
import TableCombobox from './TableCombobox.vue';
import { getFieldsDropdownItems } from '@/js/helper';
import type { ConditionValue } from '@/js/conditions';
import TableCondition from './conditions/TableCondition.vue';
import TableConditionValue from './conditions/TableConditionValue.vue';

const props = defineProps<{
  modelValue: WhereCondition[];
}>();

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

const columns = [
  {
    title: '取得元アプリのフィールド',
    field: 'field',
    render: (cellData: string, rowData: any, rowIndex: number) => {
      const container = document.createElement('div');
      const vnode = h(TableCombobox, {
        items: getFieldsDropdownItems(selectedAppData.appFields, {
          subTableCode: table.value,
          defaultLabel: 'すべてのレコード',
        }),
        modelValue: '',
        selectedAppData,
        'onUpdate:modelValue': (newValue: string) => {
          props.modelValue[rowIndex].field = newValue;
          props.modelValue[rowIndex].condition = '';
          props.modelValue[rowIndex].data = '';
        },
      });
      render(vnode, container);
      return container;
    },
  },
  {
    title: '',
    field: 'condition',
    render: (cellData: string, rowData: any, rowIndex: number) => {
      const container = document.createElement('div');
      const vnode = h(TableCondition, {
        modelValue: '',
        index: rowIndex,
        selectedAppData,
        whereConditions: props.modelValue,
        'onUpdate:modelValue': (newValue: string) => {
          props.modelValue[rowIndex].condition = newValue as ConditionValue;
          props.modelValue[rowIndex].data = '';
        },
      });
      render(vnode, container);
      return container;
    },
  },
  {
    title: '',
    field: 'data',
    render: (cellData: string, rowData: any, rowIndex: number) => {
      const container = document.createElement('div');
      const vnode = h(TableConditionValue, {
        modelValue: '',
        index: rowIndex,
        selectedAppData,
        whereConditions: props.modelValue,
        'onUpdate:modelValue': (newValue: string) => {
          props.modelValue[rowIndex].data = newValue;
        },
      });
      render(vnode, container);
      return container;
    },
  },
];
</script>
