<template>
  <centered-1280-box class="Application">
    <p class="Application-Header">Заявления</p>
    <q-table
      class="Table"
      :data="data.application"
      :columns="columns"
      :rows-per-page-options="[0]"
      row-key="id"
    >
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th
            auto-width
            v-for="col in props.cols"
            :key="col.name"
            :props="props"
            >{{ col.label }}</q-th
          >
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props" no-hover>
          <q-td auto-width>
            <q-btn
              v-if="showExpandButton(props.row)"
              size="sm"
              round
              dense
              @click="props.expand = !props.expand"
              :icon="props.expand ? 'remove' : 'add'"
              style="background-color: var(--q-color-primary); color: white"
            />
          </q-td>
          <q-td auto-width :props="props" key="number">
            {{ props.row.number }}
          </q-td>
          <q-td auto-width :props="props" key="dateStart">
            {{ formatDate(props.row.dateStart) }}
          </q-td>
          <q-td auto-width :props="props" key="dateMax">
            {{ formatDate(props.row.dateMax) }}
          </q-td>
          <q-td auto-width :props="props" key="status">
            {{ getStatus(props.row.status) }}
          </q-td>
          <q-td auto-width :props="props" key="reason">
            {{ props.row.reason }}
          </q-td>
          <q-td auto-width :props="props" key="actions">
            <reject-application
              v-if="
                $AC.haveOneOfScope([
                  $AC.scopes.MILITARY_RECRUIT_SPECIALIST,
                  $AC.scopes.SYSTEM_ADMINISTRATOR,
                ]) && props.row.status === '1'
              "
              :model="props.row"
              :personId="data.id"
              @done="$emit('refresh')"
            />
            <div
              v-if="
                $AC.haveOneOfScope([
                  $AC.scopes.MILITARY_COMMISSAR,
                  $AC.scopes.SYSTEM_ADMINISTRATOR,
                ]) &&
                (props.row.status === '1.2' || props.row.status === '1.1')
              "
              class="Application-ButtonsBlock"
            >
              <sign-reject-application
                class="Application-Button"
                process-key="milBaseMassSignProcess"
                :model="getDataForSign(props.row)"
                title="Подписание"
                @done="$emit('refresh')"
              />
            </div>
            <!-- <div
              v-if="
                $AC.haveOneOfScope([
                  $AC.scopes.MILITARY_RECRUIT_SPECIALIST,
                  $AC.scopes.SYSTEM_ADMINISTRATOR,
                ]) &&
                (props.row.status === '1.2' || props.row.status === '1.1')
              "
              class="Application-ButtonsBlock"
            >
              <cancel-application
                class="Application-Button"
                :model="props.row"
                :personId="data.id"
                @done="$emit('refresh')"
              />
              <edit-application
                :model="props.row"
                :personId="data.id"
                @done="$emit('refresh')"
              />
            </div> -->
          </q-td>
        </q-tr>
        <q-tr v-show="props.expand" :props="props">
          <q-td colspan="100%">
            <re-table
              :data="props.row.documents"
              :rows-per-page-options="[0]"
              :hide-pagination="true"
              :columns="documentColumns"
            >
              <template #body-item-actions="innerProps">
                <q-icon
                  name="pgs-message-dotted-off"
                  class="ResolutionTable-Icon"
                  color="primary"
                  size="26px"
                  v-if="innerProps.row.returnText"
                >
                  <q-tooltip>{{ innerProps.row.returnText }}</q-tooltip>
                </q-icon>
                <q-icon
                  v-if="isDecisionSigned(innerProps.row)"
                  color="green"
                  class="ResolutionTable-Icon"
                  name="pgs-sign"
                  size="26px"
                  @click="showCertificate(innerProps.row)"
                >
                  <q-tooltip>Документ подписан</q-tooltip>
                </q-icon>
                <comment
                  v-if="determiningDataAvailability(innerProps.row.comment)"
                  :comment="innerProps.row.comment"
                />
                <base-preview
                  class="preview-wrapper"
                  v-if="innerProps.row.fileInfo.format"
                  :extension="innerProps.row.fileInfo.format"
                  :s3-url="innerProps.row.fileInfo.s3url"
                >
                  <q-icon
                    class="ResolutionTable-Icon"
                    color="primary"
                    name="pgs-view"
                    size="26px"
                  >
                    <q-tooltip>Предпросмотр</q-tooltip>
                  </q-icon>
                </base-preview>
                <q-icon
                  v-else
                  disable
                  class="ResolutionTable-Icon"
                  color="primary"
                  name="pgs-view"
                  size="26px"
                />
                <q-icon
                  class="ResolutionTable-Icon"
                  color="primary"
                  name="pgs-import"
                  size="26px"
                  @click="
                    fetchDocumentAttachment(
                      innerProps.row.fileInfo,
                      'download',
                      's3Name',
                      's3url'
                    )
                  "
                >
                  <q-tooltip>Скачать</q-tooltip>
                </q-icon>
              </template>
            </re-table>
          </q-td>
        </q-tr>
      </template>
    </q-table>
  </centered-1280-box>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import get from 'lodash/get';
