<template>
  <Centered1280Box class="PersonalInfo">
    <white-card class="PersonalInfo-WhiteCard">
      <div class="PersonalInfo-Header">Личные сведения</div>
      <div class="PersonalInfo-FlexBox">
        <div class="PersonalInfo-FlexBox">
          <template v-for="info in mainInfo">
            <data-block
              v-if="info.isShow"
              :key="get(info, 'formData.label')"
              :form-data="info.formData"
              :loading="loading"
              class="PersonalInfo-FlexElement"
            />
          </template>
        </div>

        <data-block
          v-if="addressesToDisplay.length"
          :form-data="{ label: 'Адрес' }"
          bolder
          class="PersonalInfo-Card"
        >
          <div class="PersonalInfo-FlexBox">
            <div
              v-for="address in addressesToDisplay"
              :key="address.id"
              class="PersonalInfo-FlexBox"
            >
              <data-block
                :form-data="{
                  label: address.label,
                  icon: 'pgs-geo',
                  value: address.value,
                }"
                :loading="loading"
                :background="'white'"
                class="PersonalInfo-FlexElement"
              />
              <template v-for="{ label, value } in address.dates">
                <data-block
                  v-if="value"
                  :form-data="{
                    label,
                    icon: 'pgs-calendar',
                    value,
                  }"
                  :loading="loading"
                  :background="'white'"
                  class="PersonalInfo-FlexElement PersonalInfo-FlexElement__NoGrow"
                />
              </template>
            </div>
          </div>
        </data-block>

        <data-block
          v-for="document in personalDocuments"
          :form-data="{ label: document.label }"
          :key="document.key"
          bolder
          class="PersonalInfo-Card"
        >
          <div class="PersonalInfo-FlexBox">
            <data-block
              v-for="field in document.data"
              :key="get(field, 'formData.label')"
              :form-data="field.formData"
              :loading="loading"
              :background="'white'"
              class="PersonalInfo-FlexElement"
            />
          </div>
        </data-block>

        <data-block
          :form-data="{ label: 'Сведения о семье' }"
          bolder
          class="PersonalInfo-Card"
        >
          <div class="PersonalInfo-FlexBox">
            <data-block
              v-for="field in familyStatus"
              :form-data="field.formData"
              :key="get(field, 'formData.label')"
              :loading="loading"
              :background="'white'"
              class="PersonalInfo-FlexElement"
            />
          </div>
        </data-block>
      </div>
    </white-card>
    <white-card class="PersonalInfo-WhiteCard">
      <div class="PersonalInfo-Header">Сведения о воинском учёте</div>
      <div class="PersonalInfo-FlexBox">
        <template v-for="info in militaryRegistrationInfo">
          <data-block
            v-if="info.isShow"
            :key="get(info, 'formData.label')"
            :form-data="info.formData"
            :loading="loading"
            class="PersonalInfo-FlexElement PersonalInfo-FlexElement__Big"
          />
        </template>
      </div>
    </white-card>
    <white-card v-if="postponement.isShow" class="PersonalInfo-WhiteCard">
      <div class="PersonalInfo-Header">
        Сведения о наличии оснований для отсрочки/освобождения от ВС
      </div>
      <div class="PersonalInfo-FLexBox">
        <data-block
          :form-data="postponement.formData"
          :loading="loading"
          class="PersonalInfo-FlexElement"
        />
      </div>
    </white-card>
    <white-card class="PersonalInfo-WhiteCard">
      <div class="PersonalInfo-Header">Системные сведения</div>
      <div class="PersonalInfo-FlexBox">
        <template v-for="info in systemInfo">
          <data-block
            v-if="info.isShow"
            :key="get(info, 'formData.label')"
            :form-data="info.formData"
            :no-wrap="info.noWrap"
            :loading="loading"
            class="PersonalInfo-FlexElement PersonalInfo-FlexElement__NoBasis"
          />
        </template>
      </div>
    </white-card>
  </Centered1280Box>
</template>

<style lang="scss" scoped>
.PersonalInfo {
  &-WhiteCard {
    padding: 12px 16px;
    margin-bottom: 16px;
  }
  &-Header {
    font-family: 'Golos UI', sans-serif;
    font-style: normal;
    font-weight: 500;
    font-size: 20px;
    line-height: 24px;
    letter-spacing: -0.015em;
    color: rgba(2, 12, 18, 0.9);
    padding-bottom: 12px;
    margin-bottom: 20px;
    border-bottom: 1px solid rgba(1, 72, 116, 0.11);
  }

  &-FlexBox {
    width: 100%;
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    height: max-content;
  }

  &-FlexElement {
    flex-basis: calc((100% - 32px) / 4);
    flex-grow: 1;

    &__NoGrow {
      flex-grow: 0;
    }

    &__Big {
      flex-basis: inherit;
      min-width: 32%;
    }

    &__NoBasis {
      flex-basis: auto;
    }
  }

  &-Grid {
    width: 100%;
    display: grid;
    gap: 8px;
    grid-template-columns: repeat(4, 1fr);
  }

  &-Card {
    width: 100%;
  }
}
</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 } from '@/recruits/openapi/person-registry';
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 { DataForRecruit } from '@/recruits/components/recruit-card/masthead/interfaces';
import { ADDRESS_TYPES } from '@/recruits/models/Directorys/addressType';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const DocumentType = require('../../models/Directorys/DocumenType.json');
const documentTypes = getObjDict(DocumentType.documents);
const SpouseDict = require('@/recruits/models/Directorys/SpouseCodes');
const SpouseTypes = getObjDict(SpouseDict.documents);

