<template>

<fieldset class="q-mb-lg q-pt-sm">
    <legend v-if="formTitle && formTitle.trim()" class="q-px-sm">{{ formTitle }}</legend>
    <form @submit.prevent="startSearch">
      <div class="row q-col-gutter-sm">
        <div class="col-12 col-sm-6">
          <q-input ref="innInputRef" v-model="searchCriteria.inn" label="ИНН организации" mask="##########" :rules="[val => isValidInn(val)]" lazy-rules filled dense bottom-slots @input="searchCriteriaEdited" />
        </div>
        <div class="col-12 col-sm-6">
          <q-input ref="ogrnInputRef" v-model="searchCriteria.ogrn" label="ОГРН организации" mask="#############" :rules="[val => isValidOgrn(val)]" lazy-rules filled dense bottom-slots @input="searchCriteriaEdited" />
        </div>
      </div>
      <div class="row justify-end">
        <div v-if="showIncompleteSearchCriteriaError" class="col-grow q-pl-sm">
          <span class="text-negative text-caption">Введите ИНН или ОГРН организации</span>
        </div>
        <div class="col-shrink">
          <q-btn type="submit" color="primary" label="Поиск" icon="search" :loading="searching"></q-btn>
        </div>
      </div>
    </form>
  </fieldset>
</template>

<script lang="ts">
import { Component, Prop } from 'vue-property-decorator';

@Component({})
export default class ULSearchForm {

  isCriteriaEdited = true;

  searchCriteriaEdited() {
      this.isCriteriaEdited = true;
  }

  @Prop() searching: boolean;
  @Prop() formTitle: string;

  searchCriteria = {
    inn: '',
    ogrn: '',
  };

  isValidInn(val) {
    if (val.trim()) {
      if (val.match(/^[\d]{10}$/))
        return true;
      else
        return 'Некорректный ИНН';
    }
    return true; // поле не обязательное
  }

  isValidOgrn(val) {
    if (val.trim()) {
      if (val.match(/^[15]{1}[\d]{12}$/))
        return true;
      else
        return 'Некорректный ОГРН';
    }
    return true; // поле не обязательное
  }

  get showIncompleteSearchCriteriaError() {
    return (!this.isCriteriaEdited && !this.searchCriteria.inn && !this.searchCriteria.ogrn);
  }

  startSearch() {
    this.isCriteriaEdited = false;
    if (this.searchCriteria.inn || this.searchCriteria.ogrn) {
      const innInput = this.$refs.innInputRef;
      const ogrnInput = this.$refs.ogrnInputRef;
      innInput.validate();
      ogrnInput.validate();
      if (!innInput.hasError && !ogrnInput.hasError) {
        this.$emit('search', this.searchCriteria);
      }
    }
  }
}

</script>