<template>
  <fieldset class="q-mb-lg q-mx-none q-pt-sm " style="border-width: 1px;">
    <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 col-md-4">
          <q-input ref="familyNameInputRef" v-model="searchCriteria.familyName" label="Фамилия" :rules="[val => !!val.trim() || 'Введите фамилию']" filled dense bottom-slots @input="searchCriteriaEdited" />
        </div>
        <div class="col-12 col-sm-6 col-md-4">
          <q-input v-model="searchCriteria.firstName" label="Имя" filled dense bottom-slots @input="searchCriteriaEdited" />
        </div>
        <div class="col-12 col-sm-6 col-md-4">
          <q-input v-model="searchCriteria.patronymic" label="Отчество" filled dense bottom-slots @input="searchCriteriaEdited" />
        </div>
        <div class="col-12 col-sm-6 col-md-4">
          <q-input ref="dateInputRef" v-model="searchCriteria.birthDate" label="Дата рождения" mask="##.##.####" :rules="[val => isValidDate(val) || 'Введите дату в формате ДД.ММ.ГГГГ']" lazy-rules filled dense @input="searchCriteriaEdited"  />
        </div>
        <div class="col-12 col-md-4 col-sm-6">
          <q-input ref="innInputRef" v-model="searchCriteria.inn" label="ИНН" mask="############" :rules="[val => isValidNumber(val, 12)]" lazy-rules filled dense bottom-slots @input="searchCriteriaEdited" />
        </div>
        <div class="col-12 col-md-4 col-sm-6">
          <q-input ref="snilsInputRef" v-model="searchCriteria.snils" label="СНИЛС" mask="###-###-### ##" :rules="[val =>  isValidNumber(val, 11)]" lazy-rules filled dense bottom-slots @input="searchCriteriaEdited" />
        </div>
        <div class="col-12 q-pt-none q-mb-sm">
          <fieldset class="q-pb-xs q-mx-none q-px-sm" style="border-color: #fff;">
            <legend class="q-px-sm">Паспорт</legend>
            <div class="row q-col-gutter-sm">
              <div class="col-5">
                <q-input ref="docSeriesInputRef" v-model="searchCriteria.docSeries" label="Серия" mask="####" :rules="[val => isValidDocSeries(val)]" lazy-rules filled dense bottom-slots @input="val => docInput(val, 'docNumberInputRef')" />
              </div>
              <div class="col-7">
                <q-input ref="docNumberInputRef" v-model="searchCriteria.docNumber" label="Номер" mask="######" :rules="[val => isValidDocNumber(val)]" lazy-rules filled dense bottom-slots @input="val => docInput(val, 'docSeriesInputRef')" />
              </div>
            </div>
          </fieldset>
        </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';
import { omitBy, isEmpty } from 'lodash';
import moment from 'moment';
import { toMoment } from './extract-mappings';

@Component({})
export default class FLSearchForm {
  @Prop() searching: boolean;
  @Prop() formTitle: string;

  searchCriteria = {
    familyName: '',
    firstName: '',
    patronymic: '',
    birthDate: '',
    inn: '',
    snils: '',
    ogrn: '',
    docType: '',
    docSeries: '',
    docNumber: '',
  };

  isCriteriaEdited = false;

  searchCriteriaEdited() {
    this.isCriteriaEdited = true;
  }

  collectSearchCriteria() {
    const birthday = toMoment(this.searchCriteria.birthDate);
    return {
      searchData: omitBy({
        birthday: (birthday.isValid()) ? birthday.format('YYYY-MM-DD') : '',
        fullName: [this.searchCriteria.familyName, this.searchCriteria.firstName, this.searchCriteria.patronymic].filter(n => n).join(' '),
        snils: this.stripNumbers(this.searchCriteria.snils),
        inn: this.stripNumbers(this.searchCriteria.inn),
        documentType: (this.searchCriteria.docSeries || this.searchCriteria.docNumber) ? "PasportRF" : '',
        series: this.searchCriteria.docSeries,
        number: this.searchCriteria.docNumber,
      }, isEmpty)
    }
  }

  get showIncompleteSearchCriteriaError() {
    let showMessage = false;
    if (this.searchCriteria.familyName && !this.isCriteriaEdited) {
      if (!this.searchCriteria.birthDate && !this.searchCriteria.inn && !this.searchCriteria.snils && !this.searchCriteria.docSeries && !this.searchCriteria.docNumber) {
        showMessage = true;
      }
    }
    return showMessage;
  }

  isValidDate(val) {
    if (val) {
      const dateVal = toMoment(val);
      return dateVal.isValid() && dateVal.isBetween('1870-01-01', moment());
    }
    return true; // Поле не обязательное
  }

  isValidNumber(val, length, errorMessage = '') {
    if (val) {
      val = this.stripNumbers(val);
      return val.length === length || (errorMessage || `Введите ${length} цифр`);
    }
    return true; // Само по себе поле не обязательное
  }

  docInput(val, dependencyRef) {
    this.searchCriteriaEdited();
    if (!val) {
      const dependantInput = this.$refs[dependencyRef];
      if (dependantInput.hasError) {
        dependantInput.validate();
      }
    }
  }

  isValidDocSeries(val) {
    if (val || this.searchCriteria.docNumber) {
      return val.length === 4 || 'Введите 4 цифры';
    }
    return true;
  }

  isValidDocNumber(val) {
    if (val || this.searchCriteria.docSeries) {
      return val.length === 6 || 'Введите 6 цифр';
    }
    return true;
  }

  startSearch() {
    //this.$emit('search', this.collectSearchCriteria()); return;

    this.isCriteriaEdited = false;
    const familyNameInput = this.$refs.familyNameInputRef;
    const dateInput = this.$refs.dateInputRef;
    const innInput = this.$refs.innInputRef;
    const snilsInput = this.$refs.snilsInputRef;
    const docSeriesInput = this.$refs.docSeriesInputRef;
    const docNumberInput = this.$refs.docNumberInputRef;

    familyNameInput.validate();
    if (!familyNameInput.hasError) {
      if (this.searchCriteria.birthDate || this.searchCriteria.inn || this.searchCriteria.snils || this.searchCriteria.docSeries || this.searchCriteria.docNumber) {
        dateInput.validate();
        innInput.validate();
        snilsInput.validate();
        docSeriesInput.validate();
        docNumberInput.validate();
        if (!dateInput.hasError && !innInput.hasError && !snilsInput.hasError && !docSeriesInput.hasError && !docNumberInput.hasError) {
          let searchCriteria = this.collectSearchCriteria();
          this.$emit('search', searchCriteria);
        }
      }
    }
  }

  stripNumbers(numberString) {
      return numberString?.replace(/[^0-9]/g, '');
  }
}

</script>
