<i18n>
{
  "en": {
    "CreateDepartmentConfirmationForm": {
      "confirmationMessage": "Are you sure you are willing to create department in ",
      "messageRoot": "To create child department, please select root",
      "historyMessage": "Department succesfully attached:",
      "cancel": "Cancel",
      "create": "Create"
    }
  },
  "ru": {
    "CreateDepartmentConfirmationForm": {
      "confirmationMessage": "Вы уверены, что хотите создать подразделение в организации ",
      "messageRoot": "Для создания дочернего подразделения выберите корневой.",
      "historyMessage": "Подразделение успешно прикреплено:",
      "cancel": "Отмена",
      "create": "Создать"
    }
  }
}
</i18n>

<template>
  <q-form @submit="submit" class="q-gutter-y-md">
    <div v-if="!readonly" class="q-gutter-y-sm">
      <div class="col-12">
        {{
          $t('CreateDepartmentConfirmationForm.confirmationMessage') +
          this.organization +
          '?'
        }}
        {{ $t('CreateDepartmentConfirmationForm.messageRoot') }}
      </div>
      <q-tree
        v-if="Boolean(departments.length)"
        node-key="id"
        ref="tree"
        default-expand-all
        selected-color="primary"
        :nodes="departments"
        :selected.sync="selected"
      />
      <div class="col-12 q-mt-sm row q-gutter-y-md">
        <q-btn
          color="white"
          text-color="primary"
          class="col-xs-12 col-sm-auto"
          outline
          @click="sendCancel"
          :label="$t('CreateDepartmentConfirmationForm.cancel')"
          type="button"
        />
        <q-btn
          class="col-xs-12 col-sm-auto q-ml-sm-md"
          color="primary"
          @click="sendCreate"
          :label="$t('CreateDepartmentConfirmationForm.create')"
          type="button"
        />
      </div>
    </div>
    <div v-else>
      <div class="q-gutter-y-md">
        <div class="col-12">
          {{ $t('CreateDepartmentConfirmationForm.historyMessage') }}
          <q-tree
            node-key="id"
            ref="tree"
            disabled
            default-expand-all
            selected-color="primary"
            :nodes="departments"
            :selected="selected"
          />
        </div>
      </div>
    </div>
  </q-form>
</template>

<script lang="ts">
// @ts-nocheck
export default {
  props: ['input-data', 'readonly'],
  data() {
    return {
      organization: '',
      organizationId: '',
      departments: [],
      selected: '',
    };
  },
  computed: {
    outputData() {
      return {
        parent: this.selected ? this.selected : this.organizationId,
        departments: this.departments,
      };
    },
  },
  methods: {
    submit(e) {
      this.$emit('submit', e, this.outputData);
    },
    sendCancel(e) {
      this.$emit('submit', e, {
        ...this.outputData,
        transExit: true,
      });
    },
    sendCreate(e) {
      this.$emit('submit', e, {
        ...this.outputData,
        transExit: false,
      });
    },
    getTreeStructure(node) {
      const result = {
        ...node.value,
        id: node.value.id,
        label: node.value.fullname || node.value.name,
      };

      if (node.leafs && node.leafs instanceof Array) {
        result.children = node.leafs
          .filter((el) => {
            return el.value.schema === 'Department';
          })
          .map((childNode) => {
            return this.getTreeStructure(childNode);
          });
      }

      return result;
    },
  },
  watch: {
    inputData: {
      handler: function (val) {
        if (this.readonly && val.departments) {
          this.departments = val.departments;
          this.selected = val.parent;
        }
        if (val && val.structure && val.structure.leafs) {
          const leafs = val.structure.leafs;
          const deps = [];
          deps.push({
            label: val.structure.value.fullname,
            id: val.structure.value.id,
          });
          deps[0].children = leafs
            .filter((el) => {
              return el.value.schema === 'Department';
            })
            .map((el) => {
              return this.getTreeStructure(el);
            });
          this.departments = deps;
        }
        if (val && val.structure && val.structure.value) {
          this.organization = val.structure.value.fullname;
          this.organizationId = val.structure.value.id;
        }

        this.$nextTick().then(() => {
          this.$refs.tree?.expandAll();
        });
      },
      immediate: true,
      deep: true,
    },
  },
};
</script>
