<template>
  <div v-bind="$attrs">
    <q-field v-model="selectedField" :label="displayName" labelColor="primary" :clearable="isSelected" stack-label
      :bottom-slots="!isSelected">
      <template v-slot:control>
        <q-chip color="primary" text-color="white" v-if="isSelected">
          {{ selectedField.name }}
        </q-chip>
      </template>
      <template v-slot:hint v-if="!isSelected">
        {{ placeholder }}
      </template>

      <template v-slot:append>
        <q-icon name="search" class="cursor-pointer" color="primary" @click="showDg" />
      </template>
    </q-field>
    <show-dialog v-model:visible="show" name="フィールド一覧" @close="closeDg" widht="400px">
      <field-select ref="appDg" name="フィールド" :type="selectType" :appId="store.appInfo?.appId" :fieldTypes="fieldTypes"></field-select>
    </show-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watchEffect, computed } from 'vue';
import ShowDialog from '../ShowDialog.vue';
import FieldSelect from '../FieldSelect.vue';
import { useFlowEditorStore } from 'stores/flowEditor';
interface IField {
  name: string,
  code: string,
  type: string
}
export default defineComponent({
  name: 'FieldInput',
  inheritAttrs:false,
  components: {
    ShowDialog,
    FieldSelect,
  },
  props: {
    displayName: {
      type: String,
      default: '',
    },
    name: {
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '',
    },
    selectType:{
        type:String,
        default:'single'
    },
    fieldTypes:{
      type:Array,
      default:()=>[]
    },
    hint: {
      type: String,
      default: '',
    },
    modelValue: {
      type: Object,
      default: null
    },
  },

  setup(props, { emit }) {
    const appDg = ref();
    const show = ref(false);
    const selectedField = ref(props.modelValue);
    const store = useFlowEditorStore();
    const isSelected = computed(() => {
      return selectedField.value !== null && typeof selectedField.value === 'object' && ('name' in selectedField.value)
    });

    const showDg = () => {
      show.value = true;
    };

    const closeDg = (val: string) => {
      if (val == 'OK') {
        selectedField.value = appDg.value.selected[0];
      }
    };

    watchEffect(() => {
      emit('update:modelValue', selectedField.value);
    });

    return {
      store,
      appDg,
      show,
      showDg,
      closeDg,
      selectedField,
      isSelected
    };
  }
});
</script>
