<template>
  <t-form-item
    :label="isBigTitle ? '' : config.title"
    :name="config.formName"
    class="my-form-item"
  >
    <component
      :is="tabComp"
      v-model="valueData"
      :config="config"
      @change="emitChange"
      :sop="sop"
    ></component>
  </t-form-item>
</template>

<script setup name="DynamicFormItem">
import { computed, ref, watch } from 'vue';
import TEXT from './TEXT.vue';
import SELECT from './SELECT.vue';
import DATE from './DATE';
import TABLE from './table/index.vue';
import RADIO from './RADIO.vue';
import CHECKBOX from './CHECKBOX.vue';
import TEXTAREA from './TEXTAREA.vue';
import UPLOADIMAGE from './UPLOAD_IMAGE.vue';
import RADIOWITHINPUT from './RADIO_WITH_INPUT.vue';
import NUMBER from './NUMBER.vue';
import BIGTITLE from './BIG_TITLE.vue';
import SIGN from './SIGN.vue';
import DEVICEOUTTABLE from './device-table/index.vue';
import DEVICEINTABLE from './device-table/device-in-table.vue';
import LABEL from './LABEL.vue';

const props = defineProps({
  config: { type: Object },
  sop: {
    type: Object,
    default() {
      return {};
    },
  },
});
const emit = defineEmits(['change']);

const valueData = ref(null);

const bigTitles = ['FORM_GROUP_TITLE', 'ONLY_TITLE', 'LABEL'];
const isBigTitle = computed(() => {
  return bigTitles.includes(props.config.code);
});

const tabComps = {
  SIGN: SIGN,
  TEXT: TEXT,
  NUMBER: NUMBER,
  POP_SELECT: SELECT,
  SINGLE_SELECT: SELECT,
  MULTIPLE_SELECT: SELECT,
  DATE: DATE,
  TABLE: TABLE,
  RADIO: RADIO,
  CHECKBOX: CHECKBOX,
  TEXTAREA: TEXTAREA,
  FILE: UPLOADIMAGE,
  RADIO_WITH_INPUT: RADIOWITHINPUT,
  DEVICE_OUT_TABLE: DEVICEOUTTABLE,
  DEVICE_IN_TABLE: DEVICEINTABLE,
  FORM_GROUP_TITLE: BIGTITLE,
  ONLY_TITLE: BIGTITLE,
  LABEL: LABEL,
};
const tabComp = computed(() => {
  return tabComps[props.config.code];
});

const emitChange = () => {
  emit('change', {
    prop: props.config.formName,
    value: valueData.value,
  });
};

watch(
  () => props.config.value,
  (val, oldval) => {
    if (val === oldval) return;
    valueData.value = val;
  },
  {
    immediate: true,
  }
);
</script>
