<template>
  <div>
    <div v-if="!isProcessCreated">
      <q-btn
        color="primary"
        text-color="white"
        @click="addProcess"
        icon="add_box"
        :label="$t('interagencies.createBpmnProcess')"
        class="q-mt-md"
      />
      <ProcessDialog
        v-if="formComponent"
        :common="common"
        @commonModels="commonModels"
        :dialog-data="processData"
        :locked-type="lockedType"
        @created="onProcessCreated"
      />
    </div>
    <div v-else>
      <base-label-value padded-label class="q-mt-sm items-center">
        <template v-slot:label>{{ $t('base.type') }}</template>
        <template v-slot:value>
          {{ $t('interagencies.interagencyRequestTemplate') }}
        </template>
      </base-label-value>

      <div>
        <bpmn-editor-component
          :schema="bpmnSchema"
          :model="processData"
          @save="onTemplateSaved"
          v-if="!readingBpmm"
        >
          <template>
            <div class="title text-h6 text-grey-10">
              {{ processData.name }}
            </div>
          </template>
        </bpmn-editor-component>

        <q-inner-loading :showing="readingBpmm">
          <q-spinner-gears color="primary" size="50px" />
        </q-inner-loading>
      </div>

      <div>
        <q-btn
          color="primary"
          text-color="white"
          @click="onDelete"
          icon="delete"
          :label="$t('interagencies.deleteProcess')"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import ProcessDialog from '@/components/cards/services/ProcessDialog.vue';
import { isEmpty } from 'lodash';
import BpmnEditorComponent from '@components/cards/processes/BpmnEditorComponent.vue';
import { createInteragencyTemplate, unlink } from '@/services/registry-service';
import { InteragencyTemplateApi } from '@openapi/registry-service';
import { notifyError, notifySuccess } from '@/utils/notify';

const interagencyTemplateApi = new InteragencyTemplateApi();

@Component({
  components: {
    ProcessDialog,
    BpmnEditorComponent,
  },
})
export default class ProcessEditor extends Vue {
  @Prop() lockedType: string;
  @Prop() template: any;

  common = {
    models: {
      index: {},
      processes: {},
      forms: {},
      directories: {},
      verifications: {},
      documents: {},
      interagencies: {},
      stages: {},
      payments: {},
      form_model: {},
      digital_regulations: {},
      basic: {},
      income: {},
      ProcessDialog: { data: { mode: 'createMode', schema: 'Process' } },
    },
  };
  formComponent = '';
  processData: any = {};
  bpmnSchema: string = '';
  readingBpmm: boolean = false;

  created() {
    this.processData = this.template;
    this.bpmnSchema = this.template?.templateBpmn;
  }

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

  get isProcessCreated() {
    return !isEmpty(this.processData);
  }

  get typeLabel() {
    return this.isProcessCreated
      ? this.processData.processTypes.find(
          (t: any) => t.value === this.processData.type
        )?.label
      : '';
  }

  async onTemplateSaved(file: File) {
    if (this.processData.id) {
      try {
        const {
          data,
        } = await interagencyTemplateApi.updateInteragencyTemplate(
          this.processData.id,
          [file]);
        if (data.success) {
          notifySuccess('BPMN-схема успешно сохранена')
        }
      } catch (e) {
        if (e instanceof Error) {
          notifyError(e.message);
        }
      }
    }
  }

  addProcess() {
    const val = 'Process';
    const componentName = 'process_dialog';
    const schema = {
      ProcessDialog: {
        data: { mode: 'createMode', schema: val },
      },
    };
    this.fetchForm(componentName);
    this.commonModels(schema);
  }

  fetchForm(template: string) {
    this.formComponent = this.$GlobalComponentImporter.registerComponent(
      template,
      `cards/services/`
    );
  }

  commonModels(val: any) {
    this.common.models = val;
  }

  async onProcessCreated(v: any) {
    createInteragencyTemplate(v.file, this.childInteragency.id);
    this.processData = v;
    this.readingBpmm = true;
    this.bpmnSchema = await v.file.text();
    this.readingBpmm = false;
  }

  async onDelete() {
    if (this.template?.id) {
      try {
        const { data } = await unlink(
          this,
          'Interagency',
          this.childInteragency,
          'bpmnTemplate',
          this.template.id
        );
        if (data.success) {
          const {
            data,
          } = await interagencyTemplateApi.deleteInteragencyTemplate(
            [this.template.id]
          );
          if (data.success) {
            this.processData = null;
            this.bpmnSchema = '';
            notifySuccess('Процесс успешно сохранен');
          }
        }
      } catch (e) {
        if (e instanceof Error) {
          notifyError(e.message);
        }
      }
    }
  }
}
</script>

<style scoped></style>
