<template>
  <div
    class="no-shadow full-width bg-white q-pa-md rounded-borders relative-position q-gutter-y-md create-card"
    v-if="model"
  >
    <div class="text-h6 q-ma-none">
      {{ $t('interagencies.newChildInteragencyRequestCreation') }}
    </div>

    <q-tabs v-model="tab" no-caps outside-arrows mobile-arrows>
      <q-tab :name="Tab.Common" label="Общие" />
      <q-tab :name="Tab.Request" label="Запрос" />
      <q-tab v-if="response" :name="Tab.Response" label="Ответ" />
    </q-tabs>

    <CommonTab v-show="tab === Tab.Common" @input="onInput" ref="commonTabRef" />

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

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

    <div>
      <q-btn
        :label="$t('base.create')"
        type="submit"
        color="primary"
        @click="onCreateClick"
      />
      <q-btn
        @click="$emit('close')"
        :label="$t('base.close')"
        color="primary"
        flat
        class="q-ml-sm"
      />
    </div>

    <q-inner-loading :showing="loading" />
  </div>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import RequestTab from '../../request-tab.vue';
import ResponseTab from '../../child-interagency/response-tab.vue';
import CommonTab from './common-tab.vue';
import { notifyError, notifySuccess } from '@/utils/notify';
import { FormProperties } from '@/components/interagency-requests/types';
import { defaultChildInteragency } from '@/state/modules/registry-service/interagencies';
import { QForm } from 'quasar';
import { Tab } from '../../../utils';

@Component({
  components: {
    CommonTab,
    RequestTab,
    ResponseTab,
  },
})
export default class CreateChildInteragency extends Vue {
  Tab = Tab;
  loading = false;
  tab = Tab.Common;
  model = defaultChildInteragency();

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

  onInput(v: any) {
    this.model = { ...this.model, ...v };
  }

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

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

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

  async onCreateClick() {
    const form = this.$refs.commonTabRef as QForm;
    const success = await form.validate();
    if (!success) {
      if (this.tab !== Tab.Common) {
        this.tab = Tab.Common;
      }
      return;
    }
    const newInteragency: any = {
      mock: "Mock", 
      testMsg: "mock",
      clazz: this.parentInteragency.clazz,
      ...this.model,
    };
    this.loading = true;
    try {
      const data = await this.$store.dispatch(
        'registryService/interagencies/createChildInteragency',
        newInteragency
      );
      if (data.success) {
        const childId = data.objectIds![0];
        notifySuccess(this.$tc('interagencies.message.success.creation'));
        this.$router.push({
          path: `/interagency-requests/${this.parentInteragency.id}/child/${childId}`,
        });
      }
    } catch (e) {
      if (e instanceof Error) {
        notifyError(e.message);
      }
    } finally {
      this.loading = false;
    }
  }

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

<style scoped>
.create-card {
  min-width: 970px;
}
</style>
