<i18n>
{
  "en": {
    "EmployeesRolesForm": {
      "formName": "Choose roles",
      "assigned": "Assigned roles",
      "choose": "Choose",
      "cancel": "Cancel"
    }
  },
  "ru": {
    "EmployeesRolesForm": {
      "formName": "Выбор ролей",
      "assigned": "Назначенные роли",
      "choose": "Назначить",
      "cancel": "Отмена"
    }
  }
}
</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('EmployeesRolesForm.assigned') }}
        </div>
        <div class="col text-grey-7">
          <div v-for="tick in ticked" :key="`ticked-${tick}`">
            {{ tick }}
          </div>
        </div>
      </div>
    </div>
    <div v-else class="q-gutter-b-md">
      <div class="q-b-md q-px-md row q-col-gutter-sm">
        <q-tree
          class="col-12 col-sm-6"
          :nodes="rolesFormatted"
          node-key="id"
          tick-strategy="leaf"
          :ticked.sync="rolesList"
          default-expand-all
        />
        <div class="col-12 col-sm-6 q-gutter-sm">
          <div class="text-h6">
            {{ $t('EmployeesRolesForm.assigned') }}
          </div>
          <div>
            <div v-for="(tick, i) in ticked" :key="`ticked-${tick}-${i}`">
              {{ tick }}
            </div>
          </div>
        </div>
      </div>
      <div class="q-mt-md row q-gutter-y-md">
        <q-btn
          class="col-xs-12 col-sm-auto"
          color="primary"
          :label="$t('EmployeesRolesForm.cancel')"
          type="button"
          outline
          @click="cancelProcess"
        />
        <q-btn
          color="primary"
          class="col-xs-12 col-sm-auto q-ml-sm-md"
          :label="$t('EmployeesRolesForm.choose')"
          type="submit"
        />
      </div>
    </div>
  </q-form>
</template>

<script lang="ts">
// @ts-nocheck
// TODO: refactoring

export default {
  props: ['input-data', 'readonly'],
  data() {
    return {
      roles: [],
      rolesFormatted: [],
      tickedId: [],
      rolesList: [],
      activeRolesIds: [],
    };
  },
  computed: {
    organizationRoles() {
      return this?.inputData?.organizationRoles || [];
    },
    removeRoles() {
      const arrNotChoose = [];

      this.rolesFormatted.forEach((item) => {
        if (item.children) {
          item.children.forEach((itemRoles) => {
            if (!this.rolesList.includes(itemRoles.id)) {
              arrNotChoose.push(itemRoles.id);
            }
          });
        }
      });

      return arrNotChoose;
    },
    outputData() {
      return {
        rolesList: this.rolesList.filter(
          (roleId) => !this.activeRolesIds.includes(roleId)
        ),
        removeRoles: this.activeRolesIds.filter(
          (roleId) => !this.rolesList.includes(roleId)
        ),
        ticked: this.ticked,
        transExit: false,
      };
    },
    ticked() {
      if (this.inputData.ticked) {
        return this.inputData.ticked || [];
      }
      const flat = this.rolesFormatted.flatMap((e) => {
        return e.children.concat(e);
      });

      return (
        this.rolesList.map((e) => {
          const found = flat.find((f) => f.id === e);

          return found?.displayName;
        }) || []
      );
    },
  },
  watch: {
    inputData: {
      handler: function (val) {
        if (val) {
          this.rolesFormatted = this.changeProperties(
            val.roles.filter((role) => role.ervuSolution) || []
          );
          this.rolesList = [];
          this.activeRolesIds = [];
          const activeRolesFromUT = val?.activeRoles || [];
          const orgRolesFromUT = val?.organizationRoles || [];
          const orgIds = orgRolesFromUT.map((r) => r.id);
          const activeRoles = [
            ...orgRolesFromUT,
            ...activeRolesFromUT.filter((role) => !orgIds.includes(role.id)),
          ];
          activeRoles.forEach((itemRole) => {
            this.rolesList.push(itemRole.id);
            this.activeRolesIds.push(itemRole.id);
          });
        }
      },
      immediate: true,
    },
  },
  methods: {
    changeProperties(arr) {
      if (arr && arr instanceof Array) {
        const changeList = (item) => {
          const returnObj = {
            id: item.id,
            label: item.displayName || item.shortname,
            disabled: this.organizationRoles.some(
              (role) => role.id === item.id
            ),
            ...item,
          };

          if (item.roles && item.roles instanceof Array) {
            returnObj.children = item.roles.map(changeList);
          }
          return returnObj;
        };
        return arr.filter((item) => item.roles).map(changeList);
      }
      return [];
    },
    submit(e) {
      this.$emit('submit', e, this.outputData);
    },
    cancelProcess(e) {
      this.$emit('submit', e, { transExit: true });
    },
  },
};
</script>
