<template>
  <div class="q-pa-md Import">
    <div class="row">
      <span class="header">
        Загрузить список граждан, состоящих на воинском учёте
      </span>
    </div>
    <q-card>
      <q-card-section>
        <r-file-loader
          ref="csvFileLoader"
          :multiply="false"
          supportedFile=".csv"
          @change="addFileCsv"
        />
      </q-card-section>
      <q-card-section class="q-pt-none">
        <r-btn
          :disable="!filesCsv"
          :title="!filesCsv && 'Нет файла для загрузки'"
          label="Загрузить"
          @click="loadFile"
        />
      </q-card-section>
    </q-card>
    <import-results-dialog v-model="requestImportDialog" :result="result" />
    <q-dialog v-model="apiErrorShow" no-backdrop-dismiss>
      <process-api-error :errorObject="errorObject" />
    </q-dialog>

    <screen-blocker v-if="isShowBlocker">
      <progress-bar :progress="uploadPercentage">
        Идет процесс загрузки
      </progress-bar>
    </screen-blocker>
  </div>
</template>

<style lang="scss" scoped>
.header {
  font-family: 'Golos Text', sans-serif;
  font-style: normal;
  font-weight: 500;
  font-size: 28px;
  line-height: 32px;
  letter-spacing: -0.02em;
  color: rgba(2, 12, 18, 0.9);
  margin-bottom: 20px;
}
</style>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import {
  PersonRegistryApi,
  RegisteredImportResult,
} from '@/recruits/openapi/person-registry';
import ProcessApiError from '@/recruits/components/dialogs/ProcessApiError.vue';
import ImportResultsDialog from './import-results-dialog.vue';
import ProgressBar from '@components/common/progress-bar/index.vue';
import ScreenBlocker from '@components/common/screen-blocker/index.vue';
import { AxiosRequestConfig } from 'axios';
import { callMethodOnComponent, formatBytes } from '@/recruits/utils';

interface FileInfo {
  file: File;
  fileName: string;
  fileSize: string;
}

@Component({
  components: {
    ProcessApiError,
    ImportResultsDialog,
    ProgressBar,
    ScreenBlocker,
  },
  methods: {
    formatBytes,
  },
})
export default class ImportConscripts extends Vue {
  public requestImportDialog = false;
  public filesCsv: File | null = null;
  public result: RegisteredImportResult = {};
  apiErrorShow = false;
  errorObject = {};
  uploadPercentage = 0;
  isShowBlocker = false;
  private personRegistryApi = new PersonRegistryApi();

  @Watch('uploadPercentage')
  checkUpload(uploadPercentage: number): void {
    if (uploadPercentage === 100) {
      this.uploadPercentage = 0;
      this.isShowBlocker = false;

      this.$q.loading.show({
        message: 'Обработка данных',
      });
    }
  }

  public addFileCsv(file: FileInfo[]): void {
    this.filesCsv = file?.length ? file[0].file : null;
  }

  async loadFile(): Promise<void> {
    if (!this.filesCsv) return;
    this.isShowBlocker = true;

    try {
      const { data } = await this.personRegistryApi.importForRegistered(
        this.filesCsv,
        this.importOptions(this)
      );
      this.result = data;
      this.requestImportDialog = true;
    } catch ({ response }) {
      this.apiErrorShow = true;
      this.errorObject = {
        data: {
          message: response?.data?.descName,
          description: response?.data?.description?.details,
        },
      };
    } finally {
      this.$q.loading.hide();
      callMethodOnComponent(this.$refs.csvFileLoader, 'clearResults');
    }
  }

  importOptions = (that = this): AxiosRequestConfig => {
    return {
      onUploadProgress: (progressEvent: {
        loaded: number;
        total: number;
      }): void => {
        const { loaded, total } = progressEvent;
        that.uploadPercentage = Math.round((loaded / total) * 100);
      },
    };
  };
}
</script>
