<template>
  <div class="column q-gutter-y-md">
    <div v-for="documentType in documentsGroups" class="DocumentTables q-gutter-y-sm">
      <div class="DocumentTables-Header">
        {{ documentType.title }}
      </div>
      <template v-for="document in documentType.documents">
        <div v-if="getTableTitle(document)" class="section-title">
          {{ getTableTitle(document) }}
        </div>
        <q-table
          :key="document[0].id"
          :data="document"
          :columns="columns"
          class="DocumentTables-Table"
          :pagination="pagination"
          separator="none"
          hide-bottom
          wrap-cells
          binary-state-sort
        >
          <template v-slot:header="props">
            <q-tr :props="props" class="DocumentTables-Theader">
              <q-th
                v-for="col in props.cols"
                :key="col.name"
                :props="props"
                class="DocumentTables-TH header-text"
              >
                {{ col.label }}
              </q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props" class="DocumentTables-Row">
              <q-td class="DocumentTables-Cell" name="type">
                <div>
                  <DocumentPreviewDialog
                    :key="props.row.id"
                    :common="common"
                    :row="props.row"
                    :model="model"
                    :user-task="userTask"
                  >
                    <template #button>
                      <div>
                        <span>{{ props.row.type.name }}</span>
                        <template v-if="props.row.file">
                          /
                          <span class="file-name">
                            {{ props.row.file.name }}
                            <q-badge v-if="props.row.receivedFrom15">new</q-badge><!-- TODO: Это пришло от PGSRUSH-2900 - Mironov Yuriy -->
                          </span>
                        </template>
                      </div>
                    </template>
                  </DocumentPreviewDialog>
                </div>
              </q-td>
              <q-td class="DocumentTables-Cell" name="modified">
                {{ parseUnixTime(props.row.modified).format("DD.MM.YYYY HH:mm") }}
              </q-td>
              <q-td class="DocumentTables-Cell" name="file">
                <div class="row text-no-wrap float-right">
                  <base-preview
                    :extension="get(props.row, 'file.name', '').split('.').pop()"
                    :s3-url="get(props.row, 'file.url')"
                  >
                    <q-btn
                      flat
                      dense
                      :icon="icons.view"
                      size="12"
                      style="color: #107ABC;"
                    >
                      <template #loading>
                        <q-spinner-gears />
                      </template>
                      <q-tooltip>
                        {{ $t('base.preview.dialog.title') }}
                      </q-tooltip>
                    </q-btn>
                  </base-preview>
                  <q-btn
                    :disable="!get(props.row, 'file.url')"
                    flat
                    dense
                    :icon="icons.down"
                    size="12"
                    style="color: #107ABC;"
                    @click="fetchDocumentAttachment(props.row, 'download')"
                  >
                    <q-tooltip>
                      {{ $t('documents.download') }}
                    </q-tooltip>
                  </q-btn>
                  <q-btn
                    v-if="props.row.sign"
                    flat
                    dense
                    :icon="icons.validSignature"
                    size="16"
                    style="color: rgba(0, 0, 0, 0.54)"
                    color="positive"
                    @click="signatureHandler(props.row, 'info')"
                  >
                    <q-tooltip>
                      {{ $t('documents.viewingEDSData') }}
                    </q-tooltip>
                  </q-btn>
                  <div v-show="props.row.source !== 'ЕПГУ' && canEdit">
                    <DocumentEditDialog
                      :key="props.row.id"
                      :common="common"
                      :row="props.row"
                      :model="model"
                      :user-task="userTask"
                    >
                      <template #button>
                        <q-btn
                          flat
                          dense
                          :icon="icons.edit"
                          size="16"
                          style="color: #107ABC;"                          
                        >
                          <q-tooltip>
                            {{ $t('base.edit') }}
                          </q-tooltip>
                        </q-btn>
                      </template>
                    </DocumentEditDialog>
                  </div>
                  <div v-show="props.row.source !== 'ЕПГУ' && canEdit">
                    <DocumentUploaderDialog
                      :key="props.row.id"
                      :common="common"
                      :row="props.row"
                      :model="model"
                      :user-task="userTask"
                    >
                      <template #button>
                        <q-btn
                          flat
                          dense
                          :icon="icons.up"
                          size="16"
                          style="color: #107ABC;"                          
                        >
                          <q-tooltip>
                            {{ $t('base.uploader.upload') }}
                          </q-tooltip>
                        </q-btn>
                      </template>
                    </DocumentUploaderDialog>
                  </div>
                  <q-btn
                    v-show="
                    props.row.template &&
                    actions.includes('printDocumentTemplate')
                  "
                    flat
                    dense
                    :icon="icons.template"
                    size="16"
                    style="color: #107ABC;"                          
                    @click="
                    fetchDocumentAttachment(
                      props.row,
                      'download',
                      'template.name',
                      'template.url'
                    )
                  "
                  >
                    <q-tooltip>
                      {{ $t('documents.printForm') }}
                    </q-tooltip>
                  </q-btn>
                  <q-btn
                    v-if="
                    props.row.source !== 'ЕПГУ' &&
                    actions.includes(deleteDocuments.button.id) &&
                    props.row.type.code !== 'criterRedefining'
                  "
                    flat
                    dense
                    :icon="icons.delete"
                    size="16"
                    style="color: rgba(0, 0, 0, 0.54)"
                    color="negative"
                    @click="showDeleteDialog(props.row)"
                  >
                    <q-tooltip>
                      {{ $t('base.delete') }}
                    </q-tooltip>
                  </q-btn>
                </div>
              </q-td>
            </q-tr>
          </template>
        </q-table>
      </template>
    </div>
    <q-dialog v-model="deleteDocuments.dialog.value">
      <q-card class="no-shadow">
        <q-card-section>
          <div class="text-h6">
            {{ $t('documents.confirmation') }}
          </div>
        </q-card-section>
        <q-card-section class="q-pt-none">
          {{ $t('documents.deleteQuestion') }}
        </q-card-section>
        <q-card-actions align="right">
          <q-btn
            flat
            :label="$t('base.no')"
            color="primary"
            @click="hideDeleteDialog"
          />
          <q-btn
            flat
            :label="$t('base.yes')"
            color="red"
            @click="deleteDocument"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <loader-with-text
      message="Выполняется удаление документа"
      :flag="loaderWithTextFlag"
    />
  </div>
