<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')"
            :disabled="!file"
            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 S3UrlSignerFilesService from '@services/s3urlsigner/files';
import { S3Api } from '@openapi/personal-accounts';
import { WorkflowServiceApi } from '@openapi/wf';
import { notifyError } from '@/utils/notify';
const wfApi = new WorkflowServiceApi();

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

  async uploadDocument(): Promise<void> {
    this.loading = true;
    let traceId = '';
    if (this.file instanceof File) {
      try {
        const { data: file } = await new S3Api().putFileToS3(this.file);
        // TODO Если получится то переиспользовать urlsigner
        // const currentUser = this.$store.getters['oidcClient/currentUser'];
        // const s3url = await S3UrlSignerFilesService.uploadFileToS3ByPath({
        //   file: this.file,
        //   path: `${this.file.name}`,
        //   options: {
        //     params: {
        //       bucket: 'personal-account-service',
        //       orgId: currentUser?.domain_id ?? '',
        //       region: 'us-east-1',
        //     },
        //   },
        // });

        const {
          data: { msg = '' },
        } = await wfApi.start({
          processKey: this.processKey,
          data: {
            s3Url: file.s3link,
            fileName: file.filename,
            registryPaymentCode: this.registryPaymentCode,
            userId: this.$store.getters['oidcClient/currentUser'].sub,
            filetype: this.file.type,
          },
        });

        this.file = null;
        this.loading = false;
        this.dialog = false;
        const traceIdMatch = msg.match(/traceId=[a-zA-Z0-9-]+/);
        if (traceIdMatch) {
          traceId = traceIdMatch[0].slice(8);
        }
      } catch (e) {
        if (e instanceof Error) notifyError(e.message);
      }

      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>
