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

@Component({
  components: {
    WidgetWrapper,
  },
})
export default class MappedDictionary extends mixins(
  ValidatedField,
  FormWidget
) {
  @Prop({ default: '' }) dictionaryId: string;
  @Prop({ default: () => ({ label: 'name', value: 'type' }) }) mapFields: {
    [key: string]: string;
  };

  $refs!: {
    widget: WidgetWrapper;
  };

  dictionary: any[] | null = null;
  dictModel: any = '';

  get label(): string {
    return this.fieldNode?.rawAttrs?.label || '';
  }

  get isClearModalOpen(): boolean {
    return this.$store.getters['formGenerator/isClearModalOpen'];
  }

  get disable(): boolean {
    return this.isClearModalOpen;
  }

  async created(): Promise<void> {
    this.dictionary = await this.getReferenceBook(this.dictionaryId);
    const val = get(this.value, 'content.content');
    if (val) {
      this.dictModel = val;
    } else {
      this.setDefault();
    }
  }

  setDefault(): void {
    if (this.fieldNode.rawAttrs?.props?.setDefault) {
      this.dictModel = this.dictionary[
        this.fieldNode.rawAttrs.props.setDefault
      ].value;
    }
  }

  @Watch('model')
  clearSelect(model: any) {
    if (!get(model, this.$refs.widget.baseField.name) && this.dictModel) {
      this.dictModel = '';
      if (this.dictionary) {
        this.setDefault();
      }
    }
  }

  @Watch('dictModel', { deep: true }) //deep не удалять. нужен, чтобы сработал watch после добавления.
  onDictModelChange(newValue: any) {
    const option: any =
      this.options.find(
        (opt) => opt.value === newValue || opt.label === newValue
      ) || {};
    this.$refs.widget.inputEvents?.input({
      ...option?.data,
    });
    this.$refs.widget.updateHistory.push(
      `${this.fieldNode.fieldName}.${this.mapFields.code}`
    );
  }

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

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

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

    return Object.entries(this.dictionary).map(([key, valueWrapper]) => ({
      value: key,
      label: valueWrapper.value,
      data: Object.fromEntries(
        Object.entries(this.mapFields).map(([mapKey, target]) => {
          return [target, mapKey === 'code' ? key : valueWrapper[mapKey]];
        })
      ),
    }));
  }

  filteredOptions: QSelectOption[] = [];

  filterItems(query: string, done: Function) {
    if (query === '') {
      done(() => {
        this.filteredOptions = this.options;
      });
      return;
    }

    done(() => {
      const needle = query.toLowerCase();
      this.filteredOptions = this.options.filter(
        (v) => v.label.toLowerCase().indexOf(needle) > -1
      );
    });
  }

  onPopupShow() {
    this.$store.commit('formGenerator/setClearModal', true);
  }
}
