<template>
  <q-form @submit="submit">
    <div v-if="readonly" class="q-gutter-y-sm">
      <div class="row">
        <div class="col text-grey-5">Фамилия*</div>
        <div class="col text-grey-7">{{ surname }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">Имя*</div>
        <div class="col text-grey-7">{{ firstname }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">Отчество</div>
        <div class="col text-grey-7">{{ middlename }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">Пол*</div>
        <div class="col text-grey-7">{{ sex }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">Дата рождения*</div>
        <div class="col text-grey-7">{{ birthdate }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">СНИЛС</div>
        <div class="col text-grey-7">{{ inn }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">Адрес электронной почты*</div>
        <div class="col text-grey-7">{{ email }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">Номер телефона*</div>
        <div class="col text-grey-7">+7{{ phone }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">Место рождения*</div>
        <div class="col text-grey-7">{{ placeOfBirth }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">Гражданство*</div>
        <div class="col text-grey-7">{{ citizenship }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">Адрес регистрации</div>
        <div class="col text-grey-7">{{ registrationAddress }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          Адрес временной регистрации по месту пребывания
        </div>
        <div class="col text-grey-7">{{ tempRegistrationAddress }}</div>
      </div>
    </div>
    <div class="q-gutter-y-md" v-else>
      <div class="row">
        <div class="col q-mt-xs-md q-mt-sm-none">
          <q-input
            filled
            label="Фамилия*"
            v-model="surname"
            :rules="[noEmptyValueRule]"
          />
        </div>
      </div>
      <div class="row">
        <div class="col q-mt-xs-md q-mt-sm-none">
          <q-input
            filled
            label="Имя*"
            v-model="firstname"
            :rules="[noEmptyValueRule]"
          />
        </div>
      </div>
      <div class="row">
        <div class="col q-mt-xs-md q-mt-sm-none" style="margin-bottom: 17px">
          <q-input filled label="Отчество" v-model="middlename" />
        </div>
      </div>
      <div class="row">
        <div class="col-xs-12 col-sm q-mr-sm-md">
          <q-select
            :options="genders"
            filled
            label="Пол*"
            v-model="sex"
            :rules="[noEmptyValueRule]"
          />
        </div>

        <div class="col-xs-12 col-sm q-mt-xs-md q-mt-sm-none">
          <q-input
            class="q-pb-none"
            label="Дата рождения*"
            filled
            v-model="birthdate"
            :mask="inputMask"
            :rules="[noEmptyValueRule]"
            @input="closeBirthDatePopup"
          >
            <template v-slot: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="closeBirthDatePopup"
                  />
                </q-popup-proxy>
              </q-icon>
            </template>
          </q-input>
        </div>
      </div>
      <div class="row">
        <div class="col" style="margin-bottom: 17px">
          <q-input
            fill-mask
            filled
            label="СНИЛС"
            type="text"
            v-model="inn"
            mask="###-###-### ##"
            unmasked-value
          />
        </div>
      </div>

      <div class="row">
        <div class="col-xs-12 col-sm q-mr-sm-md">
          <q-input
            filled
            label="Адрес электронной почты*"
            type="email"
            v-model="email"
            :rules="[validEmailRule]"
          >
            <template v-slot:prepend>
              <q-icon name="email" />
            </template>
          </q-input>
        </div>
        <div class="col-xs-12 col-sm q-mt-xs-md q-mt-sm-none">
          <q-input
            fill-mask
            filled
            label="Номер телефона*"
            mask="+7 (###) ###-##-##"
            unmasked-value
            v-model="phone"
            :rules="[validPhoneNumberRule]"
          >
            <template v-slot:prepend>
              <q-icon name="phone" />
            </template>
          </q-input>
        </div>
      </div>
      <q-separator />
      <div class="q-gutter-y-md">
        <div class="row">
          <div class="col-xs-12 col-sm q-mr-sm-md">
            <q-input
              filled
              label="Место рождения*"
              type="text"
              v-model="placeOfBirth"
              :rules="[noEmptyValueRule]"
            />
          </div>
          <div class="col-xs-12 col-sm q-mt-xs-md q-mt-sm-none">
            <q-select
              :options="citizenFilteredOptions"
              filled
              use-input
              input-debounce="0"
              @filter="filterFn"
              label="Гражданство*"
              v-model="citizenship"
              :rules="[noEmptyValueRule]"
            />
          </div>
        </div>
      </div>
      <q-separator />
      <div class="q-gutter-y-md">
        <div class="row">
          <div class="col">
            <BasicMAddressComponent
              :id.sync="registrationAddressId"
              :value.sync="registrationAddress"
              label="Адрес регистрации"
              filled
            />
          </div>
        </div>
      </div>
      <div class="q-gutter-y-md">
        <div class="row">
          <div class="col">
            <BasicMAddressComponent
              :id.sync="tempRegistrationAddressId"
              :value.sync="tempRegistrationAddress"
              label="Адрес временной регистрации по месту пребывания"
              filled
            />
          </div>
        </div>
      </div>
      <q-separator />
      <div class="q-gutter-y-md">
        <div class="row">
          <div class="col">
            <q-checkbox
              v-model="isGuardian"
              label="Я являюсь опекуном (попечителем) несовершеннолетнего ребенка (детей)"
            />
          </div>
        </div>
      </div>
      <div v-if="isGuardian" class="q-gutter-y-md">
        <div class="row">
          <div class="col">
            <p>Реквизиты решения органа опеки и попечительства</p>
          </div>
        </div>
        <div class="row">
          <div class="col-xs-12 col-sm q-mr-sm-md">
            <q-input
              filled
              label="Номер*"
              v-model="custodyAllowanceNumber"
              :rules="[noEmptyValueRule]"
            />
          </div>
          <div class="col-xs-12 col-sm q-mt-xs-md q-mt-sm-none">
            <q-input
              class="q-pb-none"
              label="Дата выдачи*"
              filled
              v-model="custodyAllowanceDate"
              :mask="inputMask"
              :rules="[noEmptyValueRule]"
            >
              <template v-slot:append>
                <q-icon name="event" class="cursor-pointer">
                  <q-popup-proxy
                    ref="qDateProxy"
                    transition-show="scale"
                    transition-hide="scale"
                  >
                    <q-date
                      v-model="custodyAllowanceDate"
                      :mask="dateMask"
                      @input="$refs.qDateProxy.hide()"
                      :rules="[noEmptyValueRule]"
                    />
                  </q-popup-proxy>
                </q-icon>
              </template>
            </q-input>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <q-input
              filled
              label="Орган, выдавший документ*"
              v-model="custodianAuthority"
              :rules="[noEmptyValueRule]"
            />
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col">
          <q-checkbox :label="confirm.label" v-model="confirm.value" />
        </div>
      </div>
      <q-btn
        :disable="!confirm.value"
        color="primary"
        label="Отправить"
        type="submit"
      />
    </div>
  </q-form>
</template>

<script lang="ts">
// @ts-nocheck
import BasicMAddressComponent from '../m-address/index.vue';
import {
  convertDateFormat,
  convertDateFromBackendFormat,
  convertDateToBackendFormat,
} from '@utils/format-date';
import {
  noEmptyValueRule,
  validPhoneNumberRule,
  validEmailRule,
} from '@utils/field-validation/basic';

export default {
  props: ['input-data', 'readonly'],
  components: {
    BasicMAddressComponent,
  },
  data() {
    return {
      surname: '',
      firstname: '',
      middlename: '',
      sex: '',
      genders: ['Мужской', 'Женский'],
      citizenFilteredOptions: [],
      countries: [
        'Российская Федерация',
        'Республика Беларусь',
        'Республика Словения',
        'Республика Абхазия',
        'Республика Азербайджан',
        'Республика Абхазия',
        'Республика Казахстан',
        'Турецкая Республика',
        'Эстонская Республика',
        'Чешская Республика',
        'Украина',
        'Государство Израиль',
        'Греческая Республика',
        'Республика Грузия',
      ],
      birthdate: '',
      inn: '',
      email: '',
      phone: '',
      placeOfBirthId: '',
      placeOfBirth: '',
      citizenship: null,
      registrationAddressId: '',
      registrationAddress: '',
      tempRegistrationAddressId: '',
      tempRegistrationAddress: '',
      isGuardian: false,
      custodyAllowanceNumber: '',
      custodyAllowanceDate: '',
      custodianAuthority: '',
      confirm: {
        label: 'Я даю согласие на обработку персональных данных.',
        value: false,
      },
      isSurnameValid: false,
      isFirstNameValid: false,
      isSexValid: false,
      isBirthDateValid: false,
      isBirthPlaceValid: false,
      isCitizenshipValid: false,
      isEmailValid: false,
      isPhoneValid: false,
    };
  },
  computed: {
    outputData() {
      return {
        surname: this.surname,
        firstname: this.firstname,
        middlename: this.middlename,
        sex: this.sex,
        birthdate: this.birthdateFormatted,
        inn: this.inn,
        email: this.email,
        phone: this.phone,
        placeOfBirthId: this.placeOfBirthId,
        placeOfBirth: this.placeOfBirth,
        citizenship: this.citizenship,
        registrationAddressId: this.registrationAddressId,
        registrationAddress: this.registrationAddress,
        tempRegistrationAddressId: this.tempRegistrationAddressId,
        tempRegistrationAddress: this.tempRegistrationAddress,
        isGuardian: this.isGuardian,
        custodyAllowanceNumber: this.custodyAllowanceNumber,
        custodyAllowanceDate: this.custodyAllowanceDate,
        custodianAuthority: this.custodianAuthority,
        confirm: this.confirm.value,
      };
    },
    birthdateFormatted() {
      return convertDateToBackendFormat(this.birthdate, this.dateMask);
    },
    dateMask() {
      return this.$store.getters['i18N/localeMask'].date;
    },
    inputMask() {
      return this.$store.getters['i18N/localeMask'].input;
    },
  },
  methods: {
    submit(e) {
      this.$emit('submit', e, this.outputData);
    },
    closeBirthDatePopup() {
      this.$refs.qDateProxy.hide();
    },
    filterFn(val, update) {
      if (val === '') {
        update(() => {
          this.citizenFilteredOptions = this.countries;
        });
        return;
      }

      update(() => {
        const needle = val.toLowerCase();
        this.citizenFilteredOptions = this.countries.filter(
          (v) => v.toLowerCase().indexOf(needle) > -1
        );
      });
    },
    noEmptyValueRule,
    validPhoneNumberRule,
    validEmailRule,
  },
  watch: {
    inputData: {
      handler: function (val) {
        if (val) {
          this.firstname = val.firstname || '';
          this.surname = val.surname || '';
          this.middlename = val.middlename || '';
          this.sex = val.sex || '';
          this.birthdate =
            convertDateFromBackendFormat(val.birthdate, this.dateMask) || '';
          this.inn = val.inn || '';
          this.email = val.email || '';
          this.phone = val.phone || '';
          this.placeOfBirthId = val.placeOfBirthId || '';
          this.placeOfBirth = val.placeOfBirth || '';
          this.citizenship = val.citizenship || '';
          this.registrationAddressId = val.registrationAddressId || '';
          this.registrationAddress = val.registrationAddress || '';
          this.tempRegistrationAddressId = val.tempRegistrationAddressId || '';
          this.tempRegistrationAddress = val.tempRegistrationAddress || '';
          this.isGuardian = val.isGuardian || false;
          this.custodyAllowanceNumber = val.custodyAllowanceNumber || '';
          this.custodyAllowanceDate = val.custodyAllowanceDate || '';
          this.custodianAuthority = val.custodianAuthority || '';
        }
      },
      immediate: true,
    },
    dateMask: {
      handler: function (currentValue, oldValue) {
        if (this.birthdate) {
          this.birthdate = convertDateFormat(
            this.birthdate,
            oldValue,
            currentValue
          );
        }
      },
    },
  },
};
</script>
