<template>
  <Centered1280Box>
    <white-card>
      <div class="row q-pa-sm">
        <div class="col-12 col-sm-3 header q-pb-sm">
          <block-header> Личные сведения </block-header>
        </div>
        <div class="col-12 col-sm-9">
          <div class="row q-col-gutter-xs">
            <div class="col-12 col-sm-6 col-md-4">
              <data-block
                :form-data="{
                  label: 'Фамилия',
                  value: get(recruitData, 'mainInfo.lastName'),
                }"
                :loading="loading"
              />
            </div>

            <div class="col-12 col-sm-6 col-md-4">
              <data-block
                :form-data="{
                  label: 'Имя',
                  value: get(recruitData, 'mainInfo.firstName'),
                }"
                :loading="loading"
              />
            </div>

            <div class="col-12 col-sm-6 col-md-4">
              <data-block
                :form-data="{
                  label: 'Отчество (при наличии)',
                  value: get(recruitData, 'mainInfo.middleName'),
                }"
                :loading="loading"
              />
            </div>

            <div class="col-12 col-sm-6 col-md-4">
              <data-block
                :form-data="{
                  label: 'Пол',
                  value: genderToString(get(recruitData, 'mainInfo.gender')),
                }"
                :loading="loading"
              />
            </div>

            <div class="col-12 col-sm-6 col-md-4">
              <data-block
                :form-data="{
                  label: 'Дата рождения',
                  value: formatDate(get(recruitData, 'mainInfo.birthDate')),
                  icon: 'pgs-calendar',
                }"
                :loading="loading"
              />
            </div>
            <div class="col-12 col-sm-6 col-md-4">
              <data-block
                :form-data="{
                  label: 'Место рождения',
                  value: get(recruitData, 'mainInfo.birthPlace'),
                  icon: 'pgs-geo',
                }"
                :loading="loading"
              />
            </div>

            <div class="col-12 col-sm-6 col-md-4">
              <data-block
                :form-data="{
                  label: 'Идентификатор ЕРН',
                  value: get(recruitData, 'systemInfo.idERN'),
                }"
                :loading="loading"
              />
            </div>

            <div class="col-12 col-sm-6 col-md-4">
              <data-block
                :form-data="{
                  label: 'СНИЛС',
                  value: get(recruitData, 'mainInfo.snils'),
                }"
                :loading="loading"
              />
            </div>

            <div class="col-12 col-sm-6 col-md-4">
              <data-block
                :form-data="{
                  label: 'ИНН',
                  value: get(recruitData, 'mainInfo.inn'),
                }"
                :loading="loading"
              />
            </div>

            <div
              class="col-12 col-sm-6 col-md-4"
              v-if="get(data, 'systemInfo.esiaId')"
            >
              <data-block
                :form-data="{
                  label: 'Идентификатор ЕСИА',
                  value: get(recruitData, 'systemInfo.esiaId'),
                }"
                :loading="loading"
              />
            </div>

            <div
              class="col-12"
              v-if="
                get(recruitData, 'mainInfo.phone') ||
                get(recruitData, 'mainInfo.email')
              "
            >
              <data-block bolder :form-data="{ label: 'Контактные сведения' }">
                <div class="full-width q-mt-sm">
                  <div class="row q-col-gutter-xs">
                    <div
                      class="col-12 col-sm-6 col-md-4"
                      v-if="get(recruitData, 'mainInfo.phone')"
                    >
                      <data-block
                        :form-data="{
                          label: 'Телефон',
                          icon: 'pgs-phone',
                          value: get(recruitData, 'mainInfo.phone'),
                        }"
                        :loading="loading"
                        background="white"
                      />
                    </div>
                    <div
                      class="col-12 col-sm-6 col-md-4"
                      v-if="get(recruitData, 'mainInfo.email')"
                    >
                      <data-block
                        :form-data="{
                          label: 'Электронная почта',
                          icon: 'pgs-mail',
                          value: get(recruitData, 'mainInfo.email'),
                        }"
                        :loading="loading"
                        background="white"
                      />
                    </div>
                  </div>
                </div>
              </data-block>
            </div>

            <div
              class="col-12"
              v-if="get(recruitData, 'mainInfo.addresses', []).length"
            >
              <data-block bolder :form-data="{ label: 'Адреса' }">
                <div class="full-width q-mt-sm">
                  <div class="row q-col-gutter-xs">
                    <div
                      class="col-12 row q-col-gutter-xs"
                      v-for="(address, i) in addressesToDisplay"
                      :key="`address_${address.id}` + i"
                    >
                      <div :class="address.insertClass">
                        <data-block
                          :background="'white'"
                          :loading="loading"
                          :form-data="{
                            label: address.label,
                            icon: 'pgs-geo',
                            value: address.value,
                          }"
                        />
                      </div>
                      <template v-for="{ label, value } in address.dates">
                        <data-block
                          v-if="value"
                          :background="'white'"
                          :loading="loading"
                          :form-data="{
                            label,
                            icon: 'pgs-calendar',
                            value,
                          }"
                          class="col-2"
                        />
                      </template>
                    </div>
                  </div>
                </div>
              </data-block>
            </div>

            <div class="col-12">
              <data-block
                bolder
                :form-data="{ label: 'Документ, удостоверяющий личность' }"
              >
                <div class="full-width q-mt-sm">
                  <div
                    class="row q-col-gutter-xs"
                    :class="
                      index !==
                      get(recruitData, 'mainInfo.documents', []).length - 1
                        ? 'q-mb-lg'
                        : ''
                    "
                    v-for="(document, index) in get(
                      recruitData,
                      'mainInfo.documents',
                      []
                    )"
                    :key="`passport_${document.series}-${document.number}_${index}`"
                  >
                    <div class="col-6">
                      <data-block
                        :form-data="{
                          label: 'Вид документа',
                          value: docType(document.type),
                        }"
                        :loading="loading"
                        background="white"
                      />
                    </div>

                    <div class="col-2">
                      <data-block
                        :form-data="{
                          label: 'Серия',
                          value: document.series,
                        }"
                        :loading="loading"
                        background="white"
                      />
                    </div>

                    <div class="col-2">
                      <data-block
                        :form-data="{
                          label: 'Номер',
                          value: document.number,
                        }"
                        :loading="loading"
                        background="white"
                      />
                    </div>

                    <div class="col-2">
                      <data-block
                        :form-data="{
                          label: 'Дата выдачи',
                          value: formatDate(document.issueDate),
                          icon: 'pgs-calendar',
                        }"
                        :loading="loading"
                        background="white"
                      />
                    </div>

                    <div class="col-12">
                      <data-block
                        :form-data="{
                          label: 'Наименование органа, выдавшего документ',
                          value: document.issueOrg,
                        }"
                        :loading="loading"
                        background="white"
                      />
                    </div>

                    <div class="col-6">
                      <data-block
                        :form-data="{
                          label: 'Статус действительности документа',
                          value: getDocumentStatus(document.status),
                        }"
                        :loading="loading"
                        background="white"
                      />
                    </div>

                    <div class="col-6">
                      <data-block
                        :form-data="{
                          label: 'Код подразделения',
                          value: document.issueIdCode,
                        }"
                        :loading="loading"
                        background="white"
                      />
                    </div>
                  </div>
                </div>
              </data-block>
            </div>

            <div class="col-12 col-sm-6 col-md-3">
              <data-block
                :form-data="{
                  label: 'Состояние в браке',
                  value: spouseType(get(recruitData, 'details.spouse.status')),
                }"
                :loading="loading"
              />
            </div>

            <div
              class="col-12 col-sm-6 col-md-3"
              v-if="get(recruitData, 'details.spouse.hasChildren')"
            >
              <data-block
                :form-data="{
                  label: 'Наличие детей до 18 лет',
                  icon: 'pgs-people',
                  value:
                    get(recruitData, 'details.spouse.countLittleChildren') ||
                    'Нет',
                }"
                :loading="loading"
              />
            </div>
            <div class="col-12 col-sm-6">
              <data-block
                :form-data="{
                  label: 'Получено согласие на обработку персональных данных',
                  icon: 'pgs-sign-2',
                  value: get(
                    recruitData,
                    'stateRecruit.personalDataProcessingAgreeConfirmed',
                    false
                  )
                    ? 'Да'
                    : 'Нет',
                }"
                :loading="loading"
              />
            </div>
            <div class="col-6 col-sm-3">
              <data-block
                :form-data="{
                  label: 'Несовершеннолетних детей',
                  value: get(
                    recruitData,
                    'details.spouse.countLittleChildren',
                    0
                  ),
                }"
                :loading="loading"
              />
            </div>
            <div
              class="col-6 col-sm-3"
              v-if="get(recruitData, 'details.spouse.dateActualTo')"
            >
              <data-block
                :form-data="{
                  label: 'Дата актуализации данных',
                  icon: 'pgs-calendar',
                  value: formatDate(
                    get(recruitData, 'details.spouse.dateActualTo', '')
                  ),
                }"
                :loading="loading"
              />
            </div>
            <div
              class="col-12 col-sm-6"
              v-if="get(recruitData, 'mainInfo.deathDate')"
            >
              <data-block
                :form-data="{
                  label: 'Дата смерти',
                  icon: 'pgs-calendar',
                  value: formatDate(get(recruitData, 'mainInfo.deathDate')),
                }"
                :loading="loading"
              />
            </div>
          </div>
        </div>
      </div>
    </white-card>
    <white-card>
      <div class="row q-pa-sm">
        <div class="col-12 col-sm-3 header q-pb-sm">
          <block-header>Сведения о воинском учёте</block-header>
        </div>
        <div class="col-12 col-sm-9">
          <div class="row q-col-gutter-xs">
            <div class="col-3" v-if="get(recruitData, 'systemInfo.source')">
              <data-block
                :form-data="{
                  label: 'Источник данных',
                  icon: 'pgs-bpmn',
                  value: source(get(recruitData, 'systemInfo.source', '')),
                }"
                :loading="loading"
              />
            </div>
            <div class="col-6" v-if="!!registrationReasons">
              <data-block
                :form-data="{
                  label: 'Причина постановки на учёт',
                  icon: 'pgs-bpmn',
                  value: registrationReasons,
                }"
                :loading="loading"
              />
            </div>
            <div
              class="col-3"
              v-if="
                get(
                  recruitData,
                  'details.citizenshipInfo.obtainCitizenshipDate'
                )
              "
            >
              <data-block
                class="col-3"
                :form-data="{
                  label: 'Дата приобретения гражданства',
                  icon: 'pgs-calendar',
                  value: formatDate(
                    get(
                      recruitData,
                      'details.citizenshipInfo.obtainCitizenshipDate'
                    )
                  ),
                }"
                :loading="loading"
              />
            </div>
            <div
              class="col-3"
              v-if="
                get(recruitData, 'details.citizenshipInfo.loseCitizenshipDate')
              "
            >
              <data-block
                class="col-3"
                :form-data="{
                  label: 'Дата утраты гражданства',
                  icon: 'pgs-calendar',
                  value: formatDate(
                    get(
                      recruitData,
                      'details.citizenshipInfo.loseCitizenshipDate'
                    )
                  ),
                }"
                :loading="loading"
              />
            </div>
            <div class="col-3" v-if="get(recruitData, 'extraInfo.dateArrival')">
              <data-block
                class="col-3"
                :form-data="{
                  label: 'Дата приезда в РФ',
                  icon: 'pgs-calendar',
                  value: formatDate(get(recruitData, 'extraInfo.dateArrival')),
                }"
                :loading="loading"
              />
            </div>
            <div class="col-3" v-if="get(recruitData, 'extraInfo.dateRelease')">
              <data-block
                class="col-3"
                :form-data="{
                  label: 'Дата освобождения',
                  icon: 'pgs-calendar',
                  value: formatDate(get(recruitData, 'extraInfo.dateRelease')),
                }"
                :loading="loading"
              />
            </div>
            <div class="col-6" v-if="get(recruitData, 'systemInfo.docId')">
              <data-block
                class="col-6"
                :form-data="{
                  label: 'Военный идентификатор',
                  icon: 'pgs-admin',
                  value: get(recruitData, 'systemInfo.docId'),
                }"
                :loading="loading"
              />
            </div>
            <div class="col-3" v-if="get(recruitData, 'systemInfo.docIdDate')">
              <data-block
                :form-data="{
                  label: 'Дата присвоения военного идентификатора',
                  icon: 'pgs-calendar',
                  value: formatDate(get(recruitData, 'systemInfo.docIdDate')),
                }"
                :loading="loading"
              />
            </div>
            <div
              class="col-3"
              v-if="get(recruitData, 'systemInfo.militaryRegistrationDate')"
            >
              <data-block
                :form-data="{
                  label: 'Дата постановки на учёт',
                  icon: 'pgs-calendar',
                  value: formatDate(
                    get(recruitData, 'systemInfo.militaryRegistrationDate')
                  ),
                }"
                :loading="loading"
              />
            </div>
            <div class="col-3" v-if="get(recruitData, 'mainInfo.vuUnsetDate')">
              <data-block
                :form-data="{
                  label: 'Дата снятия с учёта',
                  icon: 'pgs-calendar',
                  value: formatDate(get(recruitData, 'mainInfo.vuUnsetDate')),
                }"
                :loading="loading"
              />
            </div>
            <div
              class="col-3"
              v-if="
                isBoolean(
                  get(recruitData, 'recruitSystemInfo.militaryRegistrationFlag')
                ) && sourceHaveGIRInfo
              "
            >
              <data-block
                :form-data="{
                  label: 'Сведения о воинском учёте',
                  icon: 'pgs-people',
                  value: get(
                    recruitData,
                    'recruitSystemInfo.militaryRegistrationFlag'
                  )
                    ? 'Состоит на учёте'
                    : 'Снят с учёта',
                }"
                :loading="loading"
              />
            </div>
            <div
              class="col-9"
              v-if="
                get(
                  recruitData,
                  'recruitSystemInfo.militaryRegistrationFlag'
                ) && militaryDepartmentName
              "
            >
              <data-block
                :form-data="{
                  label: 'Военный комиссариат',
                  icon: 'pgs-people',
                  value: militaryDepartmentName,
                }"
                :loading="loading"
              />
            </div>
          </div>
        </div>
      </div>
    </white-card>
  </Centered1280Box>