</template>

<style lang="scss" scoped>

.header-text {
  font-family: 'Golos Text', sans-serif;
  font-style: normal;
  font-weight: 600;
  font-size: 10px;
  line-height: 12px;
  letter-spacing: 0.05em;
  text-transform: uppercase;
}

.file-name {
  word-break: break-word;
  font-style: normal;
  font-weight: 400;
  font-size: 12px;
  line-height: 14px;
  color: rgba(2, 12, 18, 0.58);  
}

.DocumentTables {
  display: flex;
  flex-direction: column;
  font-family: 'Golos UI', sans-serif;

  .section-title {
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    line-height: 18px;
    letter-spacing: -0.015em;
  }

  &-Header {
    margin-top: 0;
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 400;
    font-size: 18px;
    line-height: 22px;
    letter-spacing: -0.015em;
    color: rgba(2, 12, 18, 0.9);     
  }
  &-Table {
    font-family: 'Golos UI', sans-serif;
  }
  &-Theader {
    height: auto;
    display: grid;
    grid-template-columns: 3fr 110px 160px;
    padding: 0 6px 0 0;
    white-space: nowrap;
    color: rgba(2, 12, 18, 0.58);
  }
  &-TH {
    padding-right: 0;
    padding-left: 0;
    display: flex;
    &:nth-last-child(-n+2) {
      justify-content: flex-end;
    }
  }
  &-Row {
    background: rgba(38, 117, 166, 0.025);
    border: 1px solid rgba(1, 72, 116, 0.11);
    border-radius: 8px;
    display: grid;
    grid-template-columns: 3fr 110px 160px;
    margin-bottom: 4px;
  }
  &-Cell {
    padding: 0;
    height: auto;
    display: flex;
    align-items: center;
    &:not(:last-child) {
      padding-right: 4px;
    }
    &:first-child {
      padding: 4px 0 4px 4px;
    }
    &:last-child {
      justify-content: flex-end;
    }
    &[name="type"] {
      font-style: normal;
      font-weight: 500;
      font-size: 14px;
      line-height: 16px;
      color: rgba(2, 12, 18, 0.9);
    }
    &[name="modified"] {
      font-style: normal;
      font-weight: 400;
      font-size: 12px;
      line-height: 14px;
      color: rgba(2, 12, 18, 0.58);
      justify-content: flex-end;
    }
  }
}
</style>

<script>
import { Component, Prop, Vue } from 'vue-property-decorator';
import { WorkflowServiceApi } from '@openapi/wf';
import get from 'lodash/get';
import moment from 'moment';
import DocumentUploaderDialog from '@components/cards/statements/DocumentUploaderDialog';
import DocumentEditDialog from '@components/cards/statements/DocumentEditDialog';
import DocumentPreviewDialog from '@components/cards/statements/DocumentPreviewDialog';
import { fetchDocumentAttachment } from '@utils/fetch-document-attachment';
import { notifyError, notifySuccess } from '@utils/notify';
import LoaderWithText from '@components/common/loader';

