<template>
  <q-form @submit="submit">
    <div v-if="readonly" class="q-gutter-y-xs">
      <div class="row">
        <div class="col text-grey-5">
          {{ $t('notifications.message') }}
        </div>
        <div class="col text-grey-7">{{ messageTopic }}</div>
      </div>
    </div>
    <div v-else class="q-gutter-y-md">
      <div v-if="!!templates.length" class="row">
        <q-select
          v-model="templateObject"
          class="col"
          :options="templates"
          filled
          map-options
          :label="$t('notifications.template')"
        />
      </div>
      <q-input
        v-model="messageTopic"
        filled
        :label="$t('notifications.messageTopic')"
        required
        class="col-12"
      />
      <div class="row no-wrap q-gutter-xs items-start">
        <q-editor
          class="col-9"
          v-model="editorText"
          :placeholder="$t('notifications.message')"
        />
        <div class="col-3">
          <q-select
            class="q-mb-xs"
            :options="placeholders"
            v-model="placeholder"
            option-value="code"
            option-label="name"
            emit-value
            map-options
            label="Данные"
          />
          <q-btn icon="add" color="primary" @click="addPlaceholder" />
        </div>
      </div>
      <div class="row q-gutter-y-md">
        <q-btn
          class="col-xs-12 col-sm-auto"
          color="primary"
          outline
          type="button"
          :label="$t('base.actions.cancel')"
          @click="cancelProcess"
        />
        <q-btn
          color="primary"
          class="col-xs-12 col-sm-auto q-ml-sm-md"
          type="submit"
          :label="$t('base.send')"
        />
      </div>
    </div>
  </q-form>
</template>

<script lang="ts">
import { Component, Prop, Watch } from 'vue-property-decorator';
import InputData from '@/types/wf/InputData';
import Vue from 'vue';
import { QSelectOption } from '@models/models-ui';
import { Placeholder, PlaceholdersApi } from '@openapi/notifier-registry';
import { notifyError } from '@utils/notify';
declare interface FormInputData extends InputData {
  templates: Array<any>;
  currentTemplate: any;
}
declare interface QSelectOptionAndBody extends QSelectOption {
  body: string;
}

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

  private placeholderApi = new PlaceholdersApi();

  private editorText = '';

  private messageTopic = '';

  private templateId = '';

  private placeholders: Placeholder[] = [];
  private placeholder = '';
  private addPlaceholder(): void {
    this.editorText += ` {{{${this.placeholder}}}}`;
  }

  private templates: Array<QSelectOptionAndBody> = [];

  private templateObject: QSelectOptionAndBody | null = null;

  private cancelProcess(e: any): void {
    this.$emit('submit', e, { transExit: true });
  }

  private submit(e: any): void {
    const outputData: any = {};

    const template = this.templates.find(
      (x: any) => x.value === this.templateId
    );

    if (
      template &&
      template.body === this.editorText &&
      template.label === this.messageTopic
    ) {
      outputData.selectedTemplateId = this.templateId;
      outputData.templateTitle = this.messageTopic;
    } else {
      outputData.newTemplateBody = this.editorText;
      outputData.newTemplateTitle = this.messageTopic;
    }
    this.$emit('submit', e, outputData);
  }

  private mounted(): void {
    this.placeholderApi
      .searchPlaceholders()
      .then((response) => {
        this.placeholders = [...response.data];
      })
      .catch((e) => {});
  }

  @Watch('templateObject')
  private templateObjectUpdate(val: QSelectOptionAndBody): void {
    if (val) {
      this.editorText = val.body ?? '';
      this.messageTopic = val.label ?? '';
      this.templateId = (val.value as string) ?? '';
    }
  }

  @Watch('inputData', { immediate: true })
  private inputDataUpdate(val: FormInputData): void {
    if (!val) return;

    this.templates = (val?.templates ?? []).map(
      (el: any): QSelectOptionAndBody => {
        return {
          value: el.id,
          label: el.name,
          body: el.body,
        };
      }
    );
    if (val.currentTemplate) {
      this.templateObject = this.templates.find(
        (template: any) => template.value === val.currentTemplate.id
      ) as QSelectOptionAndBody;
    }
  }
}
</script>