</template>

<style lang="scss" scoped>
.header {
  > span {
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 400;
    font-size: 18px;
    line-height: 22px;
    letter-spacing: -0.015em;
    color: rgba(2, 12, 18, 0.9);
  }
}
</style>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';

import { formatDate, getObjDict, mask } from '@/recruits/utils';
import dataBlock from '@components/cards/statements/components/dataBlock.vue';
import { sex } from '@/recruits/models';
import { Address, RecruitV3 } from '@/recruits/openapi/person-registry';
import { ArchivedRecruitV3 } from '@/recruits/openapi/person-archive';
import Centered1280Box from '@/recruits/components/common/centered-1280-box.vue';
import WhiteCard from '@/recruits/components/common/white-card.vue';
import BlockHeader from '@/recruits/components/common/block-header.vue';
import get from 'lodash/get';
import isBoolean from 'lodash/isBoolean';
import { ADDRESS_TYPES } from '@/recruits/models/Directorys/addressType';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const DocumentType = require('@/recruits/models/Directorys/DocumenType.json');
const documentTypes = getObjDict(DocumentType.documents);
// eslint-disable-next-line @typescript-eslint/no-var-requires
const SpouseDict = require('@/recruits/models/Directorys/SpouseCodes');
const SpouseTypes = getObjDict(SpouseDict.documents);
// eslint-disable-next-line @typescript-eslint/no-var-requires

