<template>
  <div>
    <Centered1280Box class="Organization">
      <WhiteCard class="Organization__WhiteCard">
        <div class="Organization__Header">
          <div class="Organization__HeaderText">Основные данные</div>
          <r-btn
            v-if="$AC.haveScope($AC.scopes.SECURITY_ADMINISTRATOR)"
            action
            label="Редактировать"
            @click="editOrg = model"
          />
        </div>
        <div class="Organization__FlexBox">
          <DataBlock
            :form-data="{
              label: 'Полное наименование',
              value: model.fullname || '-',
            }"
            :loading="loading"
            class="Organization__FlexElement Organization__FlexElement_Big"
          />
          <DataBlock
            v-if="model.shortname"
            :form-data="{
              label: 'Сокращённое наименование',
              value: model.shortname,
            }"
            :loading="loading"
            class="Organization__FlexElement Organization__FlexElement_Big"
          />
          <DataBlock
            v-if="model.militaryCode"
            :form-data="{
              label: 'Код военного комиссариата',
              value: model.militaryCode,
            }"
            :loading="loading"
            class="Organization__FlexElement"
          />
          <DataBlock
            v-if="model.leg"
            :form-data="{
              label: 'ОПФ',
              value: model.leg,
            }"
            :loading="loading"
            class="Organization__FlexElement"
          />
          <DataBlock
            v-if="!isErvuMode && model.dns"
            :form-data="{
              label: 'ДНС',
              value: model.dns,
            }"
            :loading="loading"
            class="Organization__FlexElement"
          />
          <DataBlock
            v-if="model.address"
            :form-data="{
              label: 'Адрес',
              value: model.address,
            }"
            :loading="loading"
            class="Organization__FlexElement Organization__FlexElement_Big"
          />
          <DataBlock
            v-if="model.postalAddress"
            :form-data="{
              label: 'Почтовый адрес',
              value: model.postalAddress,
            }"
            :loading="loading"
            class="Organization__FlexElement Organization__FlexElement_Big"
          />
          <DataBlock
            v-if="regionName"
            :form-data="{
              label: 'Субъект РФ',
              value: regionName,
            }"
            :loading="loading"
            class="Organization__FlexElement Organization__FlexElement_Big"
          />
          <DataBlock
            v-if="model.tnsDepartmentId"
            :form-data="{
              label: 'ID ведомства (ЕПГУ)',
              value: model.tnsDepartmentId,
            }"
            :loading="loading"
            class="Organization__FlexElement"
          />
          <DataBlock
            v-if="model.orgDate"
            :form-data="{
              label: 'Дата гос. регистрации организации',
              value: model.orgDate,
            }"
            :loading="loading"
            class="Organization__FlexElement"
          />
          <DataBlock
            v-if="orgType"
            :form-data="{
              label: 'Тип организации',
              value: orgType,
            }"
            :loading="loading"
            class="Organization__FlexElement"
          />
          <DataBlock
            :form-data="{
              label: 'ИНН',
              value: model.inn || '-',
            }"
            :loading="loading"
            class="Organization__FlexElement"
          />
          <DataBlock
            v-if="model.ogrn"
            :form-data="{
              label: 'ОГРН',
              value: model.ogrn,
            }"
            :loading="loading"
            class="Organization__FlexElement"
          />
          <DataBlock
            v-if="model.oktmo"
            :form-data="{
              label: 'ОКТМО',
              value: model.oktmo,
            }"
            :loading="loading"
            class="Organization__FlexElement"
          />
          <DataBlock
            v-if="model.kpp"
            :form-data="{
              label: 'КПП',
              value: model.kpp,
            }"
            :loading="loading"
            class="Organization__FlexElement"
          />
          <DataBlock
            v-if="model.phone"
            :form-data="{
              label: 'Номер телефона',
              value: model.phone,
            }"
            :loading="loading"
            class="Organization__FlexElement"
          />
          <DataBlock
            v-if="model.email"
            :form-data="{
              label: 'Адрес электронной почты',
              value: model.email,
            }"
            :loading="loading"
            class="Organization__FlexElement"
          />
          <DataBlock
            :form-data="{
              label: 'Часовой пояс',
              value: model.timezone || '-',
            }"
            :loading="loading"
            class="Organization__FlexElement"
          />
          <DataBlock
            v-if="parentOrganizationValue"
            :form-data="{
              label: 'Вышестоящая организация',
            }"
            :loading="loading"
            class="Organization__FlexElement Organization__FlexElement_Big"
          >
            <q-skeleton v-if="loading" width="50%" />
            <q-chip
              v-else
              clickable
              @click="goToParentOrganization"
              icon="work_outline"
            >
              {{ parentOrganizationValue }}
            </q-chip>
          </DataBlock>
          <DataBlock
            :form-data="{
              label: 'Нижестоящие организации',
            }"
            :loading="loading"
            class="Organization__FlexElement Organization__FlexElement_Big"
          >
            <q-skeleton v-if="loading" style="width: 50%" />
            <div
              v-else-if="!organizationsChild || organizationsChild.length === 0"
            >
              Не выбрано
            </div>
            <div v-else class="Organization__ListOrganizations">
              <q-chip
                v-for="child in organizationsChild"
                :key="child.id"
                clickable
                @click="goToOrganization(child.id)"
                icon="work_outline"
              >
                {{ child.label }}
              </q-chip>
            </div>
          </DataBlock>
          <DataBlock
            :form-data="{
              label: 'Блокировка',
              value: model.enabled ? 'Разблокирована' : 'Заблокирована',
            }"
            :loading="loading"
            class="Organization__FlexElement"
          />
          <DataBlock
            :form-data="{
              label: 'Включать в отчеты',
              value: model.reportsEnabled ? 'Да' : 'Нет',
            }"
            :loading="loading"
            class="Organization__FlexElement"
          />
          <DataBlock
            v-if="!isErvuMode"
            :form-data="{
              label: 'Сертификат',
            }"
            :loading="loading"
            class="Organization__FlexElement Organization__FlexElement_Big"
          >
            <q-skeleton v-if="loading" style="width: 50%" />
            <q-item v-else>
              <q-item-section>
                <a ref="download" download="certificate.cer" />
                <q-btn
                  outline
                  rounded
                  icon="article"
                  label="Скачать"
                  :disable="!certFile"
                  style="max-width: 160px"
                  @click="downloadCert"
                />
              </q-item-section>
            </q-item>
          </DataBlock>
        </div>
      </WhiteCard>
    </Centered1280Box>
    <EditModal
      :organization="editOrg"
      @refresh="$emit('refresh')"
      @close="editOrg = null"
    />
  </div>
