<template>
  <centered-1280-box class="Summons">
    <p class="SummonsHeader">Повестки</p>
    <div v-if="checkValue">
      Имеется активная повестка. Информация о повестке отобразится после
      постановки на учет
    </div>
    <div class="SummonsColumn">
      <div class="SummonsColumn__Title">Серия / Номер</div>
      <div class="SummonsColumn__Title">Причина вызова</div>
      <div class="SummonsColumn__Title_Center">Дата и время явки</div>
      <div class="SummonsColumn__Title_Center">Статус</div>
      <div class="SummonsColumn__Title_Center">Действия</div>
    </div>
    <q-table
      grid
      :data="data.subpoenas"
      :hide-pagination="true"
      row-key="id"
      :expanded.sync="expanded"
      class="SummonsTable"
    >
      <q-dialog v-model="sigDialogShow">
        <summon-dialog :signature="signature" />
      </q-dialog>
      <template v-slot:item="props">
        <div class="SummonsTable__Row">
          <div class="SummonsTable__Cell SummonsTable__Cell_Number">
            <router-link
              class="SummonsTable__Cell_Link"
              :to="{
                name: 'subpoena-card',
                params: { id: props.row.id },
              }"
            >
              {{
                props.row.series && props.row.number
                  ? props.row.series + ' №' + props.row.number
                  : '-'
              }}
            </router-link>
          </div>
          <div class="SummonsTable__Cell SummonsTable__Cell_Reason">
            {{ getSummonObjective(get(props.row, 'summonObjective', '-')) }}
          </div>
          <div class="SummonsTable__Cell SummonsTable__Cell_Date">
            <q-icon
              class="SummonsTable__Cell_Icon"
              name="pgs-time"
              size="26px"
            />
            <p>
              {{ formatDate(props.row.turnoutDate, 'DD.MM.YYYY') }}
              <span>{{ formatDate(props.row.turnoutDate, 'HH:mm') }}</span>
            </p>
          </div>
          <div class="SummonsTable__Cell SummonsTable__Cell_Status">
            <status-box :status="props.row.status" borderless type="subpoena" />
          </div>
          <div class="SummonsTable__Cell SummonsTable__Cell_Actions">
            <sign-info
              v-if="isSubpoenaCertificate(props.row)"
              :certificate-info="props.row.certificateInfo"
              :file-info="props.row.file"
            >
              <q-icon
                class="SummonsTable__Cell_Icon"
                color="green"
                name="pgs-sign"
                size="26px"
              >
                <q-tooltip>Документ подписан</q-tooltip>
              </q-icon>
            </sign-info>
            <q-icon v-else size="26px"/>
            <base-preview
              v-if="props.row.file && props.row.file.format"
              :extension="props.row.file.format"
              :s3-url="props.row.file.s3Url"
            >
              <q-icon
                class="SummonsTable__Cell_Icon"
                name="pgs-view"
                color="primary"
                size="26px"
              >
                <q-tooltip>Предпросмотр</q-tooltip>
              </q-icon>
            </base-preview>
            <q-icon
              v-else
              class="SummonsTable__Cell_Icon"
              name="pgs-view"
              color="primary"
              size="26px"
            />
            <q-icon
              name="pgs-import"
              class="SummonsTable__Cell_Icon"
              color="primary"
              size="26px"
              @click="
                fetchDocumentAttachment(
                  props.row,
                  'download',
                  'file.s3Name',
                  'file.s3Url'
                )
              "
            >
              <q-tooltip>Скачать</q-tooltip>
            </q-icon>
            <q-icon
              class="SummonsTable__Cell_Icon"
              v-if="props.expand"
              @click="props.expand = !props.expand"
              color="primary"
              size="26px"
              name="pgs-close"
            />
            <div v-if="!props.expand" @click="props.expand = !props.expand">
              <q-icon
                class="SummonsTable__Cell_Icon"
                name="pgs-message-constructor"
                color="primary"
                size="26px"
              >
                <q-tooltip>Раскрыть</q-tooltip>
              </q-icon>
            </div>
          </div>
        </div>
        <div v-show="props.expand" class="SummonsExpand">
          <div class="SummonsExpand__InfoBlock">
            <data-block
              v-if="props.row.nameVK"
              :form-data="{ label: 'Военнный коммисариат' }"
              :no-wrap="false"
              :loading="loading"
              class="SummonsExpand__Info_Vk"
            >
              {{ props.row.nameVK }}
            </data-block>
            <data-block
              v-if="props.row.humanReadableId"
              :form-data="{ label: 'ИД повестки' }"
              :no-wrap="false"
              :loading="loading"
              class="SummonsExpand__Info_Id"
            >
              {{ props.row.humanReadableId }}
              <q-icon
                size="sm"
                name="pgs-copy"
                class="SummonsTable__Cell_Icon"
                color="primary"
                @click="sendToClipBoard(props.row.humanReadableId)"
              />
            </data-block>
            <data-block
              v-if="props.row.signerName"
              :form-data="{ label: 'Военный коммисар' }"
              :no-wrap="false"
              :loading="loading"
              class="SummonsExpand__Info_Commissar"
            >
              {{ props.row.signerName }}
            </data-block>
            <div
              class="SummonsExpand__InfoBlock SummonsExpand__InfoBlock_InRow"
            >
              <data-block
                v-if="props.row.createDate"
                :form-data="{ label: 'Дата формирования' }"
                :no-wrap="false"
                :loading="loading"
              >
                <q-icon name="pgs-calendar" size="20px" />
                {{ formatDate(props.row.createDate) }}
              </data-block>
              <data-block
                v-if="props.row.sendingDate"
                :form-data="{ label: 'Дата направления' }"
                :no-wrap="false"
                :loading="loading"
              >
                <q-icon name="pgs-calendar" size="20px" />
                {{ formatDate(props.row.sendingDate) }}
              </data-block>
              <data-block
                v-if="props.row.deliveryDate"
                :form-data="{ label: 'Дата вручения' }"
                :no-wrap="false"
                :loading="loading"
              >
                <q-icon name="pgs-calendar" size="20px" />
                {{ formatDate(props.row.deliveryDate) }}
              </data-block>
              <data-block
                v-if="props.row.lists.id"
                :key="props.row.lists.id"
                :form-data="{ label: 'Список' }"
                :no-wrap="false"
                :loading="loading"
              >
                <router-link
                  v-if="props.row.lists.number"
                  class="cursor-pointer"
                  :to="{
                    name: 'call-list',
                    params: { id: props.row.lists.id },
                  }"
                >
                  {{ props.row.lists.number }}
                </router-link>
              </data-block>
            </div>
          </div>
          <div v-if="props.row.sendInfo" class="SummonsExpand__AddressBlock">
            <div class="SummonsExpand__AddressBlockHeader">
              <div class="SummonsExpand__AddressBlockHeaderTitle">
                Адрес направления
              </div>
              <div class="SummonsExpand__AddressBlockHeaderTitle">
                Тип направления
              </div>
              <div class="SummonsExpand__AddressBlockHeaderTitle">
                Трек номер
              </div>
            </div>
            <div class="SummonsExpand__AddressBlock__Form">
              <div
                v-for="info in convertSendInfo(props.row.sendInfo)"
                class="SummonsExpand__AddressBlockRow"
              >
                <div class="SummonsExpand__AddressBlockFieldAddress">
                  <span class="SummonsExpand__AddressBlockFieldAddress_Type">{{
                    convertAddressType(info.sendAddressType)
                  }}</span>
                  <span
                    class="SummonsExpand__AddressBlockFieldAddress_Address"
                    >{{ info.reg }}</span
                  >
                </div>
                <div class="SummonsExpand__AddressBlockFieldDelivery">
                  <div
                    class="SummonsExpand__AddressBlockFieldDeliveryMeet"
                    v-if="info.sendCode.includes('14')"
                  >
                    <span>{{ getDeliveryMethod('14') }}</span>
                  </div>
                  <div
                    class="SummonsExpand__AddressBlockFieldDeliveryMail"
                    v-if="info.sendCode.includes('15')"
                  >
                    <span>{{ getDeliveryMethod('15') }}</span>
                  </div>
                </div>
                <div class="SummonsExpand__AddressBlockFieldTracker">
                  <div
                    v-if="info.sendCode.includes('15') && props.row.sendingDate"
                    :key="info.id"
                    class="SummonsExpand__AddressBlocFieldTracker"
                  >
                    <div
                      v-if="getEditFormId !== info.id"
                      class="SummonsExpand__AddressBlockFieldTracker_View"
                    >
                      <p># {{ info.trackNumber || '-' }}</p>
                      <q-icon
                        size="sm"
                        color="primary"
                        name="pgs-copy"
                        class="SummonsTable__Cell_Icon"
                        @click="sendToClipBoard(info.trackNumber)"
                      />
                      <q-icon
                        size="sm"
                        color="primary"
                        name="pgs-edit"
                        class="SummonsTable__Cell_Icon"
                        @click="chooseEditForm(props.row.id, info.id)"
                      />
                    </div>
                    <div
                      v-if="getEditFormId === info.id"
                      class="SummonsExpand__AddressBlockFieldTracker_Edit"
                    >
                      <q-input
                        :value="getTrackerField"
                        :rules="[validateTrackNumber]"
                        @input="changeTrackNumber"
                        mask="#####-#####"
                      />
                      <q-icon
                        size="sm"
                        color="negative"
                        name="pgs-close"
                        class="SummonsTable__Cell_Icon"
                        @click="editForm = ''"
                      />
                      <q-icon
                        size="sm"
                        color="positive"
                        name="pgs-check"
                        class="SummonsTable__Cell_Icon"
                        @click="setTrackNumber(props.row.id, info.id)"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </q-table>
  </centered-1280-box>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { StateRecruitV3 } from '@/recruits/openapi/person-registry';
