<i18n>
{
  "en": {
    "EmployeesSearchForm": {
      "searchNotUsed": "Search not used",
      "searchBy": "Search by",
      "lastName": "Last name",
      "firstName": "First name",
      "middleName": "Middle name",
      "birthDate": "Birth date",
      "search": "Search",
      "employees": "Employees",
      "choose": "Choose",
      "create": "Create new",
      "noDataLabel": "The search returned no results, change the search parameters or create a new person.",
      "snils": "SNILS"
    }
  },
  "ru": {
    "EmployeesSearchForm": {
      "searchNotUsed": "Поиск не использовался",
      "searchBy": "Поиск по",
      "lastName": "Фамилия",
      "firstName": "Имя",
      "middleName": "Отчество",
      "birthDate": "Дата рождения",
      "search": "Поиск",
      "employees": "Сотрудники",
      "choose": "Выбрать",
      "create": "Создать нового",
      "noDataLabel": "Поиск не дал результатов, поменяйте параметры поиска или создайте новую персону.",
      "snils": "СНИЛС"
    }
  }
}
</i18n>

<template>
  <q-form class="q-gutter-y-md" @submit="submit">
    <div v-if="readonly" class="q-gutter-y-sm">
      <div v-if="!!searchData" class="row">
        <div class="col text-grey-5">
          {{ $t('EmployeesSearchForm.searchBy') }}
        </div>
        <div class="col text-grey-7">{{ searchData }}</div>
      </div>
      <p v-else class="text-grey-7">
        {{ $t('EmployeesSearchForm.searchNotUsed') }}
      </p>
    </div>
    <div v-else class="q-gutter-y-md">
      <div class="row q-gutter-y-md">
        <div class="col-12">
          <q-input
            v-model="surname"
            filled
            :label="$t('EmployeesSearchForm.lastName') + '*'"
          />
        </div>
        <div class="col-12">
          <q-input
            v-model="firstname"
            filled
            :label="$t('EmployeesSearchForm.firstName') + '*'"
          />
        </div>
        <div class="col-12">
          <q-input
            v-model="middlename"
            filled
            :label="$t('EmployeesSearchForm.middleName')"
          />
        </div>
        <div class="col-xs-12 col-sm-8">
          <q-input
            v-model="birthdate"
            :label="$t('EmployeesSearchForm.birthDate') + '*'"
            filled
            :mask="inputMask"
          >
            <template #append>
              <q-icon name="event" class="cursor-pointer">
                <q-popup-proxy
                  ref="qDateProxy"
                  transition-show="scale"
                  transition-hide="scale"
                >
                  <q-date
                    v-model="birthdate"
                    :mask="dateMask"
                    @input="() => $refs.qDateProxy.hide()"
                  />
                </q-popup-proxy>
              </q-icon>
            </template>
          </q-input>
        </div>
        <div class="col-12">
          <q-input
            v-model="snils"
            filled
            :label="$t('EmployeesSearchForm.snils')"
          />
        </div>
      </div>
      <div class="q-mt-lg">
        <q-btn
          :disable="
            !birthdate && !middlename && !firstname && !surname && !snils
          "
          :label="$t('EmployeesSearchForm.search')"
          color="primary"
          type="button"
          @click="searchPerson"
        />
      </div>
      <q-table
        v-if="this.inputData && this.inputData.searchResult"
        :title="$t('EmployeesSearchForm.employees')"
        :data="data"
        :columns="columns"
        row-key="id"
        selection="single"
        :selected.sync="selected"
        :no-data-label="$t('EmployeesSearchForm.noDataLabel')"
        :grid="$q.screen.xs"
      >
        <template #item="props">
          <div
            class="q-pa-xs col-xs-12 col-sm-6 col-md-4 col-lg-3 grid-style-transition"
            :style="props.selected ? 'transform: scale(0.95);' : ''"
          >
            <q-card :class="props.selected ? 'bg-grey-2' : ''">
              <q-card-section>
                <q-checkbox
                  v-model="props.selected"
                  dense
                  :label="props.row.name"
                />
              </q-card-section>
              <q-separator />
              <div class="q-table__grid-item-card">
                <div
                  v-for="col in props.cols"
                  :key="col.name"
                  class="q-table__grid-item-row"
                >
                  <div class="q-table__grid-item-title">
                    {{ col.label }}
                  </div>
                  <div class="q-table__grid-item-value">
                    {{ col.value }}
                  </div>
                </div>
              </div>
            </q-card>
          </div>
        </template>
      </q-table>
      <div
        v-if="
          this.inputData &&
          !!this.inputData.formData &&
          !!this.inputData.formData.transSearch &&
          (!this.inputData.searchResult ||
            this.inputData.searchResult.length === 0)
        "
      >
        {{ $t('EmployeesSearchForm.noDataLabel') }}
      </div>
      <q-btn
        v-if="selected.length"
        class="q-mr-md"
        color="primary"
        :label="$t('EmployeesSearchForm.choose')"
        type="button"
        @click="choosePerson"
      />
      <q-btn
        color="primary"
        :label="$t('EmployeesSearchForm.create')"
        type="button"
        @click="createPerson"
      />
    </div>
  </q-form>
