<template>
  <centered-1280-box>
    <white-card>
      <div class="SubpoenaDetails">
        <div class="SubpoenaDetails__Title">
          <block-header>Информация о повестке</block-header>
        </div>
        <div class="SubpoenaDetails__Info">
          <div class="SubpoenaDetails__Blocks">
            <div
              class="SubpoenaDetails__Block SubpoenaDetails__Block_TinyBlock"
            >
              <data-block
                :form-data="{
                  label: 'Серия',
                  value: data.mainInfo && data.mainInfo.series,
                }"
                :loading="loading"
              />
            </div>
            <div
              class="SubpoenaDetails__Block SubpoenaDetails__Block_SmallBlock"
            >
              <data-block
                :form-data="{
                  label: 'Номер',
                  value: data.mainInfo && data.mainInfo.number,
                }"
                :loading="loading"
              />
            </div>
            <div
              class="SubpoenaDetails__Block SubpoenaDetails__Block_LargeBlock"
            >
              <data-block
                :form-data="{
                  label: 'ИД повестки',
                }"
                :loading="loading"
              >
                {{ data.humanReadableId || '-' }}
                <q-icon
                  size="sm"
                  name="pgs-copy"
                  class="SubpoenaDetails__Icon"
                  color="primary"
                  @click="sendToClipBoard(data.humanReadableId)"
                />
              </data-block>
            </div>
            <div
              v-if="get(data, 'file.s3Url')"
              class="SubpoenaDetails__Block SubpoenaDetails__Block_TinyBlock"
            >
              <data-block
                class="SubpoenaDetails__DownloadBlock"
                :loading="loading"
              >
                <q-icon
                  class="SubpoenaDetails__DownloadBlock"
                  name="pgs-import"
                  size="sm"
                  color="primary"
                  @click="downloadFile(
                      get(data, 'file.s3Url'),
                      get(data, `file.s3Name`)
                    )"
                />
                <q-tooltip>Скачать повестку</q-tooltip>
              </data-block>
            </div>
            <div
              class="SubpoenaDetails__Block SubpoenaDetails__Block_TinyBlock"
              v-if="listInfo"
            >
              <data-block
                :form-data="{
                  label: 'Список',
                }"
                :loading="loading"
              >
                <router-link
                  class="cursor-pointer"
                  :to="{
                    name: 'call-list',
                    params: { id: listInfo.id },
                  }"
                >
                  {{ listInfo.number }}
                </router-link>
              </data-block>
            </div>
            <div
              class="SubpoenaDetails__Block SubpoenaDetails__Block_BigBlock"
            >
              <data-block
                :form-data="{
                  label: 'Причина вызова',
                  value: getSummonObjective(
                    get(data, 'mainInfo.summonObjective')
                  ),
                }"
                :loading="loading"
              />
            </div>
            <div
              class="SubpoenaDetails__Block SubpoenaDetails__Block_MediumBlock"
            >
              <data-block
                :form-data="{
                  label: 'Дата формирования',
                  value: data.mainInfo && formatDate(data.mainInfo.createDate),
                  icon: 'pgs-decision-date',
                }"
                :loading="loading"
              />
            </div>

            <div
              class="SubpoenaDetails__Block SubpoenaDetails__Block_MediumBlock"
            >
              <data-block
                :form-data="{
                  label: 'Дата направления',
                  value: data.mainInfo && formatDate(data.mainInfo.sendingDate),
                  icon: 'pgs-request-date',
                }"
                :loading="loading"
              />
            </div>

            <div
              class="SubpoenaDetails__Block SubpoenaDetails__Block_MediumBlock"
            >
              <data-block
                :form-data="{
                  label: 'Дата и время явки',
                  icon: 'pgs-time',
                }"
                :loading="loading"
              >
                {{ data.mainInfo && formatDate(data.mainInfo.turnoutDate) }}
                <span v-if="!loading" class="SubpoenaDetails__Time">
                  {{
                    data.mainInfo &&
                    formatDate(data.mainInfo.turnoutDate, 'HH:mm')
                  }}
                </span>
                <q-skeleton v-else style="width: 50%" />
              </data-block>
            </div>
            <div
              class="SubpoenaDetails__Block SubpoenaDetails__Block_MediumBlock"
            >
              <data-block
                :form-data="{
                  label: 'Дата, с которой повестка считается врученной',
                  value: formatDate(get(data, 'subpoenaSystemInfoDto.automaticServiceSubpoena')),
                  icon: 'pgs-request-date',
                }"
                :loading="loading"
              />
            </div>
          </div>
          <div v-if="checkSendInfo(data.mainInfo)" class="SummonsExpand">
            <div class="SummonsExpand__AddressBlockHeader">
              <div class="SummonsExpand__AddressBlockHeaderTitle">
                Адрес направления
              </div>
              <div class="SummonsExpand__AddressBlockHeaderTitle">
                Тип направления
              </div>
              <div
                class="SummonsExpand__AddressBlockHeaderTitle SummonsExpand__AddressBlockHeaderTitle_Center"
              >
                Трек номер
              </div>
            </div>
            <div class="SummonsExpand__AddressBlockForm">
              <div
                v-for="info in convertSendInfo(data.mainInfo.sendInfo)"
                class="SummonsExpand__AddressBlockRow"
              >
                <div class="SummonsExpand__AddressBlockFieldAddress">
                  <span
                    class="SummonsExpand__AddressBlockFieldAddressElement SummonsExpand__AddressBlockFieldAddressElement_Type"
                  >
                    {{ convertAddressType(info.sendAddressType) }}
                  </span>
                  <span class="SummonsExpand__AddressBlockFieldAddressElement">
                    {{ 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') && !!info.sendDate"
                    :key="info.id"
                    class="SummonsExpand__AddressBlocFieldTracker"
                  >
                    <div
                      v-if="getEditFormId !== info.id"
                      class="SummonsExpand__AddressBlockFieldTracker"
                    >
                      <p class="SummonsExpand__AddressBlockFieldTrackerField">
                        # {{ info.trackNumber || '-' }}
                      </p>
                      <q-icon
                        size="sm"
                        color="primary"
                        name="pgs-copy"
                        class="SubpoenaDetails__Icon"
                        @click="sendToClipBoard(info.trackNumber)"
                      />
                      <q-icon
                        size="sm"
                        color="primary"
                        name="pgs-edit"
                        class="SubpoenaDetails__Icon"
                        @click="chooseEditForm(data.mainInfo.id, info.id)"
                      />
                    </div>
                    <div
                      v-if="getEditFormId === info.id"
                      class="SummonsExpand__AddressBlockFieldTracker SummonsExpand__AddressBlockFieldTracker_Edit"
                    >
                      <q-input
                        :value="getTrackerField"
                        :rules="[validateTrackNumber]"
                        @input="changeTrackNumber"
                        mask="#####-#####"
                      />
                      <q-icon
                        size="sm"
                        color="negative"
                        name="pgs-close"
                        class="SubpoenaDetails__Icon"
                        @click="editForm = ''"
                      />
                      <q-icon
                        size="sm"
                        color="positive"
                        name="pgs-check"
                        class="SubpoenaDetails__Icon"
                        @click="setTrackNumber(data.mainInfo.id, info.id)"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </white-card>
    <white-card v-if="get(data, 'restrictionDocuments', []).length">
      <div class="row q-pa-sm">
        <div class="col-12 col-sm-3 q-pb-sm">
          <block-header>Информация о временных мерах</block-header>
        </div>
        <div class="col-12 col-sm-9">
          <div
            class="col-12 col-sm-9"
            v-for="oneMeasure in data.restrictionDocuments"
            :key="oneMeasure.id"
          >
            <div class="row q-col-gutter-xs q-mb-lg">
              <div class="col-12 col-sm-6 col-md-3">
                <status-box :status="oneMeasure.status" />
              </div>
              <div class="col-12 col-sm-12 col-md-4">
                <data-block
                  :form-data="{
                    label: 'Дата Вынесения решения',
                    value: oneMeasure && formatDate(oneMeasure.decisionDate),
                    icon: 'pgs-decision-date',
                  }"
                  :loading="loading"
                />
              </div>

              <!--            <div class="col-12 col-sm-6 col-md-4">
                <data-block
                  :form-data="{
                    label: 'Дата отмена',
                    value: oneMeasure && formatDate(oneMeasure.cancelDate),
                    icon: 'pgs-decision-date',
                  }"
                  :loading="loading"
                />
              </div>-->
              <div class="col-6 col-sm-6 col-md-6">
                <data-block
                  :form-data="{
                    label: 'ВК применивший меры',
                    value: oneMeasure && oneMeasure.departmentName,
                  }"
                  :loading="loading"
                />
              </div>

              <div class="col-6 col-sm-6 col-md-6">
                <data-block
                  :form-data="{
                    label: 'Причина применения',
                    value: oneMeasure && oneMeasure.decisionReason,
                  }"
                  :loading="loading"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </white-card>
  </centered-1280-box>
