<template>
  <div>
    <Centered1280Box class="OrganizationStructure">
      <WhiteCard class="OrganizationStructure__WhiteCard">
        <div class="OrganizationStructure__Header">
          <div class="OrganizationStructure__HeaderText">
            Иерархия подразделений
          </div>
          <r-btn
            v-if="$AC.haveScope($AC.scopes.SECURITY_ADMINISTRATOR)"
            action
            label="Добавить подразделение"
            @click="parentOrg = model"
          />
        </div>
        <div class="OrganizationStructure__Tree">
          <q-inner-loading :showing="initLoading">
            <q-spinner-gears color="primary" size="50px" />
          </q-inner-loading>
          <q-tree
            v-if="!initLoading"
            node-key="id"
            ref="tree"
            selected-color="grey-9"
            text-color="grey-7"
            :nodes="departments"
            :selected.sync="selected"
          />
        </div>
      </WhiteCard>
    </Centered1280Box>
    <CreateModal
      :organization="parentOrg"
      @refresh="initDepartments"
      @close="parentOrg = null"
    />
  </div>
</template>

<script lang="ts">
import { NodeTO, DomainApi } from '@openapi/idm';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import get from 'lodash/get';
import Centered1280Box from '@/recruits/components/common/centered-1280-box.vue';
import WhiteCard from '@/recruits/components/common/white-card.vue';
import { OrganizationWithParent } from '@/models/OrganizationWithParent';
import CreateModal from './Departments/CreateModal.vue';

const domainApi = new DomainApi();

interface DepartmentToTree {
  id: string | undefined;
  label: string | undefined;
  children?: DepartmentToTree[];
}

@Component({
  components: {
    Centered1280Box,
    WhiteCard,
    CreateModal,
  },
})
export default class OrganizationCardStructure extends Vue {
  @Prop() model: OrganizationWithParent;

  private initLoading = false;
  private departments: DepartmentToTree[] = [];
  private selected = '';

  @Watch('model', { immediate: true })
  private setDepartments(val: any): void {
    if (val?.departments) {
      this.departments = val.departments;
    }
  }

  @Watch('selected', { immediate: true })
  private goTo(val: string) {
    if (val) {
      const departments: DepartmentToTree[] = this.departments.filter(
        (department) => department?.id === val
      );
      if (departments.length && departments[0]?.id) {
        this.$router.push({
          name: 'department',
          params: {
            id: departments[0].id,
          },
        });
      }
    }
  }

  created(): void {
    this.initDepartments();
  }

  parentOrg: OrganizationWithParent | null = null;

  private getTreeStructure(node: NodeTO) {
    const result: DepartmentToTree = {
      ...node.value,
      id: node?.value?.id,
      label: get(node?.value, 'fullname') || get(node?.value, 'name'),
    };

    if (node.leafs && node.leafs instanceof Array) {
      result.children = node.leafs.map((childNode) => {
        return this.getTreeStructure(childNode);
      });
    }

    return result;
  }

  async initDepartments(): Promise<void> {
    this.initLoading = true;
    try {
      const { data } = await domainApi.getDomainChildrenTreeV1(
        this.$route.params.id,
        1000,
        ['Department']
      );
      if (data?.leafs?.length) {
        this.departments = data.leafs.map((node) => {
          return this.getTreeStructure(node);
        });
      } else {
        this.departments = [];
      }
      this.initLoading = false;
    } catch {
      this.initLoading = false;
      this.$q.notify({
        color: 'negative',
        icon: 'error',
        message: 'Не удалось загрузить иерархию подразделений',
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.OrganizationStructure {
  &__WhiteCard {
    padding: 12px 16px;
    margin-bottom: 16px;
    position: relative;
  }
  &__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);
  }

  &__Tree {
    overflow-y: auto;
    max-height: 50vh;
  }
}
</style>
