<template>
  <div>
    <Centered1280Box class="Department">
      <WhiteCard class="Department__WhiteCard">
        <div class="Department__Header">
          <div class="Department__HeaderText">Основные данные</div>
          <r-btn
            v-if="$AC.haveScope($AC.scopes.SECURITY_ADMINISTRATOR)"
            action
            label="Редактировать"
            @click="editDepartment = model"
          />
        </div>
        <div class="Department__FlexBox">
          <DataBlock
            :form-data="{
              label: 'Полное наименование',
              value: model.fullname,
            }"
            :loading="loading"
            class="Department__FlexElement Department__FlexElement_Big"
          />
          <DataBlock
            v-if="model.shortname"
            :form-data="{
              label: 'Сокращённое наименование',
              value: model.shortname,
            }"
            :loading="loading"
            class="Department__FlexElement Department__FlexElement_Big"
          />
          <DataBlock
            v-if="model.militaryCode"
            :form-data="{
              label: 'Код военного комиссариата',
              value: model.militaryCode,
            }"
            :loading="loading"
            class="Department__FlexElement"
          />
          <DataBlock
            v-if="!isErvuMode"
            :form-data="{
              label: 'ID ведомства ЕПГУ',
              value: model.tnsDepartmentId,
            }"
            :loading="loading"
            class="Department__FlexElement"
          />
          <DataBlock
            v-if="!isErvuMode"
            :form-data="{
              label: 'ДНС',
              value: model.dns,
            }"
            :loading="loading"
            class="Department__FlexElement"
          />
          <DataBlock
            :form-data="{
              label: 'Адрес',
              value: model.address || '–',
            }"
            :loading="loading"
            class="Department__FlexElement Department__FlexElement_Big"
          />
          <DataBlock
            :form-data="{
              label: 'Почтовый адрес',
              value: model.postalAddress || '–',
            }"
            :loading="loading"
            class="Department__FlexElement Department__FlexElement_Big"
          />
          <DataBlock
            :form-data="{
              label: 'Номер телефона',
              value: model.phone || '–',
            }"
            :loading="loading"
            class="Department__FlexElement"
          />
          <DataBlock
            :form-data="{
              label: 'Часовой пояс',
              value: model.timezone || '–',
            }"
            :loading="loading"
            class="Department__FlexElement"
          />
          <DataBlock
            v-if="!isErvuMode"
            :form-data="{
              label: 'Адрес электронной почты',
              value: model.email,
            }"
            :loading="loading"
            class="Department__FlexElement"
          />
          <DataBlock
            v-if="model.parent"
            :form-data="{
              label: 'Вышестоящая организация',
            }"
            :loading="loading"
            class="Department__FlexElement Department__FlexElement_Big"
          >
            <q-skeleton v-if="loading" width="50%" />
            <q-chip
              v-else
              clickable
              @click="goToOrganization"
              icon="work_outline"
            >
              {{ organizationName }}
            </q-chip>
          </DataBlock>
          <DataBlock
            v-if="isDepartment"
            :form-data="{
              label: 'Вышестоящее подразделение',
            }"
            :loading="loading"
            class="Department__FlexElement Department__FlexElement_Big"
          >
            <q-skeleton v-if="loading" width="50%" />
            <q-chip
              v-else
              :clickable="$AC.haveScope($AC.scopes.SECURITY_ADMINISTRATOR)"
              @click="goToDepartment"
              icon="work_outline"
            >
              {{ model.parent.fullname }}
            </q-chip>
          </DataBlock>
          <DataBlock
            :form-data="{
              label: 'Включать в отчеты',
              value: reportsEnabled ? 'Да' : 'Нет',
            }"
            :loading="loading"
            class="Department__FlexElement"
          />
        </div>
      </WhiteCard>
    </Centered1280Box>
    <EditModal
      :department="editDepartment"
      @close="editDepartment = null"
      @refresh="updateDepartment"
    />
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { DepartmentApi } from '@openapi/idm';
import { notifyError } from '@utils/notify';
import { ERVU_SCOPES } from '@constants/entities/Scope';
import { DepartmentWithParent } from '@/models/DepartmentWithParent';
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 './Basic/EditModal.vue';

const departmentApi = new DepartmentApi();

@Component({
  components: {
    Centered1280Box,
    DataBlock,
    WhiteCard,
    EditModal,
  },
})
export default class DepartmentCardBasic extends Vue {
  @Prop({}) private model: DepartmentWithParent;
  @Prop({}) private loading: boolean;

  private parentDepartment: any = null;

  reportsEnabled = false;

  editDepartment: DepartmentWithParent | null = null;

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

  @Watch('isDepartment', { immediate: true })
  private getDepartment(isDepartment: boolean): void {
    if (isDepartment) {
      this.getParentDepartment();
    }
  }

  @Watch('model.reportsEnabled', { immediate: true })
  private getReportsEnabled(reportsEnabled: boolean): void {
    this.reportsEnabled = reportsEnabled;
  }

  get isDepartment(): boolean {
    return this.model?.parent?.schema?.toLowerCase() === 'department';
  }

  get organizationName(): string {
    return this.isDepartment
      ? this.parentDepartment.parent.fullname
      : this.model.parent.fullname;
  }

  private async getParentDepartment(): Promise<void> {
    try {
      const response = await departmentApi.getDepartment(
        this.model?.parent?.id,
        'parent'
      );
      this.parentDepartment = response.data;
    } catch (e: any) {
      notifyError(e.toString());
    }
  }

  private goToDepartment(): void {
    this.$router.push({
      name: 'department',
      params: {
        id: this.model?.id,
      },
    });
  }

  private updateDepartment(): void {
    this.editDepartment = null;
    this.$emit('refresh');
  }

  private goToOrganization(): void {
    this.$router.push({
      name: 'organization',
      params: {
        id: this.parentDepartment
          ? this.parentDepartment.parent.id
          : this.model?.parent?.id,
      },
    });
  }
}
</script>

<style lang="scss" scoped>
.Department {
  &__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>