</template>

<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;
}

.SubpoenaDetails {
  display: flex;
  flex-wrap: wrap;
  padding: 8px;
  &__Blocks {
    display: flex;
    flex-wrap: wrap;
    margin: -4px 0 0 -4px;
  }
  &__Title {
    height: auto;
    width: 25%;
  }
  &__Icon {
    cursor: pointer;
  }
  &__Info {
    height: auto;
    width: 75%;
  }
  &__Block {
    height: auto;
    padding: 4px 0 0 4px;
    &_TinyBlock {
      width: 8%;
    }
    &_SmallBlock {
      width: 16.6667%;
    }
    &_MediumBlock {
      width: 33.3333%;
    }
    &_LargeBlock {
      width: 50%;
    }
    &_BigBlock {
      width: 100%;
    }
  }

  &__Time {
    color: rgb(104, 112, 116);
  }
  &__DownloadBlock {
    display: flex;
    cursor: pointer;
    align-items: center;
    justify-content: center;
  }
}
.SummonsExpand {
  background: rgba(53, 126, 172, 0.05);
  margin: 5px 0 0 0;
  padding: 5px 0 0 0;
  border-radius: 4px;
  &__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;
    padding: 1px;
    grid-template-columns: 1fr 0.8fr 1fr;
  }
  &__AddressBlockHeaderTitle {
    font-size: 12px;
    text-transform: uppercase;
    padding: 5px;
    &_Center {
      place-self: center;
    }
    &: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;
  }
  &__AddressBlockFieldAddressElement {
    @include font-style-expand-form;
    &_Type {
      color: #020c1294;
      font-size: 12px;
    }
  }
  &__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;
    &_Edit {
      ::v-deep.q-field {
        width: 95px;
        padding-bottom: 0;
        .q-field__inner {
          height: 20px;
        }
        .q-field__control {
          height: 20px;
        }
        .q-field__marginal {
          height: 10px;
        }
      }
    }
  }
  &__AddressBlockFieldTrackerField {
    margin: 0;
  }
}
</style>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import { formatDate } from '@/recruits/utils';
import dataBlock from '@components/cards/statements/components/dataBlock.vue';
import Centered1280Box from '@/recruits/components/common/centered-1280-box.vue';
import WhiteCard from '@/recruits/components/common/white-card.vue';
import BlockHeader from '@/recruits/components/common/block-header.vue';
import StatusBox from '@/recruits/components/common/status-box/index.vue';
import get from 'lodash/get';
import {
  SendInfoByRecruitV1,
  SubpoenaMainInfoV2,
  SubpoenaOneResponseV3,
  SubpoenaRegistryApi,
} from '@/recruits/openapi/subpoena-service';
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import { saveBlob } from '@utils/files';
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[];
  sendDate: string;
  reg: string;
  sendAddressType: string;
  trackNumber: string;
}

