<template>
  <q-form class="q-gutter-y-md" @submit="submit">
    <div class="q-gutter-b-md">
      <div class="q-b-md q-px-md row q-col-gutter-sm">
        <q-tree
          :nodes="notificationsList"
          node-key="id"
          tick-strategy="leaf"
          :ticked.sync="activeNotificationsIds"
          default-expand-all
        />
      </div>
      <div class="q-mt-md row q-gutter-y-md">
        <q-btn
          class="col-xs-12 col-sm-auto"
          color="primary"
          :label="$t('base.actions.cancel')"
          type="button"
          outline
          @click="cancelProcess"
        />
        <q-btn
          color="primary"
          class="col-xs-12 col-sm-auto q-ml-sm-md"
          :label="$t('base.send')"
          type="submit"
        />
      </div>
    </div>
  </q-form>
</template>

<script lang="ts">
import { Component, Prop, Watch } from 'vue-property-decorator';
import InputData from '@/types/wf/InputData';
import { Notification } from '@openapi/idm';
import Vue from 'vue';

declare interface InputDataProp extends InputData {
  notifications: Array<Notification>;
  allNotifications: Array<Notification>;
}

@Component({})
export default class RegionNotificationsCard extends Vue {
  @Prop() readonly inputData: InputData;
  @Prop() readonly readonly: boolean;

  private activeNotifications: Array<Notification> = [];

  private notificationsList: Array<Notification> = [];

  private activeNotificationsIds: Array<string> = [];

  formatNoticesInTree(notifications: Array<Notification>) {
    return (notifications ?? []).map((notification) => {
      return { ...notification, label: notification.title };
    });
  }

  private get outputData() {
    return {
      notificationsToAttach: this.activeNotificationsIds,
      notificationsToDetach: this.activeNotifications
        .map((i: any) => i.id)
        .filter(
          (notification: any) =>
            !this.activeNotificationsIds.find((i) => i === notification)
        ),
      transExit: false,
    };
  }

  @Watch('inputData', { immediate: true })
  private inputDataUpdate(val: InputDataProp) {
    if (val) {
      this.notificationsList = this.formatNoticesInTree(val.allNotifications);
      this.activeNotifications = val.notifications ?? [];
      this.activeNotificationsIds = this.activeNotifications.map(
        (i: any) => i.id
      );
    }
  }

  submit(e: any) {
    this.$emit('submit', e, this.outputData);
  }

  cancelProcess(e: any) {
    this.$emit('submit', e, { transExit: true });
  }
}
</script>
