<i18n>
{
  "en": {
    "title": {
      "edit": "Edit surge",
      "create": "Create surge"
    },
    "label": {
      "interagency": "MZ",
      "process": "Process"
    }
  },
  "ru": {
    "title": {
      "edit": "Редактировать волну",
      "create": "Cоздать новую волну"
    },
    "label": {
      "interagency": "Классы МЗ",
      "process": "Процесс"
    }
  }
}
</i18n>

<template>
  <q-dialog v-model="dialogOpen" @hide="clearModel">
    <q-card class="full-width no-shadow" style="max-width: 800px">
      <q-card-section>
        <div class="text-h6">
          {{ formTitle }}
        </div>
      </q-card-section>

      <form v-if="dataModel">
        <q-card-section class="q-pb-xs">
          <q-select
            v-model="dataModel.interagency"
            :options="processes"
            :label="$t('label.process')"
            ref="inputInteragency"
            filled
            :rules="[rulesRequired]"
          />
        </q-card-section>

        <q-card-section class="q-pb-xs">
          <q-select
            v-model="dataModel.parent"
            :options="interagencies"
            :label="$t('label.interagency')"
            ref="inputParent"
            multiple
            filled
            :rules="[rulesRequired]"
          />
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            @click="handleSubmit"
            :label="formBtnSubmit"
            unelevated
            color="primary"
          />

          <q-btn
            @click="dialogOpen = false"
            :label="$t('base.close')"
            color="white"
            text-color="primary"
            outline
          />
        </q-card-actions>
      </form>
    </q-card>
  </q-dialog>
</template>


<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import cloneDeep from 'lodash/cloneDeep';
import { v4 } from 'uuid';

import { notifyError } from '@utils/notify';
import { BaseCardCommon } from '@/interfaces';

export type Surge = {
  uuid: string,
  interagency: string,
  parent: string[]
}

type Process = {
  name: string;
  id: string;
}

type Interagency = {
  class: string;
  id: string;
}

type Data = "createMode" | Surge | null

@Component({})
export default class SurgeDialog extends Vue {
  @Prop() common?: BaseCardCommon;

  dialogOpen = false;
  dataModel: Surge | null = null

  get formTitle() {
    return this.dataModel?.uuid ? this.$t('title.edit') : this.$t('title.create');
  }

  get formBtnSubmit() {
    return this.dataModel?.uuid ? this.$t('base.save') : this.$t('base.create');
  }

  get card() {
    return this.$store.getters['registryService/services/servicesCard'];
  }

  get processes() {
    return (this.card?.processes || []).map((v: Process) => v.name)
  }

  get interagencies() {
    return (this.card?.interagencies || []).map((v: Interagency) => v.class)
  }

  @Watch('common.models.SurgeDialog.data', { immediate: true })
  dataHandler(data?: Data) {
    if (!data) return;

    if (data === 'createMode') {
      this.dataModel = {
        uuid: '',
        interagency: '',
        parent: []
      };
    } else {
      this.dataModel = data;
    }

    this.dialogOpen = true;
  }

  destroyed() {
    this.clearModel();
  }

  clearModel() {
    this.dataModel = null;

    this.$emit('commonModels', {
      SurgeDialog: { data: null },
    });
  }

  rulesRequired(value: Process | Interagency) {
    return !!value || this.$t('validation.basic.required');
  }

  handleSubmit() {
    type Input = Vue & { validate: () => void, hasError: boolean }
    const { inputParent, inputInteragency } = this.$refs as { [key: string]: Input }

    const errors = [inputParent, inputInteragency].filter(input => {
      input.validate();
      return input.hasError;
    })

    if (errors.length) {
      notifyError(this.$t('validation.basic.formErrors') as string);
      return;
    }

    const card = cloneDeep(this.card);
    const interagencyWaves: Surge[] = card.interagencyWaves || [];
    const surge = this.dataModel as Surge;

    if (!surge.uuid) {
      interagencyWaves.push({...surge, uuid: v4()});
    } else {
      const findIndex = interagencyWaves.findIndex(s => s.uuid === surge.uuid);

      if (findIndex > -1) {
        interagencyWaves[findIndex] = surge;
      }
    }

    card.interagencyWaves = interagencyWaves.map(v => ({...v, uuid: v.uuid || v4()})); // есть записи без uuid

    this.$store.dispatch('registryService/services/setCardForJson', card);
    this.dialogOpen = false;
  }
}

</script>
