<template>
  <kuc-table className='plugin-kuc-table condition-table' 
  :columns="columns" 
  :data="modelValue"
  />
</template>

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

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

const emit = defineEmits<{
  (event: 'update:modelValue', value: WhereCondition[]): void;
}>();

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 canSave = inject<(canSave: boolean) => void>('canSave') as (canSave: boolean) => void;

watch(
  ()=>props.modelValue,
  (newValue,oldValue)=>{
      console.log(newValue);
      console.log(oldValue);
  },{
    deep:true,
    immediate:true
  }
)

const columns = reactive([
  {
    title: '取得元アプリのフィールド',
    field: 'field',
    render: (cellData: string, rowData: WhereCondition) => {
      if (!rowData.id) {
        rowData.id = generateId();
      }
      const container = document.createElement('div');
      const vnode = h(TableCombobox, {
        items: computed(() =>
          getFieldsDropdownItems(selectedAppData.appFields, {
            subTableCode: '', //table.value,
            baseFilter: undefined,
            defaultLabel: 'すべてのレコード',
            needAllSubTableField: true,
          }),
        ),
        modelValue: computed(() => (search(props.modelValue, rowData.id) as WhereCondition)?.field || ''),
        selectedAppData,
        dataList: props.modelValue,
        id: rowData.id,
        'onUpdate:modelValue': (data) => {
          const obj = (data.obj as WhereCondition);
          if (obj) {
            obj.field = data.value;
            obj.condition = '',
            obj.data = '';
          }
        },
      });
      render(vnode, container);
      return container;
    },
  },
  {
    title: '',
    field: 'condition',
    render: (cellData: string, rowData: WhereCondition) => {
      const container = document.createElement('div');
      const vnode = h(TableCondition, {
        modelValue: computed(() => (search(props.modelValue, rowData.id) as WhereCondition)?.condition || ''),
        selectedAppData,
        id: rowData.id,
        whereConditions: props.modelValue,
        'onUpdate:modelValue': ({obj, value}) => {
            obj && (obj.condition = value);
        },
      });
      render(vnode, container);
      return container;
    },
  },
  {
    title: '',
    field: 'data',
    render: (cellData: string, rowData: WhereCondition) => {
      const container = document.createElement('div');
      const vnode = h(TableConditionValue, {
        modelValue: computed(() => (search(props.modelValue, rowData.id) as WhereCondition)?.data || ''),
        selectedAppData,
        canSave,
        id: rowData.id,
        whereConditions: props.modelValue,
        'onUpdate:modelValue': ({obj, value}) => {
            if(obj){
              obj.data = value;
              const newData = props.modelValue.map((item) =>
                  item.id === obj.id ? { ...item, data: value } : item
              );
              emit('update:modelValue', newData);
            }
        },
      });
      render(vnode, container);
      return container;
    },
  },
]);

</script>
