<template>
  <centered-1280-box>
    <r-spoiler-section
      title="Решения военного комиссара"
      :counter="militaryCommissarDecisions.length"
      :bordered="true"
    >
      <q-table
        :data="militaryCommissarDecisions"
        :columns="columns"
        :hide-pagination="true"
        class="Table"
        row-key="id"
        :rows-per-page-options="[0]"
      >
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th
              v-for="col in props.cols"
              :key="col.name"
              :props="props"
              class="Table-Header"
              :class="col.align === 'center' && 'centered'"
            >
              {{ col.label }}
            </q-th>
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr
            :props="props"
            class="Table-Row"
            no-hover
            :class="{ 'Table-Row__Light': needLight(props.row.id) }"
          >
            <q-td key="numberDecision" class="Table-Cell bold">
              <copy :value="props.row.number" copy-button-position="left" />
            </q-td>
            <q-td key="type" class="Table-Cell Table-Cell__Secondary">
              {{ typeDocument(props.row.type) }}
            </q-td>
            <q-td key="name" class="Table-Cell Table-Cell__Primary">
              {{ props.row.name }}
            </q-td>
            <q-td key="dateDecision" class="Table-Cell Table-Cell__Secondary">
              {{ formatDate(props.row.createDate) }}
            </q-td>
            <q-td
              key="status"
              class="centered status"
              :class="statusClass(props.row.status)"
            >
              {{ statusText(props.row.status) }}
            </q-td>
            <q-td class="Table-Cell">
              <div class="actions-wrapper">
                <comment
                  v-if="
                    checkCommentDecision(props.row.rejectionResonDescription)
                  "
                  class="Test"
                  :comment="props.row.rejectionResonDescription"
                />
                <q-icon
                  v-if="isDecisionSigned(props.row)"
                  color="green"
                  name="pgs-sign"
                  size="26px"
                  @click="showCertificate(props.row)"
                >
                  <q-tooltip>Документ подписан</q-tooltip>
                </q-icon>
                <base-preview
                  class="preview-wrapper"
                  v-if="props.row.file.s3url"
                  :extension="props.row.file.s3url.split('.').pop()"
                  :s3-url="props.row.file.s3url"
                >
                  <q-icon color="primary" name="pgs-view" size="26px">
                    <q-tooltip>Предпросмотр</q-tooltip>
                  </q-icon>
                </base-preview>
                <q-icon
                  v-else
                  disable
                  color="primary"
                  name="pgs-view"
                  size="26px"
                />
                <q-icon
                  color="primary"
                  name="pgs-import"
                  size="26px"
                  @click="
                    fetchDocumentAttachment(
                      props.row.file,
                      'download',
                      's3Name',
                      's3url'
                    )
                  "
                >
                  <q-tooltip>Скачать</q-tooltip>
                </q-icon>
                <span class="format" v-show="props.row.file">{{
                  props.row.file && props.row.file.format
                }}</span>
              </div>
            </q-td>
          </q-tr>
        </template>
      </q-table>
    </r-spoiler-section>
    <r-spoiler-section
      title="Решения комиссии"
      :counter="commissionDecisions.length"
      :bordered="true"
    >
      <re-table
        :data="commissionDecisions"
        :columns="columns2"
        :hide-pagination="true"
        :rows-per-page-options="[0]"
      />
    </r-spoiler-section>
    <q-dialog v-model="sigDialogShow">
      <sign-info-dialog :signature="signature" />
    </q-dialog>
  </centered-1280-box>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import {
  DictionariesElement,
  CertificateInfo,
} from '@/recruits/openapi/ervu-service';
import { ArchivedRecruitV3 } from '@/recruits/openapi/person-archive';
import {
  MilitaryCommissarDecisions,
  CommissionDecisions,
} from '@/recruits/openapi/decision-document';
import get from 'lodash/get';
import SignInfoDialog from '@components/registries/sign_info_dialog.vue';
import Comment from '@/recruits/components/common/comment/index.vue';
import Centered1280Box from '@/recruits/components/common/centered-1280-box.vue';
import { fetchDocumentAttachment } from '@utils/fetch-document-attachment';
import { formatDate, isDecisionSigned } from '@/recruits/utils';
import ReTable from '@/recruits/components/common/r-table/index.vue';
import { RTableColumn } from '@/interfaces';
import RSpoilerSection from '@/recruits/components/common/r-spoiler-section.vue';
import Copy from '@/recruits/components/common/cells/copy.vue';

