<template>
  <div>
    <q-dialog v-model="open" @hide="hideModal">
      <q-card
        v-if="model"
        class="full-width q-pa-md no-shadow"
        style="max-width: 500px"
      >
        <q-card-section>
          <div class="text-h6">
            {{ $t('registries.objectCard.annulInfo') }}
          </div>
        </q-card-section>
        <q-card-section class="q-gutter-y-md">
          <form-generator-wrapper
            v-if="model && schema"
            :schema="schema"
            :model="model"
            mode="preview"
            :hideNulls="true"
          />
          <BaseLabelValue v-if="model.importFile && model.importFile.Link">
            <template v-slot:label>{{
              $t('registries.unloadingList.importFile')
            }}</template>
            <template v-slot:value>
              <q-btn
                color="primary"
                :label="model.importFile.Name"
                @click="
                  saveImportFile(model.importFile.Link, model.importFile.Name)
                "
              />
            </template>
          </BaseLabelValue>
        </q-card-section>
      </q-card>
    </q-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Prop, PropSync, Vue, Watch } from 'vue-property-decorator';
import { convertDateFromTimestamp } from '@utils/format-date';
import { DateFormat } from '@constants/utils/format-date';
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import { saveAs } from 'file-saver';
import { notifyError } from '@utils/notify';
import isEmpty from 'lodash/isEmpty';
import cloneDeep from 'lodash/cloneDeep';
import FormGeneratorWrapper from '../common/node-generator/FormGeneratorWrapper.vue';
@Component({
  components: {
    FormGeneratorWrapper,
  },
})
export default class InfoDialog extends Vue {
  @PropSync('openDialog') open?: boolean;
  @Prop() model!: Record<string, unknown>;
  @Prop() formKey!: string;

  schema = null;

  @Watch('open')
  onOpenCange(open?: boolean): void {
    if (open && !this.schema) {
      this.initSchema();
    }
  }

  private hideModal(): void {
    this.open = false;
  }

  private async saveImportFile(url: string, fileName: string): Promise<void> {
    try {
      const { file } = await S3UrlSignerFilesService.fetchFileFromS3ByUrl({
        url,
      });
      saveAs(file, `${fileName}.xml`);
    } catch (e) {
      if (e instanceof Error) notifyError(e.message);
    }
  }

  private formatDate(date: string): string {
    return convertDateFromTimestamp(date, DateFormat.date);
  }

  async initSchema(): Promise<void> {
    try {
      let schema = this.$store.getters['utils/cards/getSchemaByPath'](
        this.formKey
      );

      if (isEmpty(schema)) {
        schema = await this.$store.dispatch(
          'personalAccounts/forms/loadSchema',
          this.formKey
        );

        this.$store.commit('utils/cards/addSchema', {
          schema,
          path: this.formKey,
        });
      }
      this.schema = cloneDeep(schema);
    } catch (error) {
      console.error(error);
      console.warn(
        `[perconal-accounts/personal] Couldn't get schema ${this.formKey} `
      );
    }
  }
}
</script>

<style scoped>
  .list-section {
    border-top: 1px solid rgba(0, 0, 0, 0.12);
  }
</style>