<template>
  <div>
    <q-card
      class="bg-grey-custom no-shadow q-gutter-y-md q-mx-md q-mt-md"
      v-if="!loading"
    >
      <div
        class="rounded-borders bg-white items-center justify-between row q-pa-md"
      >
        <div class="text-h6 flex items-center text-grey-9 col q-pr-md">
          <q-btn
            padding="xs"
            class="text-grey-7 q-mr-md"
            color="grey-3"
            icon="arrow_back"
            @click="backToNotifications"
          />
          <span class="text-h5">{{ title }}</span>
        </div>
        <div class="center row-md">
          <div class="justify-end flex">
            <q-btn
              color="primary"
              class="q-mr-md"
              label="Клонировать"
              @click="dialogCopy = true"
            />
            <q-btn
              color="white"
              text-color="primary"
              class="q-mr-md"
              outline
              :label="$t('notifications.delete')"
              type="button"
              @click="dialogDelete = true"
            />
          </div>
        </div>
      </div>
    </q-card>
    <base-tabs v-if="!loading" :current-tab="tabs.current" :tabs="tabs.list" />
    <q-dialog v-model="dialogDelete">
      <q-card class="no-shadow">
        <q-card-section>
          <div class="text-h6">{{ $t('notifications.confirmation') }}</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          {{ $t('notifications.questionToDelete') }}
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            flat
            :label="$t('notifications.no')"
            color="primary"
            @click="dialogDelete = false"
          />
          <q-btn
            flat
            :label="$t('notifications.yes')"
            color="red"
            @click="deleteNotification"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <q-dialog v-model="dialogCopy">
      <q-card class="no-shadow">
        <q-card-section>
          <div class="text-h6">Подтверждение клонирования уведомления</div>
        </q-card-section>

        <q-card-section class="q-pt-none">
          Вы уверены что хотите создать копию уведомления?
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            flat
            :label="$t('notifications.no')"
            color="primary"
            @click="dialogCopy = false"
          />
          <q-btn
            flat
            :label="$t('notifications.yes')"
            color="red"
            @click="createCopy"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { BaseCardCommon } from '@interfaces/components';
import { Notification, NotificationsApi } from '@openapi/idm';
import { BaseTabs } from '@interfaces/base/BaseTabs';
import { notifyError, notifySuccess } from '@utils/notify';

// TODO: Исправить после решения тикета https://jira.egovdev.ru/browse/PGSRUSH-3801
interface KostilNotification extends Notification {
  roles: Array<string>
}

const notificationsApi = new NotificationsApi();

@Component({})
export default class NotificationsCardIndex extends Vue {
  @Prop({}) private common?: BaseCardCommon;
  @Prop({}) private model?: Notification;

  private dialogDelete = false;
  private dialogCopy = false;
  private cardModel: Notification | null = null;

  @Watch('common.active', {
    immediate: true,
  })
  activeWatcher(val: any) {
    this.tabs.current = val;
  }

  @Watch('model', {
    immediate: true,
  })
  modelWatcher(val: Notification) {
    if (val) {
      this.cardModel = val;
    }
  }

  private get title(): string {
    return this.cardModel?.title ?? 'Уведомление';
  }

  private get tabs(): BaseTabs {
    return {
      current: this.common?.active ?? 'settings',
      list: [
        {
          name: this.$t('notifications.notificationSettings').toString(),
          path: 'settings',
          visible: true,
        },
        {
          name: this.$t('notifications.notificationData').toString(),
          path: 'data',
          visible: true,
        },
      ],
    };
  }

  private get loading(): string {
    return this.$store.getters['idm/notificationss/notificationCardLoading'];
  }

  private created() {
    this.initModel();
  }

  private backToNotifications() {
    this.$router.push({
      path: '/notifications',
    });
  }

  private deleteNotification() {
    this.dialogDelete = false;
    this.$store.dispatch('wf/processes/dispatchProcess', {
      processKey: 'DeleteDomainNotificationsProcess',
      data: {
        notificationIds: [this.cardModel?.id],
        redirectUrl: '/notifications',
      },
    });
  }

  private createCopy() {
    if (this.cardModel === null) {
      return;
    }
    const copyTemplate: KostilNotification = {
      id: Math.random().toString(36).slice(2),
      title: this.cardModel.title + '_КОПИЯ',
      messageTopic: this.cardModel.messageTopic,
      eventId: this.cardModel.eventId,
      templateId: this.cardModel.templateId,
      // @ts-ignore
      roles: this.cardModel.roles.map((e: string) => e.id),
    };
    notificationsApi.createNotification([copyTemplate]).then((response) => {
      notifySuccess('Уведомление успешно клонировано')
    })
      .catch(e => {
        notifyError('Произошла ошибка при клонировании уведомления')
      })
      .finally(() => {
        this.dialogCopy = false;
      })
  }

  private async initModel() {
    try {
      this.$store.commit('idm/notifications/notificationCardLoading', true);

      const model = await notificationsApi
        .getNotification(this?.common?.id ?? '', 'roles')
        .then(({ data }) => data);

      this.$store.commit(`utils/cards/addModel`, {
        model,
        path: this.common?.path,
      });
    } catch (e) {
      notifyError(e.message.toString());
    } finally {
      this.$store.commit('idm/notifications/notificationCardLoading', false);
    }
  }
}
</script>
