import { Component, Prop, 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 { QSelectOption } from '@/models/models-ui';
import isEqual from 'lodash/isEqual';

@Component({
  components: {
    QOptionGroup,
    WidgetWrapper,
  },
})
export default class IncomeType extends mixins(ValidatedField, FormWidget) {
  @Prop({ default: 'familychildsub_manual_income_type' }) dictionary: string;
  @Prop({
    default: () => {
      return [];
    },
  })
  blackListCodes: string[];

  $refs!: {
    widget: WidgetWrapper;
  };

  incomeTypeDict: any[] | null = null;

  incomeType: any | null = null;

  async created(): Promise<void> {
    this.incomeTypeDict = await this.getReferenceBook(this.dictionary);
  }

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

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

  @Watch('incomeType')
  onIncomeTypeChange(incomeType: any): void {
    const option = this.options.find((it) => it.value === incomeType);

    this.$refs.widget.inputEvents.input(option?.data);
  }

  async getReferenceBook(name: string) {
    const config = {
      id: name,
      limit: 200,
    };

    return this.$store.dispatch(
      'registryService/referenceBooks/fetchReferenceBook',
      config
    );
  }

  get options(): QSelectOption[] {
    if (!this.incomeTypeDict) return [];

    return Object.entries(this.incomeTypeDict)
      .map(([key, valueWrapper]) => ({
        value: key,
        label: (valueWrapper as { value: string }).value,
        data: {
          code: key,
          content: (valueWrapper as { value: string }).value,
        },
      }))
      .filter(({ value: itemCode }) => {
        return !this.blackListCodes.find(
          (blackListCode) => itemCode === blackListCode
        );
      });
  }
}
