<template>
  <div class="Masthead">
    <div>
      <div
        class="Masthead__InfoBlock Masthead__InfoBlock_Padding Masthead__InfoBlock_Center"
      >
        <div>
          <q-btn
            class="Masthead__BackButton"
            icon="pgs-arrow-left"
            dense
            size="sm"
            @click="returnToParentViews('recruits')"
          />
        </div>
        <div>
          <div class="Masthead__InfoBlock Masthead__InfoBlock_Gap">
            <div class="Masthead__Field Masthead__Field_Source">
              <span>Повестка</span>
            </div>
            <div class="Masthead__Field Masthead__Field_Status">
              <status-box
                :loading="loading"
                :status="(data.mainInfo && data.mainInfo.status) || ''"
                type="subpoena"
              />
            </div>

            <div class="Masthead__Field Masthead__Field_Column">
              <span class="Masthead__SubpoenaField">Серия и номер</span>
              <span
                class="Masthead__SubpoenaField Masthead__SubpoenaField_Black"
              >
                <q-skeleton v-if="loading" type="text" />
                <template v-else>
                  <span>
                    <span>{{ data.mainInfo && data.mainInfo.series }}</span>
                    №
                    <span>{{ data.mainInfo && data.mainInfo.number }}</span>
                  </span>
                </template>
              </span>
            </div>
            <div class="Masthead__SubpoenaField Masthead__SubpoenaField_Column">
              <span>Гражданин</span>
              <span>
                <q-skeleton v-if="loading" type="text" />
                <template v-else>
                  <div v-if="checkRecruitId">
                    <div class="Masthead__Name">
                      <router-link
                        class="Masthead__Link"
                        :to="{
                          name: 'recruit-personal',
                          params: { id: checkRecruitId },
                        }"
                      >
                        {{ data.mainInfo && data.mainInfo.fullName }}
                        <q-icon
                          class="Masthead__Icon"
                          name="pgs-shevron-right-off"
                        ></q-icon>
                        <q-tooltip>Перейти в карточку гражданина</q-tooltip>
                      </router-link>
                    </div>
                  </div>
                  <div v-else>
                    <div>
                      {{ data.mainInfo && data.mainInfo.fullName }}
                    </div>
                  </div>
                </template>
              </span>
            </div>
            <div class="Masthead__SubpoenaField Masthead__SubpoenaField_Column">
              <span>Дата рождения</span>
              <span
                class="Masthead__SubpoenaField Masthead__SubpoenaField_Black"
              >
                <q-icon name="pgs-calendar" size="16px" />
                <q-skeleton v-if="loading" type="text" />
                <template v-else>
                  {{ data.mainInfo && formatDate(data.mainInfo.birthDate) }}
                </template>
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- Кнопки -->
    <div class="TaskButton">
      <task-buttons
        v-if="!loading"
        :business-key="businessKey"
        :buttons="buttons"
        :model="data"
        @reload="onReload"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.Masthead {
  display: grid;
  grid-template-columns: 75% 25%;
  font-family: 'Golos Text', sans-serif;
  font-style: normal;
  font-weight: 600;
  font-size: 12px;
  line-height: 16px;
  padding: 0 8px 0 8px;
  &__InfoBlock {
    display: flex;
    flex-flow: row;
    &_Padding {
      padding: 16px;
    }
    &_Center {
      align-items: center;
    }
    &_Gap {
      gap: 1em;
    }
  }
  &__BackButton {
    padding: 0 4px;
    border: 1px solid rgba(1, 72, 116, 0.18) !important;
    border-radius: 24px !important;
    color: #1491cf !important;
  }
  &__Field {
    display: flex;
    overflow-x: hidden;
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 600;
    font-size: 12px;
    line-height: 16px;
    padding: 0 8px 0px 8px;
    &_Source {
      display: inline-flex;
      align-items: center;
      text-align: center;
      font-family: 'Golos Text', sans-serif;
      font-style: normal;
      color: rgba(2, 12, 18, 0.58);
    }
    &_Status {
      padding: 0;
      flex-flow: column;
      width: 12em;
      min-height: 30px;
    }
    &_Column {
      flex-flow: column;
    }
  }

  &__SubpoenaField {
    display: flex;
    flex-flow: row;
    flex-wrap: nowrap;
    font-weight: 400;
    color: rgba(2, 12, 18, 0.58);
    &_Black {
      font-weight: 600;
      color: #000;
    }
    &_Column {
      flex-flow: column;
    }
  }
  &__Name {
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    color: #1487cf;
    font-size: 12px;
    font-weight: 400;
    color: rgba(2, 12, 18, 0.9);
    cursor: pointer;
  }
  &__Link {
    color: inherit;
    cursor: pointer;
    text-decoration-thickness: 15%;
    text-decoration-color: #1487cf;
    &:hover {
      color: #00a0c6;
    }
  }
  &__Icon {
    font-size: 25px;
    width: 20px;
    height: 20px;
    overflow: hidden;
    &_MinSize {
      font-size: 16px;
    }
  }
}
.TaskButton {
  display: flex;
  flex-flow: wrap;
  justify-content: flex-end;
  align-items: center;
  padding: 0 16px;
}
</style>