const wfApi = new WorkflowServiceApi();

@Component({
  methods: {
    fetchDocumentAttachment,
    get,
  },
  components: {
    DocumentUploaderDialog,
    DocumentEditDialog,
    DocumentPreviewDialog,
    LoaderWithText,
  },
})
export default class DocumentTables extends Vue {
  @Prop() documents;
  @Prop() columns;
  @Prop() common;
  @Prop() model;
  @Prop() userTask;
  @Prop() actions;

  icons = {
    eds: 'gesture',
    validSignature: 'gesture',
    view: 'pgs-search',
    template: 'pgs-print',
    down: 'pgs-import',
    delete: 'pgs-delete',
    up: 'pgs-paperclip',
    edit: 'pgs-edit',
  };

  deleteDocuments = {
    button: {
      id: 'deleteDocument',
    },
    documents: [],
    dialog: {
      value: false,
    },
  };

  pagination = {
    rowsPerPage: 0,
  };

  loaderWithTextFlag = false;

  get loading() {
    return !this.model;
  }

  get canEdit() {
    return (
      Array.isArray(this.actions) &&
      (this.actions.includes('uploadDocument') ||
        this.actions.includes('addDocument'))
    );
  }

  get markeredDocuments() {
    return (get(this.$route, 'query.markeredDocuments') || '').split(',');
  }

  getTableTitle(document) {
    const isThereGroup = document.filter((item) => item.group);

    if (isThereGroup.length > 0 && isThereGroup[0].source === 'ЕПГУ') {
      return `Субъект: ${document[0].group}`;
    }

    return '';
  }

  // Структурирование данных в группы
  get documentsGroups() {
    const filteredDocuments = this.documents.filter(
      (element) => element.documents.length > 0
    );

    const namelessGroup = 'nameless-group';

    filteredDocuments.forEach((documentType) => {
      // Определяем количество групп
      // Если поле группы отсутсвует (undefined), то так же добавляем ключ для безымянной группы
      const groupUnique = [
        ...new Set(
          documentType.documents.map((item) => item.group || namelessGroup)
        ),
      ];

      // Подготавливаем структуру объектов для наполнения
      const groupStructure = groupUnique.reduce(
        (previousValue, currentValue) => ({
          ...previousValue,
          [currentValue]: [],
        }),
        {}
      );

      documentType.documents.forEach((document) => {
        groupStructure[document.group || namelessGroup].push(document);
      });

      documentType.documents = groupStructure;
    });

    return filteredDocuments;
  }

  signatureHandler(attachment, dialogType) {
    this.signature.attachment = attachment;
    this.signature.dialog.type = dialogType;

    switch (dialogType) {
      case 'create':
        this.$store
          .dispatch('utils/cryptoPro/fetchCertificates')
          .then((certificates) => {
            this.signature.certificates = certificates.map((certificate) => ({
              label: certificate.subjectName,
              value: certificate,
            }));

            if (this.signature.certificates.length) {
              this.signature.dialog.value = true;
            } else {
              notifyError(
                this.$t('documents.noCertificatesFound'),
                'warning',
                'warning'
              );
            }
          })
          .catch((e) => {
            notifyError(e.message.toString());
          });

        break;
      case 'info':
        this.signature.dialog.value = true;
        // attachment.signatureInfo - тут лежит инфа о подписи

        break;
    }
  }

  showDeleteDialog(document) {
    this.deleteDocuments.documents = [document];

    this.deleteDocuments.dialog.value = true;
  }

  hideDeleteDialog() {
    this.deleteDocuments.documents = [];

    this.deleteDocuments.dialog.value = false;
  }

  deleteDocument() {
    this.loaderWithTextFlag = true;
    wfApi
      .submitForm(get(this.userTask, 'userTask.taskId'), {
        id: this.deleteDocuments.button.id,
        data: {
          docIds: this.deleteDocuments.documents.map((document) => document.id),
        },
      })
      .then(() => {
        notifySuccess('Документ успешно удален');
      })
      .catch(() => {
        notifyError('Удаление документа не удалось');
      })
      .finally(() => {
        this.loaderWithTextFlag = false;
      });
    this.hideDeleteDialog();
  }

  parseUnixTime(integer) {
    return moment.unix(integer);
  }
}
</script>
