<template>
  <q-dialog v-model="dialog" :persistent="loading">
    <q-card class="full-width no-shadow" style="max-width: 800px">
      <q-form ref="correctionsForm" @submit="uploadDocument">
        <q-card-section>
          <div class="text-h6">
            {{ $t('registries.uploadObjectTitle') }}
          </div>
          <q-banner rounded class="q-mt-md grey-banner q-py-xs">
            <div class="text-grey-9">
              {{ title }}
            </div>
          </q-banner>
        </q-card-section>
        <q-card-section class="q-pb-md">
          <q-file
            v-model="file"
            accept=".xml"
            label="Файл формата xml"
            clearable
            filled
          >
            <template #prepend>
              <q-icon name="attach_file" />
            </template>
          </q-file>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            type="submit"
            :loading="loading"
            :label="$t('registries.uploadBtnLabel')"
            unelevated
            color="primary"
          >
            <template #loading>
              <q-spinner-gears />
            </template>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import { Component, Prop, PropSync, Vue } from 'vue-property-decorator';
import get from 'lodash/get';
import { startWithFiles } from '@services/wf';

const IMPORT_PAYMENT_STATUS = 'ImportPaymentMirReport';

@Component({
  components: {},
})
export default class UploadPaymentStatus extends Vue {
  @PropSync('open') dialog?: boolean;
  @Prop() schema!: string;
  @Prop() title!: string;
  private file: File | undefined | null = null;
  private loading = false;

  uploadDocument() {
    this.loading = true;
    if (this.file) {
      startWithFiles({
        file: this.file,
        json: {
          processKey: IMPORT_PAYMENT_STATUS,
          userId: this.$store.getters['oidcClient/currentUser'].sub,
        },
      }).then(({ data: { msg = '' } }) => {
        this.file = null;
        this.loading = false;
        this.dialog = false;
        const traceIdMatch = msg.match(/traceId=[a-zA-Z0-9-]+/);
        let traceId = '';
        if (traceIdMatch) {
          traceId = traceIdMatch[0].slice(8);
        }

        const handler = (e: any) => {
          const data = JSON.parse(get(e, 'data', '{}'));
          if (data.traceId === traceId) {
            console.log('[UploadRegistryItem] import push', data);
            this.$emit('upload');
            this.$websockets.removeListener(handler);
          }
        };
        this.$websockets.addListener(handler);
      });
    }
  }
}
</script>
