<template>
  <div class="q-gutter-y-md q-mx-md q-mt-md">
    <template v-if="model && model.id">
      <Header
        :is-changed="isChanged"
        :is-request-changed="isRequestChanged"
        :go-back-func="onBack"
        :edit-mode="editMode"
        :model="model"
        @set-edit-mode="(v) => (editMode = v)"
        @saved="onSaved"
        ref="headerRef"
      />

      <!-- CHILD INTERAGENCY REQUEST DATA -->
      <div class="bg-white q-pa-md rounded-borders q-col-gutter-y-sm">
        <base-label-value padded-label class="items-center">
          <template v-slot:label>{{ $t('base.table.id') }}</template>
          <template v-slot:value>
            {{ model.id }}
          </template>
        </base-label-value>
        <template v-if="editMode">
          <base-label-value padded-label class="items-center">
            <template v-slot:label>{{ $t('interagencies.class') }}</template>
            <template v-slot:value>
              {{ model.class }}
            </template>
          </base-label-value>
          <base-label-value padded-label class="items-center">
            <template v-slot:label>{{ $t('interagencies.clazz') }}</template>
            <template v-slot:value>
              <q-input
                v-model="model.clazz"
                map-options
                emit-value
                option-value="label"
              />
            </template>
          </base-label-value>
          <base-label-value padded-label class="items-center">
            <template v-slot:label>{{ $t('interagencies.mock') }}</template>
            <template v-slot:value>
              <q-input
                v-model="model.mock"
                map-options
                emit-value
                option-value="label"
                @input="(v) => model.testMsg = v"
              />
            </template>
          </base-label-value>
          <base-label-value padded-label class="items-center">
            <template v-slot:label>{{ $t('base.table.title') }}</template>
            <template v-slot:value>
              <q-input
                v-model="model.requestName"
                map-options
                emit-value
                option-value="label"
              />
            </template>
          </base-label-value>
          <base-label-value padded-label class="items-center">
            <template v-slot:label>{{ $t('base.table.description') }}</template>
            <template v-slot:value>
              <q-input
                v-model="model.description"
                map-options
                emit-value
                option-value="label"
              />
            </template>
          </base-label-value>
        </template>
        <template v-else>
          <base-label-value padded-label class="items-center">
            <template v-slot:label>{{ $t('interagencies.class') }}</template>
            <template v-slot:value>
              {{ model.class }}
            </template>
          </base-label-value>
          <base-label-value padded-label class="items-center">
            <template v-slot:label>{{ $t('interagencies.clazz') }}</template>
            <template v-slot:value>
              {{ model.clazz }}
            </template>
          </base-label-value>
          <base-label-value padded-label class="items-center">
            <template v-slot:label>{{ $t('interagencies.mock') }}</template>
            <template v-slot:value>
              {{ model.mock }}
            </template>
          </base-label-value>
          <base-label-value padded-label class="items-center">
            <template v-slot:label>{{ $t('base.table.title') }}</template>
            <template v-slot:value>
              {{ model.requestName }}
            </template>
          </base-label-value>
          <base-label-value padded-label class="items-center">
            <template v-slot:label>{{ $t('base.table.description') }}</template>
            <template v-slot:value>
              {{ model.description }}
            </template>
          </base-label-value>
        </template>
      </div>

      <div class="bg-white q-pa-md rounded-borders q-col-gutter-y-sm">
        <q-tabs v-model="tab" no-caps outside-arrows mobile-arrows>
          <q-tab :name="Tab.Request" label="Запрос" />
          <q-tab :name="Tab.Response" label="Ответ" />
          <q-tab :name="Tab.Templates" label="Шаблоны" />
        </q-tabs>

        <RequestTab
          v-show="tab === Tab.Request"
          :interagency="childInteragency"
          :model="model"
          @update-request-json="onUpdateMapping"
          @update-form-id="(formId) => onUpdateForm(formId, 'formRequest')"
        />

        <ResponseTab
          v-show="tab === Tab.Response"
          :model="model"
          @update-form-id="(formId) => onUpdateForm(formId, 'formResponse')"
        />

        <TemplatesTab
          v-show="tab === Tab.Templates"
          :interagency="childInteragency"
          :model="model"
          @set-mock-response="setMockResponse"
          @set-attachments="setModelAttachments"
        />
      </div>
    </template>

    <q-inner-loading :showing="!model || !model.id">
      <q-spinner-gears color="primary" size="50px" />
    </q-inner-loading>
  </div>
</template>

<script lang="ts">
import ReturnToParentView from '@mixins/ReturnToParentView';
import isEqual from 'lodash/isEqual';
import cloneDeep from 'lodash/cloneDeep';
import { Component, Mixins, Watch } from 'vue-property-decorator';
import { notifyError } from '@/utils/notify';
import Header from '../header.vue';
import ResponseTab from './response-tab.vue';
import TemplatesTab from './templates-tab.vue';
import RequestTab from '../request-tab.vue';
import { defaultChildInteragency } from '@/state/modules/registry-service/interagencies';
import { FormProperties } from '../../types';
import { Tab } from '../../utils';

@Component({
  components: {
    Header,
    RequestTab,
    ResponseTab,
    TemplatesTab,
  },
})
export default class ChildInteragency extends Mixins(ReturnToParentView) {
  Tab = Tab;

  model: any = defaultChildInteragency();
  editMode = false;
  tab = '';

  async created() {
    await this.getCurrentInteragency();
    this.setTab();
  }

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

  get isChanged() {
    return !isEqual(this.childInteragency, this.model);
  }

  get isRequestChanged() {
    return !isEqual(this.childInteragency.mapping.out, this.model.mapping.out);
  }

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

  @Watch('tab')
  onTabChange(tab: string) {
    this.$router.push({
      path: this.$route.path,
      params: this.$route.params,
      query: { tab },
    });
  }

  @Watch('response')
  onFinishResponse(r: any) {
    if (r) {
      this.tab = Tab.Response;
    }
  }

  setTab() {
    this.tab = this.$route.query.tab
      ? (this.$route.query.tab as string)
      : Tab.Request;
  }

  onUpdateMapping(mapping: any) {
    this.model.mapping.out = mapping;
  }

  onUpdateForm(formId: string, property: FormProperties) {
    this.model[property] = formId;

    const header = this.$refs.headerRef as any;
    header.saveInteragency();
  }

  async getCurrentInteragency() {
    const id = this.$route.params.id;
    if (this.childInteragency?.id === id) {
      this.model = cloneDeep(this.childInteragency);
      return;
    }
    try {
      const data = await this.$store.dispatch(
        'registryService/interagencies/getChildInteragencyById',
        id
      );
      this.model = data;
    } catch (e) {
      if (e instanceof Error) {
        notifyError(e.message);
      }
    }
  }

  onBack() {
    this.returnToParentView(
      `/interagency-requests/${this.$route.params.parentId}`
    );
  }

  async onSaved() {
    this.model = await this.$store.dispatch(
      'registryService/interagencies/getChildInteragencyById',
      this.model.id
    );
  }

  setModelAttachments(data: any[]) {
    this.model.attachments = cloneDeep(data);
  }

  setMockResponse(response: any) {
    this.model.mockResponse = cloneDeep(response);
  }

  beforeDestroy() {
    this.$store.commit(
      'registryService/interagencies/setChildTestResponse',
      ''
    );
  }
}
</script>

<style scoped></style>
