<template>
  <div>
    <Centered1280Box class="AccountOrganization">
      <WhiteCard class="AccountOrganization__WhiteCard">
        <div class="AccountOrganization__Header">
          <div class="AccountOrganization__HeaderText">Учётная запись</div>
          <r-btn
            v-if="$AC.haveScope($AC.scopes.SECURITY_ADMINISTRATOR)"
            action
            label="Редактировать"
            @click="editingAccount = data"
          />
        </div>
        <div class="AccountOrganization__FlexBox">
          <DataBlock
            v-if="domain"
            :form-data="{
              label: 'Организация',
            }"
            :loading="loading"
            class="AccountOrganization__FlexElement AccountOrganization__FlexElement_Big"
          >
            <q-skeleton v-if="loading" style="width: 50%" />
            <q-chip v-if="domain" clickable icon="work_outline" @click="goTo">
              {{ domain }}
            </q-chip>
          </DataBlock>
          <DataBlock
            v-if="account.position"
            :form-data="{
              label: 'Должность',
              value: account.position,
            }"
            :loading="loading"
            class="AccountOrganization__FlexElement AccountOrganization__FlexElement_Big"
          />
          <DataBlock
            v-if="domainType === 'Organization' || 'Department'"
            :form-data="{
              label: 'Подразделение',
              value: departmentName,
            }"
            :loading="loading"
            class="AccountOrganization__FlexElement AccountOrganization__FlexElement_Big"
          />
          <DataBlock
            v-if="preferredDomainName"
            :form-data="{
              label: 'Подразделение для авторизации',
            }"
            :loading="loading"
            class="AccountOrganization__FlexElement AccountOrganization__FlexElement_Big"
          >
            <q-skeleton v-if="loading" style="width: 50%" />
            {{ preferredDomainName }}
            <q-btn
              dense
              round
              icon="close"
              @click="dialogDelete = true"
            ></q-btn>
          </DataBlock>
          <DataBlock
            :form-data="{
              label: 'Логин',
            }"
            :loading="loading"
            class="AccountOrganization__FlexElement"
          >
            <q-skeleton v-if="loading" style="width: 50%" />
            <span
              v-for="credential in credentials"
              :key="credential.id"
              class="q-mr-sm"
            >
              {{ credential.userName }}
            </span>
            <span v-if="!credentials.length">-</span>
          </DataBlock>
          <DataBlock
            :form-data="{
              label: 'Активен',
              value: account.enabled ? 'Да' : 'Нет',
            }"
            :loading="loading"
            class="AccountOrganization__FlexElement"
          />
          <DataBlock
            :form-data="{
              label: 'Заблокирован',
              value: isBlockedCredential ? 'Да' : 'Нет',
            }"
            :loading="loading"
            class="AccountOrganization__FlexElement"
          />
          <DataBlock
            :form-data="{
              label: 'Дата и время активации',
              value: convertDateFromBackendFormat(account.start) || '-',
            }"
            :loading="loading"
            class="AccountOrganization__FlexElement"
          />
          <DataBlock
            :form-data="{
              label: 'Дата и время отключения',
              value: convertDateFromBackendFormat(account.finish) || '-',
            }"
            :loading="loading"
            class="AccountOrganization__FlexElement"
          />
        </div>
      </WhiteCard>
    </Centered1280Box>
    <operation-dialog
      persistent
      sign
      ref="dialog"
      :title="accountFIO"
      sub="Подтверждение действия"
      v-model="dialogDelete"
      @hide="dialogDelete = false"
    >
      <q-spinner
        color="primary"
        size="50px"
        :thickness="2"
        v-if="loading"
      ></q-spinner>
      <div v-else>Вы действительно хотите удалить информацию?</div>

      <template #left-actions-panel>
        <r-btn outline label="Отмена" positive @click="dialogDelete = false" />
      </template>
      <template #right-actions-panel>
        <r-btn
          outline
          label="Подтверждение"
          negative
          @click="deletePreferredDomainId"
        />
      </template>
    </operation-dialog>
    <EditModal
      :account="editingAccount"
      @close="editingAccount = null"
      @refresh="updateAccountData"
    />
  </div>
</template>

<script lang="ts">
import { convertDateFromBackendFormat } from '@utils/format-date';
import {
  DepartmentApi,
  Organization,
  Credential,
  PersonProfileApi,
} from '@openapi/idm';
import { Account } from '@interfaces/entities/Account';
import get from 'lodash/get';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { DepartmentWithParent } from '@models/DepartmentWithParent';
import { USER_SCOPES } from '@constants/entities/Scope';
import { notifyError } from '@utils/notify';
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';