<script lang="ts">
import { Component, Emit, Mixins, Prop, Watch } from 'vue-property-decorator';
import ReturnToParentView from '@mixins/ReturnToParentView';
import {
  SubpoenaRegistryApi,
  SubpoenaOneResponseV3,
} from '@/recruits/openapi/subpoena-service';
import get from 'lodash/get';
import { formatDate, extractNameFromS3Url } from '@/recruits/utils';
import StatusBox from '@/recruits/components/common/status-box/index.vue';
import { fetchDocumentAttachment } from '@utils/fetch-document-attachment';
import UpdateTrackNumber from '@/recruits/components/dialogs/UpdateTrackNumber.vue';
import TaskButtons from '@/recruits/components/taskButtons/index.vue';
import { Button } from '@/recruits/components/taskButtons/types';
import ProcessStarter from '@mixins/ProcessStarter';
import { PersonRegistryApi, RecruitV3 } from '@/recruits/openapi/person-registry';
import moment from 'moment';

interface ISubpoena extends SubpoenaOneResponseV3 {
  recruit?: RecruitV3;
}

@Component({
  components: {
    StatusBox,
    UpdateTrackNumber,
    TaskButtons,
  },
  methods: {
    formatDate,
    get,
    fetchDocumentAttachment,
  },
})
export default class SubpoenaCard extends Mixins(
  ReturnToParentView,
  ProcessStarter
) {
  @Prop({ default: false })
  refresh: boolean;

  SubpoenaApi = new SubpoenaRegistryApi();
  RecruitApi = new PersonRegistryApi();

  public loading = false;
  public data: ISubpoena = {};
  public showModalTrackNumber = false; // переменная для показа модального окна с трек кодом

  public readonly subpoenaId: string = this.$route.params.id;

  @Watch('loading')
  @Emit('data-loading')
  private loadingWatcher(): { loading: boolean; data: any } {
    return {
      loading: this.loading,
      data: this.data,
    };
  }

  @Watch('refresh')
  refreshData(value: boolean) {
    value && this.loadSubpoena();
  }

  get checkRecruitId(): string {
    return this.data?.mainInfo?.recruitId || '';
  }

  get userTaskActions(): string[] {
    return get(
      this.$store.getters['wfActions/userTasks/userTask'],
      'outData.actions',
      []
    );
  }

  get checkDateForSendRegistration() {
    const subpoena = this.data?.mainInfo?.sendingDate
      ? null
      : this.data?.mainInfo;
    if (subpoena) {
      return moment(subpoena?.turnoutDate).format('YYYY/MM/DD') <= moment().format('YYYY/MM/DD')
    } else {
      return true;
    }
  }

  get recruitInfoRecord(): Record<string, string> {
    return {
      id: this.data.recruit?.id || '',
      idERN: this.data?.recruit?.systemInfo?.idERN || '',
      fio: this.data?.recruit?.mainInfo?.fullName || '',
    };
  }

  get subpoenaStatus() {
    return this.data?.mainInfo?.status || '';
  }

  get businessKey(): string | undefined {
    return this.data?.recruit?.recruitSystemInfo?.processIdMain;
  }

  get isDocIdExist(): boolean {
    return !!this.data?.recruit?.systemInfo?.docId;
  }

  private actionIsPresented(action: string): boolean {
    return this.userTaskActions.includes(action);
  }

  get buttons(): Button[] {
    return [
      {
        id: 'sign_registration',
        label: 'Подписать',
        tooltip: 'Подписание',
        componentPath: 'single_subpoena_sign',
        componentProps: {
          title: 'Подписание',
          sign: true,
        },
        visible:
          this.actionIsPresented('sign_registration') &&
          ['3.7', '3.13'].includes(this.subpoenaStatus) &&
          this.data?.mainInfo?.departmentId === this.userDomainId,
        scopes: [this.$AC.scopes.MILITARY_COMMISSAR],
      },
      {
        id: 'send_registration',
        label: 'Направить',
        componentPath: 'send_registration',
        componentProps: {
          title: 'Вы уверены?',
          tooltip: this.checkDateForSendRegistration
            ? 'Наступило время и дата явки по ненаправленной повестке. Необходимо отклонить повестку '
            : '',
        },
        scopes: [this.$AC.scopes.MILITARY_RECRUIT_SPECIALIST],
        props: {
          icon: 'pgs-ok',
          positive: true,
          noWrap: true,
          disable: this.checkDateForSendRegistration,
        },
        onBeforeAction: (buttonCode, data) => {
          this.$recordActivity({
            buttonCode: buttonCode || 'summons_send',
            extraInfo: {
              type: 'recruit',
              ...this.recruitInfoRecord,
              ...data,
            },
          });
        },
        visible: this.actionIsPresented('send_registration'),
      },
      {
        id: 'decline_registration',
        label: 'Отклонить',
        tooltip: 'Отклонить',
        componentPath: 'single_subpoena_sign',
        componentProps: {
          title: 'Отклонить',
          sign: true,
          declineProp: true,
        },
        props: {
          noWrap: true,
        },
        visible: this.isDocIdExist && ['3.14'].includes(this.subpoenaStatus),
        scopes: [this.$AC.scopes.MILITARY_COMMISSAR],
      },
      {
        id: 'delivery_not_required',
        label: 'Вручение не требуется',
        scopes: [this.$AC.scopes.MILITARY_RECRUIT_SPECIALIST],
        props: {
          icon: 'pgs-stop',
          negative: true,
          noWrap: true,
        },
        visible: this.actionIsPresented('delivery_not_required'),
      },
      {
        id: 'attendance_not_required',
        label: 'Явка не требуется',
        scopes: [this.$AC.scopes.MILITARY_RECRUIT_SPECIALIST],
        props: {
          icon: 'pgs-stop',
          negative: true,
          noWrap: true,
        },
        visible:
          this.actionIsPresented('attendance_not_required') &&
          this.isDocIdExist,
      },
      {
        id: 'reason_not_attendance',
        label: 'Не явился по причине',
        scopes: [this.$AC.scopes.MILITARY_RECRUIT_SPECIALIST],
        componentPath: 'reason_not_attendance',
        componentProps: {
          title: 'Фиксация решения о признании причины неявки уважительной',
        },
        visible: this.actionIsPresented('reason_not_attendance'),
      },
      {
        id: 'subpoena_awarded',
        label: 'Повестка вручена',
        scopes: [this.$AC.scopes.MILITARY_RECRUIT_SPECIALIST],
        componentPath: 'subpoena_awarded',
        componentProps: {
          title: 'Подтверждение вручения повестки',
        },
        visible: this.actionIsPresented('subpoena_awarded'),
      },
      {
        id: 'confirm_attendance',
        label: 'Явился',
        scopes: [this.$AC.scopes.MILITARY_RECRUIT_SPECIALIST],
        props: {
          icon: 'pgs-ok',
          positive: true,
          noWrap: true,
          awaitSocketMessageForRefresh: 'finish',
        },
        visible: this.actionIsPresented('confirm_attendance'),
      },
      {
        id: 'summon_required',
        label: 'Вызов требуется',
        componentPath: 'summon_edit',
        componentProps: {
          title: 'Редактирование повестки:',
          sign: false,
          icon: 'pgs-rol',
          defaultTime: '09:00',
        },
        visible: this.actionIsPresented('summon_required'),
        scopes: [this.$AC.scopes.MILITARY_RECRUIT_SPECIALIST],
      },
      {
        id: 'summon_not_required',
        label: 'Вызов не требуется',
        visible: this.actionIsPresented('summon_not_required'),
        scopes: [this.$AC.scopes.MILITARY_RECRUIT_SPECIALIST],
      },
    ];
  }

  get userDomainId(): string {
    return this.$store.getters['oidcClient/currentUser'].domain_id;
  }

  async mounted(): Promise<void> {
    await this.loadSubpoena();

    // @ts-ignore
    this.$recordActivity({
      event: 'navigation',
      extraInfo: {
        breadcrumbs: ['Карточка повестки'],
        type: 'subpoena',
        id: this.data.mainInfo?.id,
        series: this.data.mainInfo?.series,
        number: this.data.mainInfo?.number,
        fio: this.data.mainInfo?.fullName,
      },
    });
  }

  async requestProcessData(): Promise<void> {
    try {
      await this.$store.dispatch(
        'wfActions/userTasks/fetchUserData',
        this.businessKey
      );
    } catch (error) {
      console.error(error);
      console.error(
        `Ошибка при вызове wfApi.findUserTasks('${this.businessKey}',...)`,
        error
      );
    }
  }

  // функция загрузки данных о повестке и рекруте
  public async loadSubpoena(): Promise<void> {
    this.loading = true;
    try {
      const { data } = await this.SubpoenaApi.getSubpoenaV3(this.subpoenaId);
      if (data?.mainInfo?.recruitId) {
        const recruitResponse = await this.RecruitApi.getOneRecruitV4(
          data.mainInfo.recruitId
        );
        this.data = { ...data, recruit: recruitResponse.data };
        await this.requestProcessData();
      } else {
        this.data = { ...data, recruit: {} as RecruitV3 };
      }
    } catch (error) {
      console.error(`Error requesting data for list ${this.subpoenaId}`, error);
    } finally {
      this.loading = false;
    }
  }

  public onDownload(): void {
    if (this.data.file && this.data.file.s3url) {
      const { s3url, s3Name } = this.data.file;
      if (!s3Name) {
        this.data.file.s3Name = extractNameFromS3Url(s3url);
      }
      fetchDocumentAttachment(this.data.file, 'download', 's3Name', 's3Url');
    }
  }

  // функция перезагрузки данных, после изменения трек номера
  public onReload(): void {
    this.showModalTrackNumber = false;
    this.loadSubpoena();
  }
}
</script>
