import type { PropType } from 'vue';
import { defineComponent, ref, computed, toRef, reactive, watch } from 'vue'
import type { IColGridTable, IDimensioni } from 'model';
import { IOperators, ISize } from 'model'

import { useI18n } from 'vue-i18n'
import { useQuasar } from 'quasar'

import { CMySize } from '@src/components/CMySize'
import { CBorders } from '@src/components/CBorders'
import { CMyFieldRec } from '@src/components/CMyFieldRec'

import { tools } from '@tools'

import { costanti } from '@costanti'

import { shared_consts } from '@src/common/shared_vuejs'

export default defineComponent({
  name: 'CMyDimensioni',
  emits: ['update:modelValue', 'modifElem'],
  components: { CMySize, CBorders, CMyFieldRec },
  props: {
    modelValue: {
      type: Object as PropType<IDimensioni>,
      required: true,
    },
    label: {
      type: String,
      required: false,
      default: ''
    },
    path: {
      type: String,
      required: false,
      default: ''
    },
    show_imgsfondo: {
      type: Boolean,
      required: false,
      default: false,
    },
    showDim: {
      type: Boolean,
      required: false,
      default: true,
    },
    disable: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  setup(props, { emit }) {
    const $q = useQuasar()
    const { t } = useI18n()

    const internalModel = reactive({ ...props.modelValue })

    // Sincronizzare i cambiamenti esterni con internalModel quando props cambiano
    watch(() => [props.modelValue], (newModel: any) => {
      Object.assign(internalModel, newModel);
      // console.log('Internal Model updated:', newModel);
    }, { immediate: true });

    function modifSize(value: any) {
      emit('update:modelValue', { ...internalModel, size: value });
    }
    function modifElem() {
      emit('update:modelValue', { ...internalModel });
      emit('modifElem', null);
    }
    function modifMargini(value: any) {
      emit('update:modelValue', { ...internalModel, margini: value });
    }
    function modifPadding(value: any) {
      emit('update:modelValue', { ...internalModel, padding: value });
    }

    function saveFielDim(rec: any, newval: any, col: IColGridTable) {
      // console.log('saveFielDim', rec, 'newval', newval, 'col', col)

      if (col.fieldtype === costanti.FieldType.image) {

        if (!rec[col.name]) {
          rec[col.name] = {}
        }
        rec[col.name] = newval.imagefile

        console.log('rec[col.name]', rec[col.name])
        // rec[col.name].imagefile = newval.imagefile
      }
    }

    return {
      t,
      tools,
      shared_consts,
      internalModel,
      modifSize,
      modifMargini,
      modifPadding,
      saveFielDim,
      modifElem,
      costanti,
    }
  }
})