import StatusBox from '@/recruits/components/common/status-box/index.vue';
import isArray from 'lodash/isArray';
import {
  formatDate,
  isDecisionSigned,
  determiningDataAvailability,
} from '@/recruits/utils';

import Centered1280Box from '@/recruits/components/common/centered-1280-box.vue';
import { fetchDocumentAttachment } from '@utils/fetch-document-attachment';
import ReTable from '@/recruits/components/common/r-table/index.vue';
import RejectApplication from '@/recruits/components/dialogs/RejectApplication.vue';
import SignRejectApplication from '@/recruits/components/dialogs/SignRejectApplication.vue';
import RevertApplication from '@/recruits/components/dialogs/RevertApplication.vue';
import CancelApplication from '@/recruits/components/dialogs/CancelApplication.vue';
import EditApplication from '@/recruits/components/dialogs/EditApplication.vue';
import Comment from '@/recruits/components/common/comment/index.vue';

@Component({
  methods: {
    get,
    isArray,
    formatDate,
    fetchDocumentAttachment,
    isDecisionSigned,
    determiningDataAvailability,
  },
  components: {
    Comment,
    RejectApplication,
    SignRejectApplication,
    RevertApplication,
    CancelApplication,
    EditApplication,
    Centered1280Box,
    StatusBox,
    ReTable,
  },
})
export default class ApplicationTab extends Vue {
  get: typeof get;
  formatDate: typeof formatDate;
  isArray: typeof isArray;
  fetchDocumentAttachment: typeof fetchDocumentAttachment;

  @Prop()
  readonly data: any;

  columns = [
    {
      name: 'expand',
      label: '',
      field: '',
      align: 'left',
    },
    {
      name: 'number',
      label: 'Номер заявления',
      field: 'number',
      align: 'left',
    },
    {
      name: 'dateStart',
      label: 'Дата подачи',
      field: (row: any) => formatDate(row.dateStart),
      align: 'left',
    },
    {
      name: 'dateMax',
      label: 'Срок рассмотрения',
      field: (row: any) => formatDate(row.dateMax),
      align: 'left',
    },
    {
      name: 'status',
      label: 'Статус',
      field: (row: any) => this.getStatus(row.status),
      align: 'left',
    },
    {
      name: 'reason',
      label: 'Цель',
      field: 'reason',
      align: 'left',
    },
    {
      name: 'actions',
      label: 'Действия',
      field: '',
    },
  ];

  get documentColumns() {
    return [
      {
        align: 'left',
        field: (document: any): string => this.statusDocument(document.type),
        label: `Тип`,
        name: 'type',
        width: '1fr',
        type: 'regular',
      },
      {
        align: 'left',
        field: 'name',
        label: 'Наименование',
        name: 'name',
        width: '3fr',
        type: 'bold',
      },
      {
        align: 'left',
        field: 'date',
        label: 'Дата решения',
        name: 'date',
        componentPath: 'date-time',
        width: '1fr',
      },
      {
        align: 'left',
        field: (document: any) => {
          switch (document.type) {
            case 'rejectApplication':
              return 'Решение сформировано';

            case 'rejectApplicationSigned':
              return 'Решение подписано';

            case 'rejectApplicationCancelled':
              return 'Проект решения отклонён';

            default:
              return '-';
          }
        },
        label: 'Статус',
        width: '1fr',
        name: 'status',
      },
      {
        align: 'left',
        field: 'number',
        label: 'Номер решения',
        name: 'number',
        width: '1fr',
      },
      {
        align: 'left',
        field: (document: any): string => document.fileInfo.format || '-',
        label: 'Тип документа',
        name: 'format',
        width: '120px',
      },
      {
        align: 'center',
        label: 'Действия',
        name: 'actions',
        width: '130px',
        sortable: false,
      },
    ];
  }

