<i18n>
{
  "en": {
    "DepartmentDeleteSelectForm": {
      "organization": "Organization",
      "send": "Send",
      "notChoose": "Not chosen",
      "currentStructure": "Current structure",
      "departmentLabel": "Departments, positions and employees will be transferred to:",
      "doNeedToTransferRoles": "Do need to transfer Roles to a lower level?",
      "yes": "Yes",
      "no": "No"
    }
  },
  "ru": {
    "DepartmentDeleteSelectForm": {
      "organization": "Организация",
      "send": "Отправить",
      "notChoose": "Не выбрано",
      "currentStructure": "Текущая структура",
      "departmentLabel": "Подразделения, должности и сотрудники будут перенесены в:",
      "doNeedToTransferRoles": "Перенести роли на уровень ниже?",
      "yes": "Да",
      "no": "Нет"
    }
  }
}
</i18n>

<template>
  <q-form class="q-gutter-y-md" @submit="submit">
    <div v-if="readonly" class="q-gutter-y-sm">
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('DepartmentDeleteSelectForm.departmentLabel') }}
        </div>
        <div class="col text-grey-7 q-pl-md">{{ label }}</div>
      </div>
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('DepartmentDeleteSelectForm.doNeedToTransferRoles') }}
        </div>
        <div v-if="moveRoles" class="col text-grey-7 q-pl-md">
          {{ $t('DepartmentDeleteSelectForm.yes') }}
        </div>
        <div v-else class="col text-grey-7 q-pl-md">
          {{ $t('DepartmentDeleteSelectForm.no') }}
        </div>
      </div>
    </div>
    <div v-else class="q-gutter-y-md">
      <div class="row">
        <div class="col-xs-12 col-md q-mr-md-md">
          <div>{{ $t('DepartmentDeleteSelectForm.currentStructure') }}:</div>
          <q-tree
            :nodes="departments"
            node-key="id"
            accordion
            default-expand-all
          >
            <template #header-bold="prop">
              <div class="row items-center">
                <div class="text-weight-bold text-primary">
                  {{ prop.node.label }}
                </div>
              </div>
            </template>
          </q-tree>
        </div>
        <div class="col-xs-12 col-md q-mt-sm-md q-mt-md-none">
          <q-field
            :disable="!departments.length"
            class="full-width"
            filled
            :label="$t('DepartmentDeleteSelectForm.departmentLabel')"
            stack-label
          >
            <template>
              <div tabindex="0" class="no-outline full-width text-black">
                {{ labelView }}
              </div>
            </template>
            <template #append>
              <q-icon name="arrow_drop_down"></q-icon>
            </template>
            <q-menu fit auto-close>
              <q-tree
                :nodes="selectDepartments"
                :selected.sync="selected"
                node-key="id"
                accordion
                default-expand-all
              ></q-tree>
            </q-menu>
          </q-field>
        </div>
      </div>
      <div v-if="showDoNeedToTransferRoles" class="row q-gutter-x-md">
        <q-checkbox
          v-model="moveRoles"
          :label="$t('DepartmentDeleteSelectForm.doNeedToTransferRoles')"
        />
      </div>

      <q-btn
        color="primary"
        :label="$t('DepartmentDeleteSelectForm.send')"
        type="submit"
      />
    </div>
  </q-form>
</template>

<script lang="ts">
// @ts-nocheck
export default {
  props: ['input-data', 'readonly'],
  data() {
    return {
      organizationName: '',
      organizationId: '',
      departments: [],
      selectDepartments: [],
      selected: '',
      label: '',
      moveRoles: false,
      showDoNeedToTransferRoles: false,
    };
  },
  computed: {
    outputData() {
      return {
        moveRoles: this.moveRoles,
        destination: this.selected,
        label: this.label,
      };
    },
    labelView() {
      return this.label || this.$t('DepartmentDeleteSelectForm.notChoose');
    },
  },
  watch: {
    inputData: {
      handler: function (val) {
        if (val) {
          if (typeof val === 'object' && val.structure) {
            if (val.structure.value) {
              this.organizationName = val.structure.value.fullname;
              this.organizationId = val.structure.value.id;
              this.selected = this.organizationId;
            }

            const getTreeStructure = function (item, needDisabled) {
              const returnObj = {
                id: item.value.id,
                label: item.value.fullname || item.value.name,
              };

              if (item.value.id === val.source) {
                returnObj.header = 'bold';
                if (needDisabled) {
                  returnObj.disabled = true;
                }
                if (
                  item.leafs &&
                  item.leafs instanceof Array &&
                  item.leafs.length > 0
                ) {
                  this.showDoNeedToTransferRoles = true;
                }
              }

              if (item.leafs && item.leafs instanceof Array) {
                returnObj.children = item.leafs.map((itemLeaf) => {
                  return getTreeStructure(itemLeaf, needDisabled);
                });
              }

              return returnObj;
            }.bind(this);

            if (val.structure.leafs) {
              this.selectDepartments = [
                {
                  id: this.organizationId,
                  label: this.organizationName,
                  children: val.structure.leafs.map((item) => {
                    return getTreeStructure(item, true);
                  }),
                },
              ];
              this.departments = [
                {
                  id: this.organizationId,
                  label: this.organizationName,
                  children: val.structure.leafs.map((item) => {
                    return getTreeStructure(item, false);
                  }),
                },
              ];
            }
          }
          if (this.readonly) {
            this.label = val.label;
            this.moveRoles = val.moveRoles;
          }
        }
      },
      immediate: true,
    },
    selected: {
      handler: function (val) {
        if (val) {
          this.initLabel();
        }
      },
      immediate: true,
    },
  },
  methods: {
    submit(e) {
      this.$emit('submit', e, this.outputData);
    },
    getNodeByKeyRecursive(val, nodes) {
      let targetNode = null;

      if (val && nodes.length) {
        for (const node of nodes) {
          if (node.id === val) {
            targetNode = node;
          } else if (node.children && node.children.length) {
            targetNode = this.getNodeByKeyRecursive(val, node.children);
          }

          if (targetNode) break;
        }
      }
      return targetNode;
    },
    initLabel() {
      const node = this.getNodeByKeyRecursive(this.selected, this.departments);

      this.label = node ? node.label : '';
    },
  },
};
</script>
