<template>
  <widget-wrapper
    v-bind="$props"
    v-slot="{ inputEvents }"
    class="enum-select-wrapper"
  >
    <q-card flat class="selectpicker-container">
      <div class="selectpicker-wrapper">
        <q-select
          outlined
          :filled="isReadonly"
          :label="noLabels ? undefined : fieldNode.label"
          :color="color"
          :value="valueId"
          :placeholder="placeholderText"
          labelLines="3"
          :display-value="selectedTitle"
          :error="hasError"
          :error-message="errorMessage"
          ref="selectbox"
          :options="options"
          @input="changeHandler($event, inputEvents)"
          :clearable="!isLoading && valueId !== ''"
          :readonly="isReadonly"
          :loading="isLoading"
        >
          <template v-slot:no-option>
            <q-item>
              <q-item-section class="text-grey">
                Нет подходящих вариантов
              </q-item-section>
            </q-item>
          </template>
        </q-select>
      </div>
    </q-card>
  </widget-wrapper>
</template>

<script lang="ts">
// @ts-nocheck
import { Component } from 'vue-property-decorator';
import { mixins } from 'vue-class-component';
import {
  ValidatedField,
  FormWidget,
  WidgetWrapper,
} from '@devsun/form-generator/dist';

@Component({
  components: {
    WidgetWrapper,
  },
})
export default class DropdownEnumSelect extends mixins(
  FormWidget,
  ValidatedField
) {
  private defaultTitle: string = 'Нет значения';

  get valueId(): string {
    return this.value && (this.value.__id as string);
  }

  get isReadonly(): boolean {
    return this.fieldNode.readonly;
  }

  get isLoading(): boolean {
    return false;
  }

  get fieldClasses() {
    return {
      editable: !this.fieldNode.readonly,
      'label-uppercase': false,
      'dropdown-toggle': this.toggleNeeded,
    };
  }

  get selectedTitle() {
    const enumVar = this.fieldNode.enum;
    const selected = enumVar
      ? enumVar.find((e) => e.key === this.valueId)
      : null;
    return (selected && selected.value) || this.defaultTitle;
  }

  get options() {
    const enumVar = this.fieldNode && this.fieldNode.enum;
    if (enumVar) {
      return [
        ...enumVar.map((item) => {
          return {
            value: item.key,
            label: item.value,
          };
        }),
      ];
    }

    console.error(
      'empty options for enum dropdown',
      this.fieldNode.name,
      this.value,
      this.fieldNode
    );

    return [];
  }

  changeHandler(value, inputEvents) {
    inputEvents.input(value.value);
  }
}
</script>