import {
  SendInfoByRecruitV1,
  SubpoenaByRecruitV5,
  SubpoenaRegistryApi,
} from '@/recruits/openapi/subpoena-service';
import get from 'lodash/get';
import StatusBox from '@/recruits/components/common/status-box/index.vue';
import isArray from 'lodash/isArray';
import { formatDate, isSubpoenaSigned } from '@/recruits/utils';
import Centered1280Box from '@/recruits/components/common/centered-1280-box.vue';
import { fetchDocumentAttachment } from '@utils/fetch-document-attachment';
import SummonDialog from '@/recruits/components/recruit-card/dialogs/summon_dialog.vue';
import SignInfo from '@/recruits/components/dialogs/SignInfo.vue';
import dataBlock from '@components/cards/statements/components/dataBlock.vue';
import { copyToClipboard } from 'quasar';

const DELIVERY_METHOD_DICT = 'deliveryMethod';

const customSortOrder: Record<string, number> = {
  actualAddress: 1,
  residentialAddress: 2,
  residenceAddress: 3,
  criminalAddress: 4,
  universityAddress: 4,
  workAddress: 4,
};

interface ISendInfo {
  id: string;
  sendCode: string[];
  reg: string;
  sendAddressType: string;
  trackNumber: string;
}

@Component({
  methods: {
    get,
    isArray,
    formatDate,
    isSubpoenaSigned,
    fetchDocumentAttachment,
  },
  components: {
    dataBlock,
    SummonDialog,
    Centered1280Box,
    StatusBox,
    SignInfo,
  },
})
export default class SummonsTab extends Vue {
  get: typeof get;
  formatDate: typeof formatDate;
  isArray: typeof isArray;
  fetchDocumentAttachment: typeof fetchDocumentAttachment;
  sigDialogShow = false;
  signature = {};
  expanded = [];
  trackerField = '';
  editForm = '';
  SubpoenaApi = new SubpoenaRegistryApi();

