import { Component, Prop, Watch } from 'vue-property-decorator';
import { QOptionGroup } from 'quasar';
import {
  ValidatedField,
  FormWidget,
  WidgetWrapper,
} from '@devsun/form-generator/dist';
import { mixins } from 'vue-class-component';
import { QSelectOption } from '@/models/models-ui';
import isEqual from 'lodash/isEqual';

@Component({
  components: {
    QOptionGroup,
    WidgetWrapper,
  },
})
export default class Citizenship extends mixins(ValidatedField, FormWidget) {
  @Prop({
    default: 'dataObject',
    validator: (value: any): boolean =>
      ['dataObject', 'value', 'label'].includes(value),
  })
  outputMode: string;

  $refs!: {
    widget: WidgetWrapper;
  };

  citizenship = null;

  @Watch('value', { deep: true })
  onValueChange(value, prevValue) {
    if (isEqual(value, prevValue)) return;

    if (this.outputMode === 'dataObject') this.citizenship = value?.__id?.code;
    if (this.outputMode === 'value')
      this.citizenship = value?.__id?.code || value?.__id;
    if (this.outputMode === 'label')
      this.citizenship = value?.__id?.content || value?.__id;
  }

  @Watch('citizenship')
  onCitizenshipChange(citizenship): void {
    const option = this.options.find((it) => {
      if (this.outputMode === 'label') return it.label === citizenship;
      return it.value === citizenship;
    });

    if (this.outputMode === 'dataObject')
      this.$refs.widget.inputEvents?.input(option?.data);
    if (this.outputMode === 'value')
      this.$refs.widget.inputEvents?.input(option?.data.code);
    if (this.outputMode === 'label')
      this.$refs.widget.inputEvents?.input(option?.data.content);
  }

  mounted() {
    this.onValueChange(this.value, null);
  }

  get options(): QSelectOption[] {
    return [
      {
        label: 'Россия',
        value: 643,
        data: {
          code: 643,
          content: 'Россия',
        },
      },
    ];
  }
}
