<template>
  <div class="q-pa-md q-col-gutter-y-md redesigned">
    <div class="row q-gutter-sm">
      <div class="col-12 col-sm text-h5 section-header">
        Запросы личного дела
      </div>
      <div class="ButtonsBlock">
        <!-- <r-btn
          label="Импортировать коды загрузки ЛД"
          transparent
          @click="importCodes"
        /> -->
        <div class="DopButton" v-if="selectedIds.length">
          <div class="row flex items-center">
            <div class="q-pr-sm">
              <span class="DopButton-TextFiled"> Выбрано: </span>
              <span class="DopButton-TextField DopButton-TextFiled__Bold">
                {{ selectedIds.length }}
              </span>
            </div>
            <r-btn label="Скачать пакет запросов ЛД" icon="pgs-import" />
          </div>
        </div>
      </div>
    </div>
    <div class="row">
      <div class="col-12">
        <div class="row">
          <div class="col-12">
            <search-bar
              v-model="filter"
              @search="executeSearch"
              :loading="loading"
            />
          </div>
          <div class="col-12">
            <sort-bar
              v-model="sortButtons"
              :pagination="pagination"
              @click="handleSortClick"
              :loading="loading"
            />
          </div>
          <div class="col-12">
            <div class="row">
              <!-- :selection="
                  $AC.haveOneOfScope([
                    $AC.scopes.MILITARY_RECRUIT_SPECIALIST,
                    $AC.scopes.MILITARY_COMMISSAR,
                  ])
                    ? 'multiple'
                    : 'none'
                " -->
              <data-table
                selection="none"
                :loading="loading"
                :data="data"
                :pagination.sync="pagination"
                :selected="selectedIds"
                @request="onRequest"
                @update:selected="rowSelected"
                @download-personal-file="downloadPersonalFile"
                @download-quittance="downloadQuittance"
                :rows-per-page-options="[10, 25, 50, 100]"
                :disabled-mass-checkbox="
                  !data.some(({ choosable }) => choosable)
                "
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- <download-personal-files
      :opened.sync="isPersonalFilesModalOpened"
      :data="data"
      :selected-ids="selectedIds"
    /> -->
    <import-codes
      :data="data"
      :opened.sync="isImportCodesModalOpened"
      @close="isPersonalFilesModalOpened = false"
    />
  </div>
</template>

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

<script lang="ts">
import { Component, Mixins } from 'vue-property-decorator';
import Vue from 'vue';
import {
  PersonRegistryApi,
  LoadLdResponseV1,
} from '@/recruits/openapi/person-registry';
import SortBar from '@/recruits/components/common/sort-bar.vue';
import { SortingOption, UrlQueryParams } from '@/recruits/models';
import DataTable from './data-table.vue';
import SearchBar from './search-bar.vue';
import { SearchFilterUtils } from '@/recruits/utils/search-filter';
import { prepareApiParams } from '@/recruits/utils/prepare-api-params';
import UrlIntegratedSearch from '@/recruits/mixins/url-integrated-search';
import ImportCodes from './dialogs/ImportCodes.vue';
// import DownloadPersonalFiles from './dialogs/DowloadPersonalFiles.vue';
import { fetchDocumentAttachment } from '@/utils/fetch-document-attachment';
import { saveBlob } from '@/utils/files';
import S3UrlSignerFilesService from '@services/s3urlsigner/files';

@Component({
  components: {
    DataTable,
    SearchBar,
    SortBar,
    ImportCodes,
    // DownloadPersonalFiles,
  },
})
export default class PersonalFileRequests extends Mixins(UrlIntegratedSearch) {
  RecruitApi = new PersonRegistryApi();

  public sortButtons: Array<SortingOption<LoadLdResponseV1>> = [
    // { label: 'По номеру', value: 'number' },
    { label: 'По ФИО', value: 'fullName' },
    { label: 'По дате рождения', value: 'birthDate' },
    { label: 'По ИД ЕРН', value: 'idERN' },
    { label: 'По статусу', value: 'status' },
    { label: 'По дате запроса', value: 'requestDate' },
  ];

