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 Subsidies extends mixins(ValidatedField, FormWidget) {
  $refs!: {
    widget: WidgetWrapper;
  };

  subsidies = null;

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

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

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

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

  created() {
    const code = this.value?.__id?.code;
    if (code) {
      this.subsidies = code;
    }
  }

  get options() {
    return [
      {
        label: 'Через кредитную организацию',
        value: 1,
        data: {
          code: 1,
          content: 'Через кредитную организацию',
        },
      },
      {
        label: 'Через почтовое отделение',
        value: 2,
        data: {
          code: 2,
          content: 'Через почтовое отделение',
        },
      },
    ];
  }
}
