<template>
  <div class="staging-export q-pa-md">
    <h1 class="page-header">
      Экспорт данных
      <r-btn
        label="Сформировать новый файл для выгрузки..."
        transparent
        :disable="tableData.some(({ status }) => status === '1')"
        icon="pgs-export"
      >
        <q-menu
          :offset="[0, 12]"
          transition-show="jump-down"
          transition-hide="jump-up"
          auto-close
        >
          <div class="task-type-menu">
            <p class="menu-title">Задача для выгрузки:</p>
            <r-btn
              label="Присвоение военного идентификатора"
              transparent
              @click="createFile"
            />
            <r-btn
              label="Присвоение военного идентификатора для постановки в 17 лет"
              transparent
              @click="createFileForSeventeen"
            />
            <r-btn
              v-if="$AC.haveScope($AC.scopes.MILITARY_RECRUIT_SPECIALIST)"
              label="Подтверждение воинского учёта при конвертации"
              transparent
              @click="createFileInitiative"
            />
          </div>
        </q-menu>
      </r-btn>
    </h1>
    <re-table
      :loading="loading"
      :data="tableData"
      :columns="columns"
      :hide-pagination="true"
      :rows-per-page-options="[0]"
    >
      <template v-slot:body-item-dateTime="props">
        <template v-if="props.row.status === '1'">
          <upload-status
            class="inline-loader"
            status="pending"
            label="в процессе формирования..."
            :inline="true"
            :label-size="12"
            :size="24"
            :line-width="2"
          />
        </template>
      </template>
      <template v-slot:body-item-fullName="props">
        <template v-if="props.row.status === '1'"><span /></template>
      </template>
      <template v-slot:body-item-file="props">
        <template v-if="props.row.status === '1'"><span /></template>
      </template>
      <template v-slot:body-item-actions="props">
        <template v-if="props.row.status === '1'">
          <span />
        </template>
      </template>
    </re-table>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import {
  LoadListUsersV2,
  PersonRegistryApi,
} from '@/recruits/openapi/person-registry';
import ReTable from '@/recruits/components/common/r-table/index.vue';
import type { RTableColumn } from '@/interfaces';
import UploadStatus from '@/components/common/upload-status/index.vue';
import { fetchDocumentAttachment } from '@/utils/fetch-document-attachment';
import { USER_SCOPES } from '@constants/entities/Scope';

@Component({
  components: {
    ReTable,
    UploadStatus,
  },
  computed: {
    USER_SCOPES() {
      return USER_SCOPES;
    },
  },
})
export default class StagingExport extends Vue {
  personRegistryApi = new PersonRegistryApi();
  loading = false;

  public tableData: LoadListUsersV2[] = [];
  public intervalId?: number;
  public loadingIds: string[] = [];

  get columns(): RTableColumn<LoadListUsersV2>[] {
    const hasScopes = this.$AC.haveOneOfScope([
      this.$AC.scopes.MILITARY_COMMISSAR,
      this.$AC.scopes.MILITARY_RECRUIT_SPECIALIST,
    ]);

    return [
      {
        label: 'Дата и время',
        name: 'dateTime',
        field: 'dateTime',
        width: '180px',
        align: 'left',
        borderless: true,
        componentPath: 'date-time',
        componentOptions: {
          time: true,
        },
      },
      {
        label: 'Причина формирования',
        name: 'loadReasonFormation',
        field: 'loadReasonFormation',
        align: 'left',
        borderless: true,
      },
      {
        label: 'Инициатор',
        name: 'fullName',
        field: 'fullName',
        width: '250px',
        align: 'left',
        borderless: true,
      },
      {
        label: 'Файл',
        name: 'file',
        field: 'fileName',
        align: 'left',
        borderless: true,
        componentPath: 'icon-text-pair',
        componentOptions: {
          icon: 'pgs-file-plus',
          align: 'left',
          iconColor: 'black',
        },
        format: (value): string =>
          this.truncateFileName((value as string) ?? '', 80),
      },
      {
        label: 'Действия',
        name: 'actions',
        width: '110px',
        align: 'center',
        componentPath: 'action-buttons',
        componentOptions: {
          loadingIds: this.loadingIds,
          actions:
            (hasScopes && [
              {
                icon: 'pgs-export',
                color: 'primary',
                cb: this.downloadFile,
              },
            ]) ||
            [],
        },
      },
    ];
  }