  @Prop()
  readonly data: {
    subpoenas: SubpoenaByRecruitV5[];
    stateRecruit: StateRecruitV3;
    isThereActiveSubpoena: boolean;
  };

  @Prop({ type: Boolean, default: false })
  public loading: boolean;

  mounted(): void {
    this.initDeliveryDictionary();
  }

  get getEditFormId() {
    return this.editForm;
  }

  validateTrackNumber(value: string): boolean {
    const pattern = /^\d{5}-\d{5}$/;
    return pattern.test(value);
  }

  get getTrackerField() {
    return this.trackerField;
  }

  getSummonObjective(summonObjective: string): string {
    return (
      this.$store.getters[
        'ervuDictionaries/militaryRegistrationUpdatingGoalsDictionary'
      ][summonObjective] || '-'
    );
  }

  get checkValue() {
    return (
      this.data?.isThereActiveSubpoena &&
      this.data?.stateRecruit?.changeVkInProgress &&
      !this.data?.subpoenas?.[0]?.id
    );
  }

  async initDeliveryDictionary(): Promise<void> {
    await this.$store.dispatch(
      'registryService/referenceBooks/initReferenceBooks',
      [
        {
          id: DELIVERY_METHOD_DICT,
        },
      ]
    );
  }

  get getAddressTypesDictionary(): Record<string, string> {
    return this.$store.getters['ervuDictionaries/addressTypeDictionary'] || {};
  }

