<template>
  <div>
    <Centered1280Box class="Account">
      <WhiteCard class="Account__WhiteCard">
        <div class="Account__Header">
          <div class="Account__HeaderText">Основные данные</div>
          <r-btn
            v-if="$AC.haveScope($AC.scopes.SECURITY_ADMINISTRATOR)"
            action
            label="Редактировать"
            @click="editingAccount = data"
          />
        </div>
        <div class="Account__FlexBox">
          <DataBlock
            :form-data="{
              label: 'Фамилия',
              value: surname || '-',
            }"
            :loading="loading"
            class="Account__FlexElement"
          />
          <DataBlock
            :form-data="{
              label: 'Имя',
              value: firstname || '-',
            }"
            :loading="loading"
            class="Account__FlexElement"
          />
          <DataBlock
            :form-data="{
              label: 'Отчество',
              value: middlename || '-',
            }"
            :loading="loading"
            class="Account__FlexElement"
          />
          <DataBlock
            :form-data="{
              label: 'Пол',
              value: sexValue || '-',
            }"
            :loading="loading"
            class="Account__FlexElement"
          />
          <DataBlock
            :form-data="{
              label: 'Дата рождения',
              value: birthdate || '-',
            }"
            :loading="loading"
            class="Account__FlexElement"
          />
          <DataBlock
            :form-data="{
              label: 'СНИЛС',
              value: snils || '-',
            }"
            :loading="loading"
            class="Account__FlexElement"
          />
          <DataBlock
            v-if="showIpAddress"
            :form-data="{
              label: 'IP-адрес',
              value: ipAddress || '-',
            }"
            :loading="loading"
            class="Account__FlexElement"
          />
          <DataBlock
            v-if="!isErvuMode"
            :form-data="{
              label: 'Адрес электронной почты',
              value: showingEmail || '-',
            }"
            :loading="loading"
            class="Account__FlexElement"
          />
          <!-- <td
            class="q-pa-none gt-sm"
            rowspan="6"
            style="min-width: 200px; text-align: right; vertical-align: top"
          >
            <div>
              <q-avatar v-if="photo" size="200px">
                <img :src="photo" />
              </q-avatar>
              <q-avatar
                v-else
                color="grey-1"
                font-size="64px"
                icon="person"
                size="200px"
                text-color="grey"
              />
            </div>
          </td> -->
        </div>
      </WhiteCard>
    </Centered1280Box>
    <EditModal
      :account="editingAccount"
      @close="editingAccount = null"
      @refresh="updateAccountData"
    />
  </div>
</template>

<script lang="ts">
import { DateFormat } from '@constants/utils/format-date';
import { convertDateFromBackendFormat } from '@utils/format-date';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { Account } from '@interfaces/entities/Account';
import get from 'lodash/get';
import { USER_SCOPES, ERVU_SCOPES } from '@/constants/entities/Scope';
import Centered1280Box from '@/recruits/components/common/centered-1280-box.vue';
import DataBlock from '@components/cards/statements/components/dataBlock.vue';
import WhiteCard from '@/recruits/components/common/white-card.vue';
import EditModal from './EditModal.vue';

@Component({
  components: {
    Centered1280Box,
    DataBlock,
    WhiteCard,
    EditModal,
  },
  methods: {
    convertDateFromBackendFormat,
    get,
  },
  props: ['data', 'loading'],
})
export default class AccountBaseCard extends Vue {
  @Prop({ default: {} }) private data: Account;
  @Prop({}) private loading: boolean;
  private DateFormat = DateFormat;
  private birthdate = '';
  private email = '';
  private firstname = '';
  private middlename = '';
  private photo = '';
  private sex = '';
  private snils = '';
  private surname = '';
  private workMail = '';
  private ipAddress = '';
  private USER_SCOPES = USER_SCOPES;

  isErvuMode = this.$AC.haveOneOfScope(Object.values(ERVU_SCOPES));

  editingAccount = null;

  private get sexValue(): string {
    switch (String(this.sex).toLowerCase()) {
      case 'male':
        return 'Мужской';
      case 'female':
        return 'Женский';
      default:
        return this.sex || '';
    }
  }

  @Watch('data', {
    immediate: true,
  })
  dataWatcher(val: Account): void {
    if (val && val.person) {
      if (val.person.birthdate) {
        this.birthdate = convertDateFromBackendFormat(
          val.person.birthdate,
          DateFormat.date
        );
      } else {
        this.birthdate = '';
      }

      this.email = val.person.email || '';
      this.firstname = val.person.firstname || '';
      this.middlename = val.person.middlename || '';
      this.surname = val.person.surname || '';
      this.photo = val.person.photo || '';
      this.sex = val.person.sex || '';
      this.workMail = val.workMail || '';

      const ipAddresses: string[] = get(val, 'person.ipAddresses', []);
      this.ipAddress = ipAddresses.length ? ipAddresses[0] : '';

      const snils = get(val, 'person.snils');
      this.snils =
        snils.replace(/^(\d{3})(\d{3})(\d{3})(\d{2}).*/, '$1-$2-$3 $4') || '';
    }
  }

  get showingEmail(): string {
    return this.workMail?.length ? this.workMail : this.email;
  }

  /*
   * Показываем поле ip если есть ip-адрес и локальный пользователь и есть роль SECURITY_ADMINISTRATOR
   */
  get showIpAddress(): boolean {
    const localCredentials =
      this.data?.credentials?.filter(
        (credential) => credential.schema === 'LocalCredential'
      ) || [];
    return (
      !!this.ipAddress &&
      this.$AC.haveScope(this.$AC.scopes.SECURITY_ADMINISTRATOR) &&
      !!localCredentials.length
    );
  }

  updateAccountData(): void {
    this.$emit('refresh');
    this.editingAccount = null;
  }
}
</script>

<style lang="scss" scoped>
.Account {
  &__WhiteCard {
    padding: 12px 16px;
    margin-bottom: 16px;
  }
  &__Header {
    padding-bottom: 12px;
    margin-bottom: 20px;
    border-bottom: 1px solid rgba(1, 72, 116, 0.11);
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  &__HeaderText {
    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);
  }

  &__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: calc((100% - 32px) / 2);
    }

    &_NoBasis {
      flex-basis: auto;
    }
  }

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

  &__Card {
    width: 100%;
  }
}
</style>