</template>

<script lang="ts">
import { saveFileViaLink } from '@utils/files';
import { RegionApi, DomainApi } from '@openapi/idm';
import { 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 { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { OrganizationWithParent } from '@/models/OrganizationWithParent';
import EditModal from './Basic/EditModal.vue';
import get from 'lodash/get';

const domainApi = new DomainApi();
const regionApi = new RegionApi();

interface elTree {
  id: string;
  label: string;
  children?: elTree;
}

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

  organizationsChild: elTree[] | null = null;

  editOrg: OrganizationWithParent | null = null;

  get isErvuMode(): boolean {
    return this.$AC.haveOneOfScope(Object.values(ERVU_SCOPES));
  }

  get certFile(): string | undefined {
    if (this.model.certificate) {
      const bs = atob(this.model.certificate);
      const buffer = new ArrayBuffer(bs.length);
      const ba = new Uint8Array(buffer);
      for (let i = 0; i < bs.length; i++) {
        ba[i] = bs.charCodeAt(i);
      }
      const blob = new Blob([ba], { type: 'application/x-x509-ca-cert' });
      const url = window.URL.createObjectURL(blob);
      return url;
    }
    return undefined;
  }

  // computed получение родительской организации
  get parentOrganizationValue(): string {
    if (this.model?.parent?.schema === 'Organization') {
      return this.model.parent.fullname || this.model.parent.name || '';
    } else {
      return '';
    }
  }

  // Блок работы с регионом
  regionName = '';

  private async updateRegionName(): Promise<void> {
    const regionId = this.model.region || this.model.parent?.region;
    if (!regionId) {
      this.regionName = '';
      return;
    }
    await regionApi.getRegion(regionId).then(({ data }) => {
      this.regionName = data.fullname || data.name || '';
    });
  }

  @Watch('model.region', { immediate: true })
  private handlerModelRegion(): void {
    this.updateRegionName();
  }

  @Watch('model.parent.region')
  private handlerModelParentRegion(): void {
    this.updateRegionName();
  }
  // Конец блока работы с регионом

  // computed получение типа организации
  get orgType(): string {
    return this.model.govOrganizationType
      ? this.$store.getters[
          'registryService/referenceBooks/appliedReferenceBook'
        ]({
          key: this.model.govOrganizationType,
          id: 'rosregister_declarant_kind',
          valueName: 'label',
        }).value
      : '';
  }

  private downloadCert(): void {
    saveFileViaLink({
      anchor: this.$refs.download as HTMLAnchorElement,
      hrefData: this.certFile,
    });
  }

  private goToOrganization(orgId: string): void {
    this.$router.push({
      name: 'organization',
      params: {
        id: orgId,
      },
    });
  }

  private goToParentOrganization(): void {
    if (this.model?.parent?.id) {
      this.$router.push({
        name: 'organization',
        params: {
          id: this.model.parent.id,
        },
      });
    } else {
      this.$q.notify({
        color: 'negative',
        icon: 'error',
        message: 'Не удалось открыть вышестоящую организацию',
      });
    }
  }

  async initTree(): Promise<void> {
    try {
      const { data } = await domainApi.getDomainChildrenTreeV1(
        this.$route.params.id,
        1,
        ['Organization']
      );
      if (data?.leafs?.length) {
        // item: any т.к. из запроса возвращается NodeTO (Organization | Department | Region)
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const getTreeStructure = (item: any) => {
          const returnObj: elTree = {
            id: item.value.id,
            label: item.value.fullname || item.value.name,
          };
          if (item.leafs && item.leafs instanceof Array) {
            // item: any т.к. из запроса возвращается NodeTO (Organization | Department | Region)
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            returnObj.children = item.leafs.map((item: any) => {
              return getTreeStructure(item);
            });
          }
          return returnObj;
        };

        this.organizationsChild = data.leafs.map(getTreeStructure);
      }
    } catch {
      this.$q.notify({
        color: 'negative',
        icon: 'error',
        message: 'Не удалось загрузить нижестоящие организации',
      });
    }
  }

  mounted(): void {
    this.initTree();
  }
}
</script>

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

  &__ListOrganizations {
    overflow-y: auto;
    max-height: 20vh;
  }

  &__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>