const departmentApi = new DepartmentApi();
const personProfileApi = new PersonProfileApi();

const DEPARTMENT = 'Department';
const ORGANIZATION = 'Organization';

@Component({
  components: {
    Centered1280Box,
    DataBlock,
    WhiteCard,
    EditModal,
  },
  methods: {
    convertDateFromBackendFormat,
  },
  props: ['data', 'loading'],
})
export default class OrganizationTab extends Vue {
  @Prop({}) private data: Account;
  @Prop({}) private loading: boolean;

  private parent: Organization | null = null;
  private account: any = {
    dialogDelete: false,
    position: '',
    finish: '',
    start: '',
    enabled: false,
    userDomain: null,
    preferredDomainName: '',
    preferredId: '',
  };

  editingAccount = null;

  private loadBtn = false;
  private dialogDelete = false;

  private USER_SCOPES = USER_SCOPES;

  private get credentials(): Array<Credential> {
    return this.data?.credentials || [];
  }

  private get domainType(): string {
    return get(this.data, 'userDomain.schema', '');
  }

  private get accountFIO(): string {
    return this.data?.person?.fio || 'Карточка сотрудника';
  }

  // для организации получаем fullname, для департамента - parent.fullname
  private get domain(): string {
    return this.domainType === DEPARTMENT
      ? this.parent?.fullname || ''
      : this.account.userDomain?.fullname || '';
  }

  private get departmentName(): string {
    return this.domainType === DEPARTMENT
      ? this.account.userDomain?.fullname || '-'
      : '-';
  }

  // computed для удобства обращения к имени подразделения для авторизации
  private get preferredDomainName(): string {
    return this.account.preferredDomainName || '';
  }

  // функция для снятия выбора подразделения для авторизации
  private async deletePreferredDomainId(): Promise<void> {
    if (!this.account.preferredId) {
      notifyError(
        'Возникла ошибка при получении информации о подразделении для авторизации'
      );
      return;
    }
    this.loadBtn = true;
    try {
      await personProfileApi.updatePersonProfile([
        {
          id: this.account.preferredId,
          preferredDomainId: '',
        },
      ]);
      this.account.preferredDomainName = '';
      this.dialogDelete = false;
    } catch (err: any) {
      notifyError(err.toString());
    }
    this.loadBtn = false;
  }

  // функция проверки есть ли хоть один заблоикрованный акканут
  private get isBlockedCredential(): boolean {
    const credentials = this.data?.credentials?.filter((credential) => {
      return credential.schema === 'LocalCredential' && credential.blocked;
    });
    return !!credentials?.length;
  }

  @Watch('data', {
    immediate: true,
  })
  dataWatcher(val: Account): void {
    if (val) {
      this.account.position = val.position || '';
      this.account.finish = val.finish || '';
      this.account.start = val.start || '';
      this.account.enabled = !!val.enabled;
      if (val?.userDomain?.id) {
        this.account.userDomain = val.userDomain;
        this.getDepartmentParent(this.account.userDomain.id);
        this.getDepartmentDefault();
      }
    }
  }

  // функция для получения подразделения для авторизации
  async getDepartmentDefault(): Promise<void> {
    // нет проверки на наличие подразделения т.к. его может не быть и ответ 404 норма
    // по person.id получаем айди подразделения для авторизации
    const responsePersonById = await personProfileApi.getPersonProfileByPersonId(
      this.data.person.id
    );
    try {
      const preferredDomainId: string | undefined =
        responsePersonById.data.preferredDomainId;

      if (!preferredDomainId) {
        return;
      }

      this.account.preferredId = responsePersonById.data.id;

      // по айди подразделения для авторизации получаем его имя
      const { data } = await departmentApi.getDepartment(preferredDomainId);
      this.account.preferredDomainName =
        data.fullname || data.shortname || data.name || '';
    } catch (err: any) {
      notifyError(err.toString());
    }
  }

  private async getDepartmentParent(id: string): Promise<void> {
    if (this.domainType === DEPARTMENT) {
      const response = await departmentApi.getDepartment(id, 'parent');
      const data = response?.data as DepartmentWithParent;
      this.parent = data.parent ?? null;
    }
  }

  private goTo(): void {
    switch (this.domainType) {
      case ORGANIZATION:
        this.$router.push({
          name: 'organization',
          params: {
            id: this.account.userDomain.id,
          },
        });
        break;
      case DEPARTMENT:
        if (this.parent?.id) {
          this.$router.push({
            name: 'organization',
            params: {
              id: this.parent.id,
            },
          });
        }
        break;
      default:
    }
  }

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

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