@Component({
  methods: {
    get,
    fetchDocumentAttachment,
    formatDate,
    isDecisionSigned,
  },
  components: {
    Copy,
    ReTable,
    SignInfoDialog,
    Comment,
    Centered1280Box,
    RSpoilerSection,
  },
})
export default class DecisionTab extends Vue {
  get: typeof get;
  isDecisionSigned: typeof isDecisionSigned;
  fetchDocumentAttachment: typeof fetchDocumentAttachment;
  formatDate: typeof formatDate;

  @Prop()
  readonly data: ArchivedRecruitV3;

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

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

  typeDocument(documentType?: string): string {
    if (!documentType) return '-';
    return (
      this.$store.getters[
        'ervuDictionaries/militaryCommissarDocumentTypesDictionary'
      ]?.find(({ code }: DictionariesElement) => code === documentType)
        ?.value || '-'
    );
  }

  commissionTypeDocument(documentType?: string): string {
    return (
      this.commissionDocumentTypes.find(
        ({ code }: { code: string }) => code === documentType
      )?.value ??
      documentType ??
      '-'
    );
  }

  statusText(status: string | undefined): string {
    for (let i = 0; i < this.decisionStatuses.length; i++) {
      if (this.decisionStatuses[i].code === status) {
        return this.decisionStatuses[i].value;
      }
    }
    return '-';
  }

  checkCommentDecision(comment: string | undefined): boolean {
    return !!comment;
  }

  statusClass(status: string): string {
    const existedStatus =
      this.decisionStatuses.find(({ code }) => code === status)?.code ?? '';
    return (existedStatus && `status-${existedStatus}`) || '';
  }

  refreshData(): void {
    this.$emit('refresh');
  }

  get militaryCommissarDecisions(): MilitaryCommissarDecisions[] {
    return this.data?.decisions?.militaryCommissarDecisions ?? [];
  }

  get commissionDocumentTypes(): DictionariesElement[] {
    return this.$store.getters[
      'ervuDictionaries/commissionDocumentTypesDictionary'
    ];
  }

  get decisionStatuses(): DictionariesElement[] {
    return this.$store.getters[
      'ervuDictionaries/militaryCommissarDecisionStatusDictionary'
    ];
  }

  get commissionDecisions(): CommissionDecisions[] {
    return this.data?.decisions?.commissionDecisions ?? [];
  }

  get columns(): RTableColumn<MilitaryCommissarDecisions>[] {
    return [
      {
        align: 'left',
        field: 'number',
        label: 'Номер решения',
        name: 'number',
        width: '180px',
        componentPath: 'copy',
        componentOptions: {
          copyButtonPosition: 'left',
        },
        type: 'bold',
        sortable: true,
      },
      {
        align: 'left',
        field: (document): string => this.typeDocument(document.type),
        label: `Тип документа`,
        name: 'type',
        width: '2fr',
        type: 'regular',
        sortable: true,
        borderless: true,
      },
      {
        align: 'left',
        field: 'name',
        label: 'Наименование',
        name: 'name',
        width: '3fr',
        type: 'bold',
        sortable: true,
        borderless: true,
      },
      {
        align: 'left',
        field: 'dateDecision',
        label: 'Дата решения',
        name: 'dateDecision',
        componentPath: 'date-time',
        width: '140px',
        sortable: true,
        borderless: true,
      },
      {
        align: 'center',
        field: (document): string => this.statusText(document.status),
        label: 'Статус',
        name: 'status',
        width: '200px',
        sortable: true,
        borderless: true,
        collaps: true,
      },
      {
        align: 'center',
        label: 'Действия',
        name: 'actions',
        width: '220px',
        sortable: false,
      },
    ];
  }

