<i18n>
{
  "en": {
    "EmployeesBasicForm": {
      "lastName": "Last name",
      "firstName": "First name",
      "middleName": "Middle name",
      "gender": "Sex",
      "invalidSNILSFormat": "Invalid SNILS format",
      "birthDate": "Birth date",
      "email": "Email",
      "send": "Send",
      "snils": "SNILS",
      "invalidEmail": "Invalid email",
      "ipAddress": "IP-address"
    }
  },
  "ru": {
    "EmployeesBasicForm": {
      "lastName": "Фамилия",
      "firstName": "Имя",
      "middleName": "Отчество",
      "gender": "Пол",
      "invalidSNILSFormat": "Неверный формат СНИЛС",
      "birthDate": "Дата рождения",
      "email": "Адрес электронной почты",
      "send": "Далее",
      "snils": "СНИЛС",
      "invalidEmail": "Неверный email",
      "ipAddress": "IP-адрес"
    }
  }
}
</i18n>

<template>
  <q-form @submit="submit">
    <div v-if="readonly" class="q-gutter-y-sm">
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('EmployeesBasicForm.lastName') }}*
        </div>
        <div class="col text-grey-7">{{ surname }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('EmployeesBasicForm.firstName') }}*
        </div>
        <div class="col text-grey-7">{{ firstname }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('EmployeesBasicForm.middleName') }}*
        </div>
        <div class="col text-grey-7">{{ middlename }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('EmployeesBasicForm.gender') }}
        </div>
        <div class="col text-grey-7">{{ sex }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('EmployeesBasicForm.birthDate') }}
        </div>
        <div class="col text-grey-7">{{ birthdate }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">{{ $t('EmployeesBasicForm.email') }}</div>
        <div class="col text-grey-7">{{ email }}</div>
      </div>
      <div v-if="canChangeIpAddress" class="row">
        <div class="col text-grey-5">
          {{ $t('EmployeesBasicForm.ipAddress') }}
        </div>
        <div class="col text-grey-7">{{ ipAddress }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">{{ $t('EmployeesBasicForm.snils') }}*</div>
        <div class="col text-grey-7">{{ snils }}</div>
      </div>
    </div>
    <div v-else class="q-gutter-y-md">
      <div class="row">
        <div class="col">
          <q-input
            v-model="surname"
            filled
            :label="$t('EmployeesBasicForm.lastName') + '*'"
            :rules="[noEmptyValueRule]"
            required
          />
        </div>
      </div>
      <div class="row q-mt-none">
        <div class="col">
          <q-input
            v-model="firstname"
            filled
            :label="$t('EmployeesBasicForm.firstName') + '*'"
            :rules="[noEmptyValueRule]"
            required
          />
        </div>
      </div>
      <div class="row q-mt-none q-pb-md">
        <div class="col">
          <q-input
            v-model="middlename"
            filled
            :label="$t('EmployeesBasicForm.middleName')"
          />
        </div>
      </div>
      <div class="row q-mt-none q-pb-md">
        <div class="col-xs-12 col-sm q-mr-sm-md">
          <q-select
            v-model="sex"
            :options="genders"
            filled
            :label="$t('EmployeesBasicForm.gender')"
          />
        </div>

        <div class="col-xs-12 col-sm q-mt-xs-md q-mt-sm-none">
          <q-input
            v-model="birthdate"
            class="q-pb-none"
            :label="$t('EmployeesBasicForm.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" />
                </q-popup-proxy>
              </q-icon>
            </template>
          </q-input>
        </div>
      </div>

      <div class="row q-mt-none">
        <div class="col">
          <q-input
            v-model="snils"
            mask="###-###-### ##"
            unmasked-value
            filled
            :label="$t('EmployeesBasicForm.snils') + '*'"
            :rules="[snilsFormatRule, noEmptyValueRule]"
            required
          />
        </div>
      </div>

      <div class="row q-mt-none">
        <div class="col">
          <q-input
            v-model="email"
            :readonly="!!readonlyFields.find((el) => el === 'email')"
            filled
            :label="$t('EmployeesBasicForm.email')"
            type="email"
            :rules="[validEmailRule]"
          >
            <template #prepend>
              <q-icon name="email" />
            </template>
          </q-input>
        </div>
      </div>

      <div class="row q-mt-none" v-if="canChangeIpAddress">
        <div class="col">
          <q-input
            v-model="ipAddress"
            filled
            :label="$t('EmployeesBasicForm.ipAddress')"
            type="text"
            :rules="[validIpAddressRule]"
          >
            <template #prepend>
              <q-icon name="laptop" />
            </template>
          </q-input>
        </div>
      </div>
      <q-btn
        color="primary"
        :label="$t('EmployeesBasicForm.send')"
        type="submit"
      />
    </div>
  </q-form>
</template>

<script lang="ts">
// @ts-nocheck
import { v4 } from 'uuid';
import {
  convertDateFormat,
  convertDateFromBackendFormat,
  convertDateToBackendFormat,
} from '@utils/format-date';
import get from 'lodash/get';
import {
  noEmptyValueRule,
  validEmailRule,
} from '@utils/field-validation/basic';
import { snilsFormatRule } from '@utils/field-validation/employees';

export default {
  props: ['input-data', 'readonly'],
  data() {
    return {
      id: '',
      surname: '',
      firstname: '',
      middlename: '',
      sex: '',
      snils: '',
      genders: ['Мужской', 'Женский'],
      birthdate: '',
      email: '',
      modified: null,
      ipAddress: '',
      localCredentials: [],
      isEditProcess: false,
    };
  },
  computed: {
    outputData() {
      return {
        personData: {
          id: this.id,
          surname: this.surname,
          firstname: this.firstname,
          middlename: this.middlename,
          sex: this.sex,
          birthdate: this.birthdateFormatted,
          email: this.email,
          snils: this.snils,
          modified: this.modified || undefined,
          ipAddresses: this.ipAddress ? [this.ipAddress] : [],
        },
        personDataForStepper: {
          surname: this.surname,
          firstname: this.firstname,
          middlename: this.middlename,
          sex: this.sex,
          birthdate: this.birthdate,
          ipAddresses: this.ipAddress ? [this.ipAddress] : [],
          email: this.email,
          snils: this.snils,
        },
      };
    },
    readonlyFields() {
      return this.inputData.readonlyFields || [];
    },
    birthdateFormatted() {
      return convertDateToBackendFormat(this.birthdate, this.dateMask);
    },
    dateMask() {
      return this.$store.getters['i18N/localeMask'].date;
    },
    inputMask() {
      return this.$store.getters['i18N/localeMask'].input;
    },
    canChangeIpAddress() {
      return (
        !this.isEditProcess ||
        (this.$AC.haveScope(this.$AC.scopes.SECURITY_ADMINISTRATOR) &&
          !!this.localCredentials.length)
      );
    },
  },
  watch: {
    inputData: {
      handler: function (val, oldVal) {
        if (
          val &&
          oldVal &&
          typeof val === 'object' &&
          typeof oldVal === 'object' &&
          JSON.stringify(val) === JSON.stringify(oldVal)
        ) {
          return;
        }
        this.id = v4();
        if (val) {
          this.firstname = val.firstname || '';
          this.surname = val.surname || '';
          this.middlename = val.middlename || '';
          this.birthdate =
            convertDateFromBackendFormat(val.birthdate, this.dateMask) || '';
          this.sex = val.sex || '';
          this.email = val.email || '';
          this.snils = val.snils || '';

          const ipAddresses = get(val, 'person.ipAddresses', []);
          if (ipAddresses?.length) {
            this.ipAddress = ipAddresses[0];
          }

          if (this.readonly && val.personDataForStepper) {
            this.surname = val.personDataForStepper.surname;
            this.firstname = val.personDataForStepper.firstname;
            this.middlename = val.personDataForStepper.middlename;
            this.sex = val.personDataForStepper.sex;
            this.birthdate = val.personDataForStepper.birthdate;
            if (val.personData && val.personData.birthdate) {
              this.birthdate = convertDateFromBackendFormat(
                val.birthdate,
                this.dateMask
              );
            }
            this.email = val.personDataForStepper.email;
            this.snils = val.personDataForStepper.snils;

            const ipAddressesSteper = get(
              val,
              'personDataForStepper.person.ipAddresses',
              []
            );
            if (ipAddressesSteper?.length) {
              this.ipAddress = ipAddressesSteper[0];
            }
          }
        }
        if (val.isEditProcess) {
          this.isEditProcess = true;
          this.id = val.person.id;
          this.surname = val.person.surname;
          this.modified = val.person.modified;
          this.firstname = val.person.firstname;
          this.middlename = val.person.middlename;
          this.sex = val.person.sex;
          if (val.person.birthdate) {
            this.birthdate = convertDateFromBackendFormat(
              val.person.birthdate,
              this.dateMask
            );
          }
          this.email = val.person.email;
          this.snils = val.person.snils;
          this.localCredentials =
            val.credentials.filter(
              (credential) => credential.schema === 'LocalCredential'
            ) || [];
        }
      },
      immediate: true,
    },
    dateMask: {
      handler: function (currentValue, oldValue) {
        if (this.birthdate) {
          this.birthdate = convertDateFormat(
            this.birthdate,
            oldValue,
            currentValue
          );
        }
      },
    },
    ipAddress(newValue, oldValue) {
      const splitDotValue = newValue.split('.');
      if (
        // проверка что предущее действие не было удаление
        newValue !== oldValue.slice(0, -1) &&
        // проверка что уже нет разбития на 4 блока IP-адреса
        splitDotValue.length < 4 &&
        // проверка что введено 3 символа
        splitDotValue[splitDotValue.length - 1].length === 3
      ) {
        this.ipAddress += '.';
      }
    },
  },
  methods: {
    submit(e) {
      this.$emit('submit', e, this.outputData);
    },
    noEmptyValueRule,
    validEmailRule,
    snilsFormatRule,
    validIpAddressRule(val: string): boolean | string {
      const pattern = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/;
      const result = val.match(pattern);
      const haveError = val && (!result || result[0].length !== val.length);
      return !haveError || 'Некорректный IP-адрес';
    },
  },
};
</script>
