<i18n>
{
  "en": {
    "PackagesCard": {
      "download": "Download",
      "packageAction": "Action",
      "packageName": "Package name",
      "tab": "Application package",
      "user": "User",
      "creationDate": "Creation date",
      "title": "Packages list"
    }
  },
  "ru": {
    "PackagesCard": {
      "download": "Скачать",
      "packageAction": "Действие",
      "packageName": "Название пакета",
      "tab": "Пакет заявления",
      "user": "Пользователь",
      "creationDate": "Дата Формирования",
      "title": "Список пакетов"
    }
  }
}
</i18n>

<template>
  <div class="row q-pa-md justify-center" v-if="common.active === 'packages'">
    <div class="redesigned-packages-tab col-12 max-1280-width">
      <a v-show="false" ref="export" />
      <div v-if="!loading" class="q-gutter-y-md">
        <q-table
          v-if="isArray(packages) && packages.length"
          class="no-shadow text-grey-9"
          row-key="id"
          title-class="text-subtitle1"
          :columns="packagesColumns"
          :data="packages"
          wrap-cells
          :pagination="pagination"
          hide-bottom
          separator="none"
        >
          <template v-slot:header="props">
            <q-tr :props="props" class="header-row">
              <q-th
                v-for="col in props.cols"
                :key="col.name"
                :props="props"
                class="header-cell"
              >
                {{ col.label }}
              </q-th>
            </q-tr>
          </template>

          <template v-slot:body="props">
            <q-tr :props="props" class="entry-row">
              <q-td :prop="props" class="modified-cell">
                {{ convertDateFromTimestamp(props.row.modified) }}
              </q-td>
              <q-td :prop="props" class="file-name-cell">
                {{ props.row.file.name }}
              </q-td>
              <q-td :prop="props" class="creator-cell">
                {{ accounts[props.row.creator] }}
              </q-td>
              <q-td :prop="props" class="actions-cell">
                <div class="actions-bar">
                  <q-btn
                    :disable="!get(props.row, 'file.url')"
                    color="primary"
                    dense
                    flat
                    icon="pgs-import"
                    size="16"
                    style="color: rgba(0, 0, 0, 0.54)"
                    @click="fetchDocumentAttachment(props.row, 'download')"
                  >
                    <q-tooltip>
                      {{ $t('PackagesCard.download') }}
                    </q-tooltip>
                  </q-btn>
                </div>
              </q-td>
            </q-tr>
          </template>
        </q-table>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import { convertDateFromTimestamp } from '@utils/format-date';
import { saveFileViaLink } from '@utils/files';
import { AccountApi } from '@openapi/idm';
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import get from 'lodash/get';
import isArray from 'lodash/isArray';
import isEqual from 'lodash/isEqual';
import { notifyError } from '@utils/notify';

const accountApi = new AccountApi();