</template>

<script lang="ts">
// @ts-nocheck
import {
  convertDateFormat,
  convertDateFromBackendFormat,
  convertDateToBackendFormat,
} from '@utils/format-date';

export default {
  props: ['input-data', 'readonly'],
  data() {
    return {
      surname: '',
      firstname: '',
      middlename: '',
      birthdate: '',
      selected: [],
      data: [],
      snils: '',
    };
  },
  computed: {
    columns() {
      return [
        {
          name: 'surname',
          required: true,
          label: this.$t('EmployeesSearchForm.lastName'),
          align: 'left',
          field: 'surname',
          format: (val) => `${val}`,
          sortable: true,
        },
        {
          name: 'firstname',
          align: 'left',
          label: this.$t('EmployeesSearchForm.firstName'),
          field: 'firstname',
          sortable: true,
        },
        {
          name: 'middlename',
          align: 'left',
          label: this.$t('EmployeesSearchForm.middleName'),
          field: 'middlename',
          sortable: true,
        },
        {
          name: 'birthdate',
          align: 'left',
          label: this.$t('EmployeesSearchForm.birthDate'),
          field: 'birthdate',
          format: (val) => {
            if (!val) return '';
            return convertDateFromBackendFormat(val);
          },
          sortable: false,
        },
        {
          name: 'snils',
          align: 'left',
          label: this.$t('EmployeesSearchForm.snils'),
          field: 'snils',
          sortable: false,
        },
      ];
    },
    outputData() {
      return {
        surname: this.surname,
        firstname: this.firstname,
        middlename: this.middlename,
        birthdate: convertDateToBackendFormat(this.birthdate, this.dateMask),
        snils: this.snils,
      };
    },
    searchData() {
      if (this.inputData) {
        let strReturn = '';

        if (this.inputData.surname) {
          strReturn += this.inputData.surname;
        }
        if (this.inputData.firstname) {
          strReturn += ' ' + this.inputData.firstname;
        }
        if (this.inputData.middlename) {
          strReturn += ' ' + this.inputData.middlename;
        }
        if (this.inputData.birthdate) {
          strReturn += ` (${convertDateFromBackendFormat(
            this.inputData.birthdate,
            this.dateMask
          )})`;
        }
        if (this.inputData.snils) {
          strReturn += this.inputData.snils;
        }
        return strReturn || false;
      }
      return false;
    },
    dateMask() {
      return this.$store.getters['i18N/localeMask'].date;
    },
    inputMask() {
      return this.$store.getters['i18N/localeMask'].input;
    },
  },
  watch: {
    dateMask: {
      handler: function (currentValue, oldValue) {
        if (this.birthdate) {
          this.birthdate = convertDateFormat(
            this.birthdate,
            oldValue,
            currentValue
          );
        }
      },
    },
    inputData: {
      handler: function (val, oldVal) {
        if (
          val &&
          oldVal &&
          typeof val === 'object' &&
          typeof oldVal === 'object' &&
          JSON.stringify(val) === JSON.stringify(oldVal)
        ) {
          return;
        }
        if (val) {
          const currentData = this.inputData.formData;
          this.data = this.inputData.searchResult || [];

          if (currentData) {
            this.surname = currentData.surname || '';
            this.firstname = currentData.firstname || '';
            this.middlename = currentData.middlename || '';
            this.birthdate = currentData.birthdate
              ? convertDateFromBackendFormat(
                  currentData.birthdate,
                  this.dateMask
                )
              : '';
            this.snils = currentData.snils || '';
          }
        }
      },
      immediate: true,
    },
  },
  methods: {
    submit(e) {
      this.$emit('submit', e, this.outputData);
    },
    createPerson(e) {
      this.$emit('submit', e, {
        transCreate: true,
        transSearch: false,
        transSelect: false,
        ...this.outputData,
      });
    },
    choosePerson(e) {
      const person = this.selected[0] || null;

      this.$emit('submit', e, {
        transCreate: false,
        transSearch: false,
        transSelect: true,
        ...this.outputData,
        person,
      });
    },
    searchPerson(e) {
      this.$emit('submit', e, {
        transCreate: false,
        transSearch: true,
        transSelect: false,
        ...this.outputData,
      });
    },
  },
};
</script>
