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

@Component({
  components: {
    QOptionGroup,
    WidgetWrapper,
  },
})
export default class Relation extends mixins(ValidatedField, FormWidget) {
  $refs!: {
    widget: WidgetWrapper;
  };

  relation = null;

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

    this.relation = value?.__id?.code;
  }

  @Watch('relation')
  onRelationChange(relation: number): void {
    const option = this.options.find((it) => it.value === relation);

    this.$set(this.model, 'pRelation', relation);
    this.$refs.widget.pushModelHistory(this.model, { name: 'pRelation' });
    this.$refs.widget.inputEvents?.input(option?.data);
  }

  get options() {
    return [
      {
        label: 'Супруг(а)',
        value: 1,
        data: {
          code: 1,
          content: 'Супруг(а)',
        },
      },
      {
        label: 'Несовершеннолетний ребенок',
        value: 2,
        data: {
          code: 2,
          content: 'Несовершеннолетний ребенок',
        },
      },
    ];
  }
}