interface AddressToDisplay {
  id: string;
  label: string;
  value: string;
  dates: { label: string; value: string }[];
  insertClass: string;
}

@Component({
  components: {
    dataBlock,
    Centered1280Box,
    WhiteCard,
    BlockHeader,
  },
  methods: {
    mask,
    formatDate,
    get,
    isBoolean,
  },
})
export default class PersonalTab extends Vue {
  get: typeof get;
  formatDate: typeof formatDate;

  @Prop({ type: Object, default: {} })
  public data: ArchivedRecruitV3;

  @Prop({ type: Boolean, default: false })
  public loading: boolean;

  get sourceHaveGIRInfo(): boolean {
    return !(
      this.data?.recruit?.systemInfo.source === '3' ||
      this.data?.recruit?.systemInfo.source === '4'
    );
  }

  get determinationCurrentVK(): boolean {
    return !!this.data?.recruit?.recruitSystemInfo?.departmentId;
  }

  get recruitData(): Partial<RecruitV3> {
    return this.data.recruit ?? {};
  }

  get registrationReasons(): string {
    return (
      this.data?.recruit?.recruitSystemInfo?.registrationReasons?.join(', ') ||
      ''
    );
  }

  get militaryDepartmentName(): string {
    return this.data?.recruit?.recruitSystemInfo?.departmentName || '';
  }