  get columns2(): RTableColumn<CommissionDecisions>[] {
    return [
      {
        align: 'left',
        field: 'number',
        label: 'Номер решения',
        name: 'number',
        width: '1fr',
        componentPath: 'copy',
        componentOptions: {
          copyButtonPosition: 'left',
        },
        type: 'bold',
        sortable: true,
      },
      {
        align: 'left',
        field: (document): string => this.commissionTypeDocument(document.type),
        label: `Тип`,
        name: 'type',
        width: '2fr',
        sortable: true,
      },
      {
        align: 'left',
        field: 'dateDecision',
        label: 'Дата решения',
        name: 'dateDecision',
        componentPath: 'date-time',
        width: '130px',
        sortable: true,
      },
    ];
  }

  priorityFlag = false;

  needLight(idDecision: string): boolean {
    let decisionPriority = this.militaryCommissarDecisions.filter(
      ({ id, type, status }) =>
        type === 'resultCancelOffice' && status === '1' && id === idDecision
    );
    if (decisionPriority && decisionPriority.length) {
      this.priorityFlag = true;
      return true;
    }
    decisionPriority = [];
    decisionPriority = this.militaryCommissarDecisions.filter(
      ({ id, type, status }) =>
        type === 'turnoutIsNotRequired' && status === '1' && id === idDecision
    );
    if (decisionPriority && decisionPriority.length) {
      this.priorityFlag = true;
      return true;
    }
    decisionPriority = [];
    decisionPriority = this.militaryCommissarDecisions.filter(
      ({ id, status }) =>
        status === '1' && id === idDecision && !this.priorityFlag
    );
    if (decisionPriority && decisionPriority.length) {
      return true;
    }
    return false;
  }

  mounted(): void {
    this.$store.dispatch(
      'ervuDictionaries/loadMilitaryCommissarDocumentTypesDictionary'
    );
  }
}
</script>

<style lang="scss" scoped>
.preview-wrapper {
  line-height: 26px;
}

.actions-wrapper {
  width: 100%;
  display: flex;
  gap: 12px;
  padding-right: 8px;
  align-items: center;
  justify-content: flex-end;
}

::v-deep .status {
  font-weight: 500;
  letter-spacing: 0.05em;
  font-size: 10px;
  font-style: normal;
  line-height: 12px;
  text-transform: uppercase;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 4px;
  text-align: center;
  color: rgba(#020c12, 0.58);
  background: rgba(#357eac, 0.05);
  align-items: center;

  &-2 {
    background: #e3fefa;
    color: #04967d;
  }
}
.format {
  display: inline-block;
  font-size: 14px;
  font-weight: 400;
  line-height: 16px;
  letter-spacing: 0;
  color: rgba(#020c12, 0.58);
  min-width: 40px;
}
::v-deep {
  .q-table__top {
    padding-left: 0;
    padding-right: 0;
  }
  .RTable-SubCol {
    overflow: hidden;
    max-width: 100%;
  }
}

.Table {
  font-family: 'Golos text', sans-serif;
  font-style: normal;
  font-weight: 400;
  font-size: 14px;
  line-height: 16px;
  background: none;
  margin-top: 20px;
  &-Cell {
    line-height: 16px;
    padding: 12px 6px;
    font-size: 14px;
    color: rgba(2, 12, 18, 0.9);
    text-align: left;
    white-space: break-spaces;
    overflow-wrap: break-word;
  }

  ::v-deep & table {
    border-spacing: 0 6px;

    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;
    background-color: #fff;
    &__Light {
      background-color: rgba(245, 127, 32, 0.04);
    }
  }

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

.centered {
  text-align: center;
}

.bold {
  font-weight: 500;
}

::v-deep {
  .q-table thead tr,
  .q-table tbody td {
    height: unset;
  }
  .q-table__bottom--nodata {
    border-top: none;
    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);
  }
}

@keyframes blink {
  from {
    background-color: #c9e8f8;
  }
  50% {
    background-color: #fff;
  }
  to {
    background-color: #c9e8f8;
  }
}
</style>