  convertAddressType(type: string) {
    return this.getAddressTypesDictionary[type];
  }

  changeTrackNumber(text: string) {
    this.trackerField = text;
  }

  async setTrackNumber(id: string, sendInfoId: string) {
    if (this.validateTrackNumber(this.trackerField)) {
      if (
        this.trackerField ===
        this.data.subpoenas
          .find((sub) => sub.id === id)
          ?.sendInfo?.find((info) => info.id === sendInfoId)?.trackNumber
      ) {
        this.editForm = '';
        this.trackerField = '';
        return;
      }
      try {
        await this.SubpoenaApi.changeTrackNumberV1({
          id,
          sendInfoId,
          trackNumber: this.trackerField,
        });
        this.editForm = '';
        this.trackerField = '';
        this.$emit('refresh');
      } catch (e) {
        console.warn(e);
      }
    } else {
      this.$q.notify({
        color: 'negative',
        icon: 'error',
        message: 'Не валидный трек-номер',
      });
    }
  }

  chooseEditForm(subpoenaId: string, sendInfoId: string) {
    this.editForm = sendInfoId;
    const trackNumber =
      this.data.subpoenas
        .find((sub) => sub.id === subpoenaId)
        ?.sendInfo?.find((info) => info.id === sendInfoId)?.trackNumber || '';
    this.trackerField = trackNumber;
  }

  convertSendInfo(info: SendInfoByRecruitV1[]) {
    return info
      .reduce((acc, info) => {
        const obj = acc.find(
          (el) => el && el?.sendAddressType === info?.sendAddressType
        );
        const index = obj ? acc.indexOf(obj) : -1;
        if (index > -1) {
          if (acc[index].sendCode)
            Object.assign(acc[index], {
              sendCode: [...acc[index].sendCode, info.sendCode],
              id: acc[index].sendCode.includes('15') ? acc[index].id : info.id,
              trackNumber: acc[index].sendCode.includes('15')
                ? acc[index].trackNumber
                : info.trackNumber,
            });
        } else {
          acc.push({
            sendCode: [info?.sendCode || ''],
            reg: info.sendAddress?.reg || '',
            sendAddressType: info?.sendAddressType || '',
            id: info?.id || '',
            trackNumber: info?.trackNumber || '',
          });
        }
        return acc;
      }, [] as ISendInfo[])
      .sort((a, b) => {
        return (
          customSortOrder[a.sendAddressType as keyof typeof customSortOrder] -
          customSortOrder[b.sendAddressType as keyof typeof customSortOrder]
        );
      });
  }

  isSubpoenaCertificate(subpoena: SubpoenaByRecruitV5): boolean {
    if (subpoena.file.sig) {
      return isSubpoenaSigned(subpoena);
    }
    return false;
  }

  public sendToClipBoard(textValue: string): void {
    copyToClipboard(textValue);
    this.$q.notify({
      message: `'${textValue}' скопирован`,
    });
  }

  getDeliveryMethod(deliveryMethod: string): string {
    return (
      this.$store.getters['ervuDictionaries/getDeliveryDirections'][
        deliveryMethod
      ] || '-'
    );
  }
}
</script>

<style lang="scss" scoped>
@mixin font-style-expand-form {
  margin: 0;
  padding: 0;
  list-style: none;
  color: rgba(2, 12, 18, 0.9);
  font-family: 'Golos UI', sans-serif;
  font-style: normal;
  font-weight: 400;
  font-size: 14px;
  line-height: 14px;
}

.SummonsHeader {
  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);
}