@Component({
  components: {
    StatusBox,
    Centered1280Box,
    WhiteCard,
    BlockHeader,
    dataBlock,
  },
  methods: {
    formatDate,
    get,
  },
})
export default class DetailsTab extends Vue {
  get: typeof get;

  @Prop({ default: {} })
  public readonly data: SubpoenaOneResponseV3;

  @Prop({ default: false })
  public readonly loading: boolean;

  trackerField = '';
  editForm = '';
  SubpoenaApi = new SubpoenaRegistryApi();

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

  get getEditFormId() {
    return this.editForm;
  }

  get listInfo() {
    return this.data?.mainInfo?.list || null;
  }

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

  get getTrackerField() {
    return this.trackerField;
  }

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

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

  checkSendInfo(mainInfo: SubpoenaMainInfoV2) {
    return mainInfo?.sendInfo?.length;
  }

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

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

  // формируем ISendInfo[] для отрисовки полей по макету
  convertSendInfo(info: SendInfoByRecruitV1[]): ISendInfo[] {
    return info
      .reduce((acc, info) => {
        const obj = acc.find(
          (el) => el && el?.sendAddressType === info?.sendAddressType
        );
        const index = obj ? acc.indexOf(obj) : -1;
        // проверяем есть ли в нашем acc sendAddressType и если он есть допихиваем еще объект
        // с заменой основных полей если он имеет статус направления письмом(15)
        if (index > -1) {
          if (acc[index].sendCode)
            Object.assign(acc[index], {
              sendCode: [...acc[index].sendCode, info.sendCode],
              sendDate: acc[index].sendCode.includes('15')
                ? acc[index]?.sendDate
                : info.sendDate,
              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 || '',
            sendDate: info?.sendDate || '',
          });
        }
        return acc;
      }, [] as ISendInfo[])
      .sort((a, b) => {
        return (
          customSortOrder[a.sendAddressType as keyof typeof customSortOrder] -
          customSortOrder[b.sendAddressType as keyof typeof customSortOrder]
        );
      });
  }

  async setTrackNumber(id: string, sendInfoId: string) {
    if (this.validateTrackNumber(this.trackerField)) {
      if (
        this.trackerField ===
        this.data.mainInfo?.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: 'Не валидный трек-номер',
      });
    }
  }

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

  formatMeasureDescription(measure: string): string[] {
    return measure.split(';');
  }

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

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

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

  async downloadFile(s3url: string, fileName: string): Promise<void> {
    try {
      const { file: blob } = await S3UrlSignerFilesService.fetchFileFromS3ByUrl(
        {
          url: s3url,
        }
      );
      saveBlob({
        blob,
        fileName,
        blobType: 'application/pdf',
      });
    } catch (e) {
      console.log(e);
    }
  }
}
</script>