interface FormData {
  value: string;
  label: string;
  icon?: string;
}
interface AddressToDisplay {
  id: string;
  label: string;
  value: string;
  dates: { label: string; value: string }[];
}

interface PersonalInfo {
  isShow?: boolean;
  formData: FormData;
  noWrap?: boolean;
}
interface PersonalDocument {
  key?: string;
  label?: string;
  data?: PersonalInfo[];
}
@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: DataForRecruit;

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

  // флаг для отображения блока о "Сведения о воинском учёте"
  // если статус 3 или 4, то это из очного приема и там нет инфы от ГИР
  get sourceHaveGIRInfo(): boolean {
    return !(
      this.data?.systemInfo?.source === '3' ||
      this.data?.systemInfo?.source === '4'
    );
  }

  get addressesToDisplay(): AddressToDisplay[] {
    return (
      this.data?.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),
              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 || '-'}`;
  }

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

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

  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;
  }

  get mainInfo(): PersonalInfo[] {
    return [
      {
        formData: {
          label: 'Фамилия',
          value: this.data?.mainInfo?.lastName,
        },
        isShow: true,
      },
      {
        formData: {
          label: 'Имя',
          value: this.data?.mainInfo?.firstName,
        },
        isShow: true,
      },
      {
        formData: {
          label: 'Отчество',
          value: this.data?.mainInfo?.middleName || '',
        },
        isShow: true,
      },
      {
        formData: {
          label: 'Пол',
          value: this.genderToString(this.data?.mainInfo?.gender || ''),
        },
        isShow: true,
      },
      {
        formData: {
          label: 'Дата рождения',
          value: formatDate(this.data?.mainInfo?.birthDate || ''),
          icon: 'pgs-calendar',
        },
        isShow: true,
      },
      {
        formData: {
          label: 'Место рождения',
          value: this.data?.mainInfo?.birthPlace,
          icon: 'pgs-geo',
        },
        isShow: true,
      },
      {
        formData: {
          label: 'СНИЛС',
          value: this.data?.mainInfo?.snils || '',
        },
        isShow: true,
      },
      {
        formData: {
          label: 'ИНН',
          value: String(this.data?.mainInfo?.inn || ''),
        },
        isShow: true,
      },
      {
        formData: {
          label: 'Дата смерти',
          value: formatDate(this.data?.mainInfo?.deathDate || ''),
          icon: 'pgs-calendar',
        },
        isShow: !!this.data?.mainInfo?.deathDate,
      },
      {
        formData: {
          label: 'Телефон',
          icon: 'pgs-phone',
          value: this.data?.mainInfo?.phone || '',
        },
        isShow: !!this.data?.mainInfo?.phone,
      },
      {
        formData: {
          label: 'Электронная почта',
          icon: 'pgs-mail',
          value: this.data?.mainInfo?.email || '',
        },
        isShow: !!this.data?.mainInfo?.email,
      },
    ];
  }

  get personalDocuments(): PersonalDocument[] {
    return (
      this.data?.mainInfo?.documents?.map((document, index) => ({
        key: `passport_${document.series}-${document.number}_${index}`,
        label: this.docType(document.type),
        data: [
          {
            formData: {
              label: 'Серия',
              value: document.series || '',
            },
          },
          {
            formData: {
              label: 'Номер',
              value: document.number || '',
            },
          },
          {
            formData: {
              label: 'Дата выдачи',
              value: formatDate(document.issueDate || ''),
              icon: 'pgs-calendar',
            },
          },
          {
            formData: {
              label: 'Статус документа',
              value: this.getDocumentStatus(document.status || ''),
            },
          },
          {
            formData: {
              label: 'Наименование органа, выдавшего документ',
              value: document.issueOrg || '',
            },
          },
          {
            formData: {
              label: 'Код подразделения',
              value: document.issueIdCode || '',
            },
          },
        ],
      })) || []
    );
  }

  get familyStatus(): PersonalInfo[] {
    return [
      {
        formData: {
          label: 'Семейное положение',
          value: this.spouseType(this.data?.details?.spouse?.status || ''),
        },
      },
      {
        formData: {
          label: 'Количество детей до 18 лет',
          icon: 'pgs-people',
          value: String(this.data?.details?.spouse?.countLittleChildren),
        },
      },
      {
        formData: {
          label: 'Дата, до которой актуально количество детей до 18 лет',
          icon: 'pgs-calendar',
          value: formatDate(this.data?.details?.spouse?.dateActualTo || ''),
        },
      },
    ];
  }

  get militaryRegistrationInfo(): PersonalInfo[] {
    return [
      {
        formData: {
          label: 'Сведения о воинском учёте',
          value: this.data?.recruitSystemInfo?.militaryRegistrationFlag
            ? 'Cостоит'
            : 'Не состоит ',
        },
        isShow: this.sourceHaveGIRInfo,
      },
      {
        formData: {
          label: 'Дата постановки на учёт',
          icon: 'pgs-calendar',
          value: formatDate(
            this.data?.systemInfo?.militaryRegistrationDate || ''
          ),
        },
        isShow: !!this.data?.systemInfo?.militaryRegistrationDate,
      },
      {
        formData: {
          label: 'Дата снятия с учёта',
          icon: 'pgs-calendar',
          value: formatDate(this.data?.mainInfo?.vuUnsetDate || ''),
        },
        isShow: !!this.data?.mainInfo?.vuUnsetDate,
      },
      {
        formData: {
          label: 'Получено согласие на обработку персональных данных',
          icon: 'pgs-roll',
          value: this.data?.stateRecruit?.personalDataProcessingAgreeConfirmed
            ? 'Получено'
            : 'Не получено',
        },
        isShow: true,
      },
      {
        formData: {
          label: 'Причина постановки на учёт',
          value: this.registrationReasons,
        },
        isShow: !!this.registrationReasons,
      },
      {
        formData: {
          label: 'Военный комиссариат',
          icon: 'pgs-army',
          value: this.militaryDepartmentName,
        },
        isShow: !!(
          this.data?.recruitSystemInfo?.militaryRegistrationFlag &&
          this.militaryDepartmentName
        ),
      },
      {
        formData: {
          label: 'Код военного комиссариата',
          value: this.data?.recruitSystemInfo?.departmentCode || '',
        },
        isShow: !!this.data?.recruitSystemInfo?.departmentCode,
      },
      {
        formData: {
          label: 'Военный идентификатор',
          value: this.data?.systemInfo?.docId || '',
        },
        isShow: !!this.data?.systemInfo?.docId,
      },
      {
        formData: {
          label: 'Дата присвоения военного идентификатора',
          icon: 'pgs-calendar',
          value: formatDate(this.data?.systemInfo?.docIdDate || ''),
        },
        isShow: !!this.data?.systemInfo?.docIdDate,
      },
      {
        formData: {
          label: 'Сведения о факте выдачи документа воинского учёта',
          value: this.data?.details?.militaryInfo?.militaryDocument
            ? 'Выдан'
            : 'Не выдан',
        },
        isShow: true,
      },
      {
        formData: {
          icon: 'pgs-calendar',
          label: 'Дата выдачи документа воинского учёта',
          value: formatDate(
            this.data?.details?.militaryInfo?.militaryDocumentDate || ''
          ),
        },
        isShow: !!this.data?.details?.militaryInfo?.militaryDocumentDate,
      },
    ];
  }

  get systemInfo(): PersonalInfo[] {
    return [
      {
        formData: {
          label: 'Идентификатор ЕРН',
          value: this.data?.systemInfo?.idERN || 'Отсутствует',
        },
        isShow: true,
      },
      {
        formData: {
          label: 'Идентификатор ЕСИА',
          value: this.data?.systemInfo?.esiaId,
        },
        isShow: !!this.data?.systemInfo?.esiaId,
      },
      {
        formData: {
          label: 'Источник данных',
          value: this.source(this.data?.systemInfo?.source || ''),
          icon: 'pgs-database',
        },
        isShow: !!this.data?.systemInfo?.source,
      },
      {
        formData: {
          label: 'Идентификатор файла по конвертации гражданина',
          value: this.data?.systemInfo?.idPack || '',
        },
        isShow: !!this.data?.systemInfo?.idPack,
      },
      {
        noWrap: true,
        formData: {
          label:
            'Наименование источника сведений, на основании которого создана запись',
          value: this.data?.systemInfo?.sourceFileName || '',
        },
        isShow: !!this.data?.systemInfo?.sourceFileName,
      },
      {
        noWrap: true,
        formData: {
          label:
            'Наименование источника сведений, на основании которого создана запись',
          value: this.data?.systemInfo?.sourceApplicationNumber || '',
        },
        isShow: !!this.data?.systemInfo?.sourceApplicationNumber,
      },
      {
        formData: {
          label: 'Дата создания карточки',
          value: formatDate(this.data?.systemInfo?.createdAt || ''),
          icon: 'pgs-calendar',
        },
        isShow: !!this.data?.systemInfo?.createdAt,
      },
      {
        noWrap: true,
        formData: {
          label: 'Идентификатор записи о гражданине в РВУ',
          value: this.data?.systemInfo?.humanOrientedId || '',
        },
        isShow: !!this.data?.systemInfo?.humanOrientedId,
      },
    ];
  }

  get postponement(): PersonalInfo {
    return {
      formData: {
        label: 'Код отсрочки или освобождения',
        value: String(
          this.data?.details?.postponements?.[0]?.postponementCode || ''
        ),
      },
      isShow: !!this.data?.details?.postponements?.[0]?.postponementCode,
    };
  }
}
</script>