  get addressesToDisplay(): AddressToDisplay[] {
    return (
      this.recruitData?.mainInfo?.addresses?.reduce(
        (addresses: AddressToDisplay[], address, index) => {
          const type = ADDRESS_TYPES[address.type] || ADDRESS_TYPES.unknown;
          if (type.isShow) {
            addresses.push({
              id: address.id || String(index),
              label: type.label,
              value: this.addressWithIndex(address),
              insertClass: this.insertClass(address),
              dates: [
                {
                  label: type.dates.regDateStart || '',
                  value: this.formatDate(address.regDateStart || ''),
                },
                {
                  label: type.dates.regDateEnd || '',
                  value: this.formatDate(address.regDateEnd || ''),
                },
              ],
            });
          }
          return addresses;
        },
        []
      ) || []
    );
  }

  addressWithIndex({ postOfficeIndex, reg }: Address): string {
    return `${postOfficeIndex ? `${postOfficeIndex}, ` : ''}${reg || '-'}`;
  }

  docType(type: string): string {
    return documentTypes[type];
  }

  spouseType(type: string): string {
    return SpouseTypes[type];
  }

  getDocumentStatus(documentStatusId: string): string {
    const dict = this.$store.getters['ervuDictionaries/typesDulRf'];
    return dict[documentStatusId] || '';
  }

  source(sourceCode: string): string {
    const dict = this.$store.getters[
      'ervuDictionaries/sourcesRecruitDictionary'
    ];
    return dict[sourceCode] || '';
  }

  public genderToString(genderValue: string): string {
    return genderValue in sex ? sex[genderValue] : genderValue;
  }

  insertClass(address: Address): string {
    if (address.regDateStart && address.regDateEnd) {
      return 'col-8';
    } else if (address.regDateStart || address.regDateEnd) {
      return 'col-10';
    }
    return 'col-12';
  }
}
</script>
