<template>
  <q-input
    :ref="col.name + 'Input'"
    v-model="rowData.row[col.name]"
    :align="col.type"
    :class="col.type === 'number' || col.type === 'decimal' ? 'tableBody__input-number' : ''"
    :type="col.type === 'number' || col.type === 'decimal' ? 'number' : 'text'"
    :test-id="col.name + 'Input'"
    dense
    filled
    square
    :step="col.type === 'decimal' ? '0.1' : '1'"
    debounce="500"
    :rules="col.rules"
    hide-bottom-space
    :readonly="col.isFieldEditableByRules ?? false ? col.isFieldEditableByRules(rowData.row) : false"
    style="min-width: 15ch"
    @update:model-value="(value) => {
      if (col.type === 'number') {
        emitUpdateTableValue(value, '', rowData.row, col)
      }
      else {
        if (col.validation === undefined || col.validation(rowData.row[col.name])) {
          emit('updateTableValue', {
            value,
            initialValue: '',
            row: rowData.row,
            col,
          })
        }
      }
    }"
  >
    <q-tooltip

      v-if="col.isFieldEditableByRules ?? false ? col.isFieldEditableByRules(rowData.row) : false"
      max-width="400px"
    >
      {{ col.notEditableMessage ?? $t('notEditable') }}
    </q-tooltip>
  </q-input>
</template>

<script setup lang="ts">
import { debounce } from 'quasar'

const rowData = defineModel('rowData', { type: Object, required: true })
const emit = defineEmits(['updateTableValue'])
const { col } = defineProps<{ col: any }>()

const emitUpdateTableValue = debounce((value, initialValue, row, col) => {
  if (col.validation === undefined || col.validation(rowData.value.row[col.name])) {
    emit('updateTableValue', {
      value,
      initialValue,
      row,
      col
    })
  }
}, 500)

</script>