  getStatus(statusCode: string): string {
    const dict = this.$store.getters[
      'ervuDictionaries/recruitErvuApplicationStatus'
    ];
    return dict[statusCode] || '';
  }

  showExpandButton(row: any): boolean {
    return row.documents.length;
  }

  sigDialogShow = false;
  signature = {
    attachment: {},
  };

  showCertificate(doc: any): void {
    this.signature.attachment = doc;
    this.sigDialogShow = true;
  }

  statusDocument(documentType?: string): string {
    if (!documentType) return '-';
    return (
      this.$store.getters['ervuDictionaries/resolutionsDocumentsDictionary'][
        documentType
      ] || '-'
    );
  }

  getActualDocumentForSign(documents: any) {
    for (let i = 0; i < documents.length; i++) {
      if (
        (documents[i].type === 'rejectApplicationCancelled' ||
          documents[i].type === 'rejectApplication') &&
        documents[i].fileInfo.format === 'docx'
      ) {
        return documents[i];
      }
    }
  }

  getDataForSign(row: any) {
    return {
      personIds: [this.data.id],
      applicationIds: [row.id],
      document: this.getActualDocumentForSign(row.documents),
      number: row.number,
    };
  }
}
</script>

<style lang="scss" scoped>
.Application {
  &-Header {
    font-family: 'Golos text', sans-serif;
    font-style: normal;
    font-weight: 500;
    font-size: 20px;
    line-height: 24px;
    letter-spacing: -0.015em;
    color: rgba(2, 12, 18, 0.9);
    padding-bottom: 12px;
    margin-bottom: 26px;
    border-bottom: 1px solid rgba(1, 72, 116, 0.11);
  }
  &-ButtonsBlock {
    display: flex;
    justify-content: flex-end;
  }
  &-Button {
    &:not(:last-child) {
      margin-right: 5px;
    }
  }
}
.Table {
  font-family: 'Golos text', sans-serif;
  font-style: normal;
  font-weight: 400;
  font-size: 14px;
  line-height: 16px;
  background: none;

  ::v-deep & table {
    border-spacing: 0 6px;
    thead tr {
      height: auto;
      th {
        color: rgba(2, 12, 18, 0.58);
        overflow: hidden;
        font-family: 'Golos Text', sans-serif;
        font-style: normal;
        font-weight: 600;
        font-size: 10px;
        line-height: 12px;
        padding: 4px 12px;
        letter-spacing: 0.05em;
        text-transform: uppercase;
      }
    }
    tbody tr {
      background: #ffffff;
      border: 1px solid rgba(1, 72, 116, 0.11);
      border-radius: 8px;
      td {
        font-size: 12px;
      }
    }

    td {
      border-color: #e3ebf0ff;
      border-style: solid;
      border-width: 1px 0 1px 1px;

      &:first-child {
        border-top-left-radius: 4px;
        border-bottom-left-radius: 4px;
      }

      &:last-child {
        border-right-width: 1px;
        border-top-right-radius: 4px;
        border-bottom-right-radius: 4px;
      }
    }
  }

  &-Row {
    height: unset;
  }

  &-Header {
    height: unset;
    padding: 0 2px 18px 2px;
    font-weight: 600;
    font-size: 9px;
    line-height: 12px;
    letter-spacing: 0.05em;
    text-transform: uppercase;
    text-align: center;
    color: rgba(2, 12, 18, 0.58);
    border: none;
    white-space: break-spaces;
    vertical-align: top;

    @media screen and (min-width: 1480px) {
      font-size: 10px;
      padding: 0 3px 22px 3px;
    }
  }
}

.ResolutionTable {
  &-Icon {
    cursor: pointer;
  }
}
</style>
