<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.ogrnip" label="ОГРНИП" mask="###############" :rules="[val => isValidOgrnIP(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 IPSearchForm {
  
    isCriteriaEdited = true;
  
    searchCriteriaEdited() {
        this.isCriteriaEdited = true;
    }
  
    @Prop() searching: boolean;
    @Prop() formTitle: string;
  
    searchCriteria = {
      inn: '',
      ogrnip: '',
    };
  
    isValidInn(val) {
      if (val.trim()) {
        if (val.match(/^[\d]{12}$/))
          return true;
        else
          return 'Некорректный ИНН';
      }
      return true; // поле не обязательное
    }
  
    isValidOgrnIP(val) {
      if (val.trim()) {
        if (val.match(/^3[\d]{14}$/))
          return true;
        else
          return 'Некорректный ОГРНИП';
      }
      return true; // поле не обязательное
    }
  
    get showIncompleteSearchCriteriaError() {
      return (!this.isCriteriaEdited && !this.searchCriteria.inn && !this.searchCriteria.ogrnip);
    }
  
    startSearch() {
      this.isCriteriaEdited = false;
      if (this.searchCriteria.inn || this.searchCriteria.ogrnip) {
        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>