<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 './condition/TableCombobox.vue';
import { getEmptyWhereCondition, getFieldsDropdownItems } from '@/js/helper';
import { conditionList, getComponent, type ConditionValue } from '@/js/conditions';

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, table.value),
        modelValue: '',
        selectedAppData,
        'onUpdate:modelValue': (newValue: string) => {
          const res = getEmptyWhereCondition();
          res.field = newValue;
          props.modelValue[rowIndex] = res;
        },
      });
      render(vnode, container);
      return container;
    },
  },
  {
    title: '',
    field: 'condition',
    render: (cellData: string, rowData: any, rowIndex: number) => {
      const container = document.createElement('div');
      const vnode = h(TableCombobox, {
        items: conditionList,
        modelValue: '',
        selectedAppData,
        'onUpdate:modelValue': (newValue: string) => {
          const field = props.modelValue[rowIndex].field;
          const res = getEmptyWhereCondition();
          res.field = field;
          res.condition = newValue as ConditionValue;
          props.modelValue[rowIndex] = res;
        },
      });
      render(vnode, container);
      return container;
    },
  },
  {
    title: '',
    field: 'data',
    render: (cellData: string, rowData: any, rowIndex: number) => {
      const vueComponent = getComponent(props.modelValue[rowIndex].condition);
      if (!vueComponent) return cellData;
      const container = document.createElement('div');
      const vnode = h(vueComponent, {
        modelValue: '',
        selectedAppData,
        'onUpdate:modelValue': (newValue: string) => {
          props.modelValue[rowIndex].data = newValue;
        },
      });
      render(vnode, container);
      return container;
    },
  },
];
</script>