export default {
  props: ['common', 'model', 'user-task'],
  data() {
    return {
      accounts: {},
      pagination: {
        rowsPerPage: 0,
      },
    };
  },
  computed: {
    actions() {
      return get(this.userTask, 'userTask.outData.actions') || [];
    },
    packages() {
      return (get(this.model, 'documents') || []).filter((document) =>
        isEqual(document.type.code, 'archivedApplication')
      );
    },
    packagesColumns() {
      return [
        {
          align: 'left',
          field: 'modified',
          label: this.$t('PackagesCard.creationDate'),
          name: 'date',
          sortable: true,
          format: (val) => convertDateFromTimestamp(val),
        },
        {
          align: 'left',
          field: (val) => get(val, 'file.name') || '',
          label: this.$t('PackagesCard.packageName'),
          name: 'file.name',
          sortable: true,
        },
        {
          align: 'left',
          field: 'creator',
          label: this.$t('PackagesCard.user'),
          name: 'creator',
          sortable: false,
        },
        {
          align: 'left',
          field: 'file',
          label: this.$t('PackagesCard.packageAction'),
          name: 'file',
          sortable: false,
        },
      ];
    },
    loading() {
      return !this.model;
    },
  },
  watch: {
    packages(): void {
      const documentsWithCreator = (get(this.model, 'documents') || []).filter(
        (document) =>
          isEqual(document.type.code, 'archivedApplication') &&
          get(document, 'creator')
      );
      let queryString = '';
      documentsWithCreator.forEach((element, index, array) => {
        if (index !== array.length - 1) {
          queryString = queryString + 'id==' + element.creator + ' or ';
        } else {
          queryString = queryString + 'id==' + element.creator;
        }
      });
      if (queryString) {
        accountApi
          .pagingAccounts(
            undefined,
            undefined,
            undefined,
            `(${queryString})`,
            undefined,
            undefined,
            'person'
          )
          .then(({ data }) => {
            for (const x of data.records) {
              this.accounts[x.id] = `${x.person.firstname} ${x.person.surname}`;
            }
          })
          .catch(() => {
            throw new Error(
              '[components][cards][statements][Packages][pagingAccounts]'
            );
          });
      }
    },
  },
  methods: {
    get,
    isArray,
    // Проверить утилиту под данный случай
    fetchDocumentAttachment(
      document,
      mode = 'preview',
      nameField = 'file.name',
      urlField = 'file.url'
    ) {
      const fileName =
        get(document, nameField) ||
        this.$t('statements.DocumentsCard.unnamed').toString();
      const url = get(document, urlField);

      if (url) {
        S3UrlSignerFilesService.fetchFileFromS3ByUrl({ url })
          .then(({ presignedUrl }) => {
            const setTargetMode = (mode: string): string => {
              switch (mode) {
                case 'download': {
                  return '_self';
                }
                case 'preview': {
                  return '_blank';
                }
                default:
                  return '';
              }
            };
            saveFileViaLink({
              anchor: this.$refs.export,
              hrefData: presignedUrl,
              fileName,
              target: setTargetMode(mode),
            });
          })
          .catch((e) => {
            notifyError(e.message.toString());
          });
      } else {
        notifyError(
          this.$t('statements.DocumentsCard.documentFileUrlIsEmpty').toString()
        );
      }
    },
    convertDateFromTimestamp,
  },
};
</script>

<style lang="scss" scoped>

.header-row {
  height: initial;
  display: grid;
  grid-template-columns: 18% 1fr 1fr 80px;
  .header-cell {
    padding: 7px !important;
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 600;
    font-size: 10px !important;
    line-height: 12px;
    letter-spacing: 0.05em;
    text-transform: uppercase;
    color: rgba(2, 12, 18, 0.58); 
    white-space: nowrap;
    overflow: hidden;
  }
}

.entry-row {
  height: auto;
  display: grid;
  grid-template-columns: 18% 1fr 1fr 80px;

  background: rgba(38, 117, 166, 0.025);
  border: 1px solid rgba(1, 72, 116, 0.11);
  border-radius: 8px;
  margin-bottom: 4px;
}

@mixin cell-style {
  height: auto;
  display: flex;
  align-items: center;
  padding: 0 0 0 7px;
}

.modified-cell {
  @include cell-style;
  font-style: normal;
  font-weight: 400;
  font-size: 12px;
  line-height: 14px;
  color: rgba(2, 12, 18, 0.58);
  overflow: hidden;
}

.file-name-cell {
  @include cell-style;
  word-break: break-all;

  font-style: normal;
  font-weight: 500;
  font-size: 14px !important;
  line-height: 16px;
  color: rgba(2, 12, 18, 0.9);
}

.creator-cell {
  @include cell-style;
  font-family: 'Golos UI', sans-serif;
}

.actions-cell {
  @include cell-style;
  .actions-bar {
    width: 100%;
    display: flex;
    justify-content: right;
  }
}  

</style>
