<template>
  <q-card class="no-shadow">
    <q-card-section v-if="interagency">
      <Mapping v-model="mapping" />
      <TestRequest :clazz="interagency.clazz" :json="mapping" />
    </q-card-section>
    <q-separator />

    <q-card-section v-if="isChildPage">
      <span class="text-subtitle1">Экранная форма запроса</span>
      <ScreenFormEditor
        schema="Interagency"
        :form-id="formId"
        form-key="formRequest"
        :parent-linked-object="interagency"
        @change="onFormIdChange"
      />
    </q-card-section>
    <q-separator />

    <q-card-section v-if="parentInteragency">
      <XslScript :xsl="xsl" :interagency-id="parentInteragency.id" />
    </q-card-section>
  </q-card>
</template>

<script lang="ts">
import { Component, Vue, Watch, Prop } from 'vue-property-decorator';
import Mapping from './mapping.vue';
import XslScript from './xsl-script.vue';
import ScreenFormEditor from './screen-form-editor.vue';
import TestRequest from './test-request.vue';
import cloneDeep from 'lodash/cloneDeep';
import { notifyError } from '@/utils/notify';
import { isEqual } from 'lodash';

@Component({
  components: {
    XslScript,
    ScreenFormEditor,
    TestRequest,
    Mapping,
  },
})
export default class RequestTab extends Vue {
  @Prop() interagency: any;
  @Prop() model: any;

  mapping = {};
  xsl = {};
  formId = '';

  async created() {
    this.mapping = cloneDeep(this.model.mapping.out);
    this.formId = this.model.formRequest?.id;
    const parentInteragency =
      this.parentInteragency || (await this.getParentInteragency());
    this.xsl = parentInteragency.attachments?.[0];
  }

  @Watch('mapping', { deep: true })
  onMappingChange(mapping: any) {
    if (!isEqual(this.model.mapping?.out, mapping))
      this.$emit('update-request-json', mapping);
  }

  get isChildPage() {
    return !!this.$route.params.parentId;
  }

  get parentInteragency() {
    return this.$store.getters[
      'registryService/interagencies/getParentInteragency'
    ];
  }

  get childInteragency() {
    return this.$store.getters[
      'registryService/interagencies/getChildInteragency'
    ];
  }

  onFormIdChange(id: string) {
    this.formId = id;
    this.$emit('update-form-id', id);
  }

  async getParentInteragency() {
    const id = this.$route.params.parentId;
    try {
      return await this.$store.dispatch(
        'registryService/interagencies/getParentInteragencyById',
        id
      );
    } catch (e) {
      if (e instanceof Error) {
        notifyError(e.message);
      }
    }
  }
}
</script>

<style scoped></style>