  public isPersonalFilesModalOpened = false;
  public isImportCodesModalOpened = false;

  public filter = new SearchFilterUtils();
  public data: Array<LoadLdResponseV1> | undefined = [];
  public selectedIds: string[] = [];

  public async fetchData(
    query: UrlQueryParams
  ): Promise<{ totalRows: number | undefined }> {
    const params = prepareApiParams(query);
    const { data } = await this.RecruitApi.getPersonalFileV1(params);
    this.data = data.data || [];
    this.$emit('data-loading', { data: this.data, loading: false });
    return {
      totalRows: data.totalRows,
    };
  }

  rowSelected(val: string[]): void {
    Vue.set(this, 'selectedIds', val);
  }

  importCodes(): void {
    this.isImportCodesModalOpened = true;
  }

  created(): void {
    this.searchOnMounted = false;
  }

  async downloadQuittance(file: LoadLdResponseV1): Promise<void> {
    try {
      if (!file.quittance) {
        this.$q.notify({
          message: 'Файл квитанции не передан',
        });
        return;
      }

      const { s3Name: fileName, s3url } = file.quittance;

      const { file: blob } = await S3UrlSignerFilesService.fetchFileFromS3ByUrl(
        {
          url: s3url,
        }
      );
      saveBlob({
        blob,
        fileName,
      });

      const response = await this.RecruitApi.finalizePrivateFileV1(file.id);

      if (response.status === 200) {
        this.$q.notify({
          message: 'Личное дело успешно запрошено',
          color: 'positive',
        });
      }

      await this.refresh();
    } catch (e) {
      if (e) {
        this.$q.notify({
          color: 'negative',
          icon: 'error',
          message: (e as Error)?.message ?? e,
        });
      }
    }
  }

  async downloadPersonalFile(file: LoadLdResponseV1): Promise<void> {
    try {
      if (!file.requestDownloadEnable) return;

      const { data } = await this.RecruitApi.generateListRequestsV1({
        privateFileId: file.id,
      });

      await fetchDocumentAttachment(
        {
          s3Name: file.id + '.json',
          s3url: data,
        },
        'download',
        's3Name',
        's3url'
      );
    } catch (e) {
      if (e) {
        this.$q.notify({
          color: 'negative',
          icon: 'error',
          message: (e as Error)?.message ?? e,
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@keyframes appear {
  from {
    max-width: 0;
  }

  50% {
    opacity: 0;
  }

  100% {
    opacity: 1;
    max-width: 100vw;
  }
}
.ButtonsBlock {
  display: flex;
  flex-flow: row;
  align-items: flex-start;
  gap: 16px;
}

.DopButton {
  animation: appear 0.2s ease;
  overflow: hidden;
  height: 42px;
  white-space: nowrap;
  box-sizing: border-box;
  background-color: rgba(15, 32, 160, 0.08);
  border-radius: 20px;
  padding: 4px;
  margin-top: -5px;
  margin-bottom: -5px;
  &-TextFiled {
    white-space: nowrap;
    margin-left: 8px;
    margin-right: 8px;
    font-family: 'Golos UI', sans-serif;
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    line-height: 16px;
    color: rgba(2, 12, 18, 0.58);
    &__Bold {
      font-weight: 500;
      color: #015e98;
    }
  }
  &-Button {
    &__Color {
      &__DarkBlue {
        background: linear-gradient(92.91deg, #1491cf 0%, #0f68a0 100%);
        box-shadow: 0 0.6px 1.8px rgba(7, 46, 71, 0.12),
          0 3.2px 8px rgba(7, 46, 71, 0.15);
        color: rgba(255, 255, 255, 0.92);
      }
    }
  }
}
</style>