.SummonsColumn {
  width: 100%;
  display: grid;
  grid-template-columns: 0.4fr 1.6fr 0.6fr 0.6fr 0.6fr;
  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;
  letter-spacing: 0.05em;
  text-transform: uppercase;
  &__Title {
    padding-left: 4px;
    &_Center {
      padding: 0;
      text-align: center;
    }
  }
}
.SummonsTable {
  &__Row {
    width: 100%;
    display: grid;
    grid-template-columns: 0.4fr 1.6fr 0.6fr 0.6fr 0.6fr;
    background: #fff;
    margin: 2px 0 2px 0;
    border: 1px solid rgba(1, 72, 116, 0.11);
    border-radius: 8px;
    box-shadow: none;
  }
  &__Cell {
    font-family: 'Golos UI', sans-serif;
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    line-height: 16px;
    padding: 0 4px;
    color: rgba(2, 12, 18, 0.9);
    display: flex;
    justify-content: center;
    align-items: center;
    &:nth-child(-n + 3) {
      border-right: 1px solid rgba(1, 72, 116, 0.11);
    }
    &_Number {
      justify-content: start;
    }
    &_Link {
      color: inherit;
      cursor: pointer;
      text-decoration: none;
      &:link {
        color: #1487cf;
      }
      &:visited {
        color: rgba(2, 12, 18, 0.9);
      }
      &:hover {
        color: #1487cf;
        text-decoration: underline;
        text-decoration-thickness: 15%;
        text-decoration-color: #1487cf;
      }
    }

    &_Reason {
      justify-content: start;
    }
    &_Date {
      display: flex;
      flex-direction: row;
      p {
        margin: 0;
        span {
          color: #020c1294;
        }
      }
    }
    &_Icon {
      cursor: pointer;
    }
    &_Status {
      height: 100%;
      color: rgba(2, 12, 18, 0.58);
      text-align: center;
      font-size: 10px;
      font-weight: 500;
      line-height: 12px;
      letter-spacing: 0.5px;
      text-transform: uppercase;
      background-color: #ebf1f7ff;
      padding: 0;
      .status-box::v-deep {
        background: none;
        span {
          display: inline;
        }
      }
    }
  }
}
.SummonsExpand {
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  background: #fff;
  padding: 4px;
  margin: -3px 0 0 0;
  border: 1px solid rgba(1, 72, 116, 0.11);
  border-radius: 8px;
  box-shadow: none;
  &__InfoBlock {
    @include font-style-expand-form;
    display: flex;
    flex-direction: column;
    gap: 8px;
    height: max-content;
    &_InRow {
      flex-direction: row;
    }
  }

  &__AddressBlockHeader {
    @include font-style-expand-form;
    font-family: 'Golos Text', sans-serif;
    display: grid;
    color: rgba(2, 12, 18, 0.58);
    font-weight: 600;
    grid-template-columns: 1fr 0.8fr 1fr;
  }
  &__AddressBlockHeaderTitle {
    font-size: 12px;
    text-transform: uppercase;
    padding: 5px;
    &:nth-child(2) {
      border-right: 1px solid rgba(1, 72, 116, 0.11);
    }
  }
  &__AddressBlockRow {
    box-sizing: border-box;
    border: 1px solid rgba(1, 72, 116, 0.11);
    border-radius: 8px;
    display: grid;
    grid-template-columns: 1fr 0.8fr 1fr;
  }
  &__AddressBlockFieldAddress {
    padding: 5px;
    display: flex;
    flex-direction: column;
    &_Type {
      color: #020c1294;
      font-size: 12px;
    }
    &_Address {
      @include font-style-expand-form;
    }
  }
  &__AddressBlockFieldDelivery {
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 5px;
    border-right: 1px solid rgba(1, 72, 116, 0.11);
  }
  &__AddressBlockFieldDeliveryMeet {
    text-align: center;
    background: rgba(4, 150, 125, 0.2);
    color: #04967d;
    border-radius: 4px;
    text-transform: uppercase;
  }
  &__AddressBlockFieldDeliveryMail {
    text-align: center;
    background: rgba(1, 94, 152, 0.2);
    color: #015e98;
    border-radius: 4px;
    text-transform: uppercase;
  }
  &__AddressBlockFieldTracker {
    display: flex;
    align-items: center;
    justify-content: center;
    &_View {
      display: flex;
      flex-direction: row;
      justify-content: center;
      p {
        margin: 0;
      }
    }
    &_Edit {
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      ::v-deep.q-field {
        width: 95px;
        padding-bottom: 0;
        .q-field__inner {
          height: 20px;
        }
        .q-field__control {
          height: 20px;
        }
        .q-field__marginal {
          height: 10px;
        }
      }
    }
  }
}
</style>