  async createFile(): Promise<void> {
    this.$recordActivity({ buttonCode: 'export_create' });
    await this.personRegistryApi.createLoadListV2();
    this.fetchList();
  }

  async createFileForSeventeen(): Promise<void> {
    this.$recordActivity({ buttonCode: 'export_create_seventeen' });
    await this.personRegistryApi.createFileRegistrationAtSeventeenV2();
    this.fetchList();
  }

  async createFileInitiative(): Promise<void> {
    this.$recordActivity({ buttonCode: 'export_initiative' });
    await this.personRegistryApi.createLoadListInitiativeV1();
    this.fetchList();
  }

  async downloadFile({ file, id }: LoadListUsersV2): Promise<void> {
    try {
      this.loadingIds.push(id);
      const fetchFileResult = await fetchDocumentAttachment(
        file,
        'download',
        's3Name',
        's3url'
      );

      if (!fetchFileResult?.file) return;

      await this.personRegistryApi.changeStatusLoadListDocumentV1(id);
      this.$recordActivity({
        buttonCode: 'export_download',
        extraInfo: {
          previewInfo: [
            {
              label: 'файл',
              value: file.s3Name,
            },
          ],
        },
      });
      this.fetchList();
    } catch (e) {
      if (e) {
        this.$q.notify({
          color: 'negative',
          icon: 'error',
          message: (e as Error)?.message ?? e,
        });
      }
    } finally {
      this.loadingIds = this.loadingIds.filter((lid: string) => lid !== id);
    }
  }

  async fetchList(): Promise<void> {
    this.loading = true;
    const { data } = await this.personRegistryApi.getLoadListUsersV2();
    this.tableData = data;
    setTimeout(() => {
      this.loading = false;
    }, 500);
  }

  truncateFileName(fileName: string, len: number): string {
    if (fileName.length <= len) return fileName;
    const extensionIndex = fileName.lastIndexOf('.');
    const extension = fileName.substring(extensionIndex);
    return fileName.substring(0, len - extension.length) + '...' + extension;
  }

  mounted(): void {
    this.fetchList();
    this.intervalId = window.setInterval(this.fetchList, 10000) as number;
  }

  beforeDestroy(): void {
    window.clearInterval(this.intervalId);
  }
}
</script>

<style lang="scss" scoped>
.page-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;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.staging-export {
  height: calc(100vh - 50px);
  display: grid;
  grid-template-rows: min-content min-content 1fr;
  gap: 16px;
}

.q-table__container::v-deep {
  overflow: auto;
  padding-right: 6px;
  .q-table__top {
    position: sticky;
    top: 0;
    z-index: 100;
    background: #f7f9fb;
    padding-left: 0;
    padding-right: 0;
  }
  .q-table__grid-content {
    flex: unset;
    align-items: flex-start;
  }

  .RTable-Col.RTable-Col_AlignLeft:first-child {
    overflow: visible;
  }

  .RTable-SubCol_AlignLeft {
    max-width: 100%;
  }
  .RTable-Row {
    position: relative;
    min-height: 46px;
    box-sizing: border-box;
  }

  .RTable-Col {
    position: static;
  }

  .inline-loader {
    background-color: #e1ecf3;
    border-radius: 6px;
    // height: 34px;
    color: rgba(2, 12, 18, 0.58);
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
  }
  .cancel-button {
    border-color: transparent;
    margin-bottom: -6px;
    margin-top: -6px;
    .q-btn__wrapper {
      padding-left: 10px;
      padding-right: 10px;
    }
  }
}

.task-type-menu {
  .menu-title {
    color: rgba(2, 12, 18, 0.58);
    font-family: 'Golos UI', sans-serif;
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    margin: 0;
  }

  padding: 12px;
  display: flex;
  gap: 12px;
  flex-direction: column;
}
</style>
