<i18n>
{
  "en": {
    "title": {
      "create": "Create IDR"
    },
    "label": {
      "interagency": "MZ name",
      "mvz": "Process"
    },
    "btn": {
      "createMapping": "create mapping",
      "editMapping": "edit mapping"

    }
  },
  "ru": {
    "title": {
      "create": "Создать процесс МВЗ"
    },
    "label": {
      "interagency": "Наименование МЗ",
      "mvz": "Наименование"
    },
    "btn": {
      "createMapping": "Создать маппинг",
      "editMapping": "Изменить маппинг"
    }
  }
}
</i18n>

<template>
  <q-dialog v-model="dialogOpen" @hide="clearModel" persistent>
    <q-card v-if="!showMapping" 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-input
            v-model="dataModel.name"
            :options="processes"
            :label="$t('label.mvz')"
            ref="inputName"
            filled
            :rules="[rulesRequired]"
          />
        </q-card-section>

        <q-card-section class="q-pb-xs">
          <q-select
            v-model="dataModel.interagency"
            :options="interagencies"
            :label="$t('label.interagency')"
            ref="inputInteragency"
            option-value="id"
            option-label="requestName"
            multiple
            menu-anchor="bottom left"
            filled
            :rules="[rulesRequired]"
          />
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            class="q-mr-auto"
            @click="createMapping"
            :label="mappingLabel"
            color="white"
            text-color="primary"
            outline
          />
          <q-btn
            @click="handleSubmit"
            :label="$t('base.create')"
            :disable="!fileName"
            unelevated
            color="primary"
          />
          <q-btn
            @click="handleClose"
            :label="$t('base.close')"
            color="white"
            text-color="primary"
            outline
          />
        </q-card-actions>
      </form>
    </q-card>
    <MappingDialog 
      v-else 
      :addMapping="mapping"
      @mapping="setMapping"
      @hideMapping="showMapping = !showMapping"
    />
  </q-dialog>
</template>


<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { ConstructorBpmnInteragenciesGenerationApi, InteragenciesGenerationParams } from '@openapi/bpmn-generation'
import MappingDialog, { MappingTableColumn } from './MappingDialog.vue'
import cloneDeep from 'lodash/cloneDeep';

import { exportFile } from 'quasar';

import {
  createDocument,
  updateAttachment,
  updateDocument,
} from '@services/registry-service';
import get from 'lodash/get';
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 Interagencies = Interagency[];

type Data = "createMode" | Surge | null

@Component({
  components: {
    MappingDialog
  },
})
export default class MvzDialog extends Vue {
  @Prop() common?: BaseCardCommon;
  
  dataModel: {interagency: Interagencies, name: string} | null = null;
  mapping: MappingTableColumn[] = [];
  schemaName: 'Process'
  dialogData: {
    name: string, 
    id: string, 
    schema: string, 
    attachment?: boolean, 
    modified?: number
  } = {
    name: '',
    schema:'', 
    id: '',
  };
  mvzBpmn: File | null = null;
  
  loading = false;
  dialogOpen = false;
  showMapping = false;

  get formTitle() {
    return this.$t('title.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 || []);
  }

  get selectedMvz() {
    return !!this.dataModel?.interagency?.length;
  }

  get fileName() {
    return !!this.dataModel?.name?.length;
  }

  get mappingLabel() {
    return this.mapping?.length ? this.$t('btn.editMapping') : this.$t('btn.createMapping');
  }

  @Watch('common.models.MvzDialog.data', { immediate: true })
  dataHandler(data?: Data) {
    if (!data) return;
    this.dataModel = {
      interagency: [],
      name: ''
    };
    this.dialogOpen = true;
  }

  destroyed() {
    this.clearModel();
  }

  clearModel() {
    this.dataModel = null;
    this.$emit('commonModels', {
      MvzDialog: { data: null },
    });
  }

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

  async handleSubmit() {
    const userInput = {
      "interagencyIds": this.dataModel?.interagency.map((v: Interagency) => v.id) || [], 
      "name": this.dataModel?.name || '',
      "mapping": this.mapping.map((el) => ({from: el.name, to: el.value})),
    }
    const generateBpmn = await new ConstructorBpmnInteragenciesGenerationApi()
      .generateInteragenciesProcess(userInput);
      this.mvzBpmn = new File([generateBpmn.data], this.dataModel?.name  + '.bpmn');
      exportFile( this.dataModel?.name  + '.bpmn', generateBpmn.data, 'application/xml');
      this.SendFile(this.mvzBpmn);
  }

  async SendFile(mvzBpmn: File) {
    try {
      this.loading = true;
      this.dialogData.name = mvzBpmn.name;
        const { data: docResult } = await createDocument('Process', [
          this.dialogData,
        ]);
        this.dialogData.id = get(docResult, 'objectIds[0]');
        this.dialogData.schema = 'Process';

        if (true) {
          const file = mvzBpmn;

          const { data: attachResult } = await updateAttachment(
            'Process',
            get(this.dialogData, 'id'),
            undefined,
            [file]
          );
          this.dialogData.modified = attachResult.modified;
          this.dialogData.attachment = true;
          const { data: docResult } = await updateDocument(this.schemaName, [
            this.dialogData,
          ]);
          this.dialogData.modified = docResult.modified;
        }
        const card = cloneDeep(
          this.$store.getters['registryService/services/servicesCard']
        );
        const processes = card.processes || [];
        processes.push(this.dialogData);
        card.processes = processes;

        this.$store.dispatch('registryService/services/setCardForJson', card);
      } catch (e) {
        this.$q.notify({
          color: 'negative',
          icon: 'error',
          message: e.message,
        });
      } finally {
        this.loading = false;
        this.dialogOpen = false;
      }
  }

  createMapping() {
    this.showMapping = !this.showMapping;
  }

  setMapping(items: MappingTableColumn[]) {
    this.mapping = cloneDeep(items);
  }

  handleClose() {
    this.dialogOpen = false;
  }
}

</script>
