<template>
  <div class="register-new-recruit">
    <q-dialog
      v-model="isOpened"
      position="right"
      full-height
      maximized
      persistent
    >
      <q-card class="dialog-content full-width full-height">
        <header>
          <span class="_title">
            Решение о постановке на воинский учёт по новому адресу
          </span>
          <span class="_sub">{{ model.fullName }}</span>
        </header>
        <q-separator />
        <main class="q-col-gutter-md" v-if="!status">
          <div class="col-12">
            <data-block
              :form-data="{
                label: 'Тип документа',
                value: 'Решение о постановке на воинский учёт по новому адресу',
                icon: 'pgs-document',
              }"
              bolder
            />
          </div>
          <div class="col-12">
            <data-block
              :form-data="{
                label: 'Дата решения',
                value: resolutionDate,
                icon: 'pgs-calendar',
              }"
              bolder
            />
          </div>
          <div class="col-12">
            <data-block :form-data="{ label: 'ФИО / ДАТА РОЖДЕНИЯ' }" bolder>
              <span>
                {{ model.fullName }}
              </span>
              &nbsp;/&nbsp;
              <span>
                <q-icon name="pgs-calendar" />
                <span>
                  {{ formatDate(model.birthDate) }}
                </span>
              </span>
            </data-block>
          </div>
          <div class="col-12">
            <h5 class="title">Загрузка файла квитанции подтверждения</h5>
            <r-file-loader
              supported-file=".json"
              ref="fileLoader"
              @change="addFile"
            />
          </div>
        </main>
        <main v-else class="flex items-center justify-center">
          <upload-status
            :status="status"
            :label="descName"
            :reverse-labels-order="true"
            :label-size="16"
          />
        </main>
        <footer>
          <r-btn
            v-if="!status"
            outline
            label="Отмена"
            icon="pgs-close"
            color="primary"
            @click="close"
          />
          <div />
          <r-btn
            v-if="!status"
            action
            icon="pgs-double-check"
            label="Сформировать"
            :disable="!formModel.file"
            @click="action"
          />
          <r-btn
            v-else
            action
            label="Продолжить"
            :disable="status === 'pending'"
            icon-right="pgs-shevron-right-off"
            @click="close"
          />
        </footer>
      </q-card>
    </q-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Mixins, Prop, PropSync, Ref } from 'vue-property-decorator';
import dataBlock from '@components/cards/statements/components/dataBlock.vue';
import {
  MilitaryRegistrationItem,
  PersonRegistryApi,
} from '@/recruits/openapi/person-registry';
import S3UrlSignerFilesService from '@/recruits/services/s3UrlService/files';
import get from 'lodash/get';
import ProcessStarter from '@/mixins/ProcessStarter';
import { DateFormat, convertDateFormat } from '@/utils/format-date';
import { now } from 'lodash';
import RInput from '@/recruits/components/common/r-input.vue';
import { formatDate } from '@/recruits/utils';
import RFileLoader, { FileInfo } from '@/components/common/r-file-loader';
import { ModelData, DocumentInfo } from '@/types/documents';

const RegistryApi = new PersonRegistryApi();

@Component({
  components: {
    RInput,
    dataBlock,
  },
  methods: {
    get,
    formatDate,
  },
})
export default class AcceptDialog extends Mixins(ProcessStarter) {
  @Prop({ default: () => [] })
  declare readonly model: MilitaryRegistrationItem;

  @PropSync('opened', { default: false }) isOpened: boolean;

  @Prop({ default: 'milBaseUserActionDistribute' }) declare processKey: string;

  formatDate: typeof formatDate;

  get: typeof get;

  @Ref('fileLoader') fileLoader: RFileLoader;

  formModel: ModelData = {
    file: null,
  };

  descName = '';
  status = '';

  async addFile([file]: FileInfo[]): Promise<void> {
    if (!this.formModel || !file) return;

    const docInfo = await this.saveDocument(file);
    if (!docInfo) return;

    const fileIsValid = await this.validateFile(docInfo.s3Url);

    if (docInfo && fileIsValid) {
      this.formModel.file = file?.file || null;
      this.formModel.docInfo = docInfo;
    } else {
      this.fileLoader.clearResults();
    }
  }

  get resolutionDate(): string {
    return convertDateFormat(new Date(now()), undefined, DateFormat.date);
  }

  async saveDocument(file: FileInfo): Promise<DocumentInfo | void> {
    try {
      const s3Url = await S3UrlSignerFilesService.uploadFileToS3ByPath({
        bucket: 'ervu-attachment',
        file: file.file,
        path: `PersonalFiles/quitances/${file.file.name}`,
      });
      if (!s3Url) throw new Error('Не удалось загрузить файл');
      return {
        s3Url,
        name: file.file.name,
      };
    } catch (error: any) {
      this.$q.notify({
        message: error.message,
      });
    }
  }

  async validateFile(s3Url: string): Promise<boolean> {
    try {
      const response = await RegistryApi.checkQuittanceValidityV2({
        s3Url,
        id: this.model.id,
      });
      if (response.status === 200) {
        this.$q.notify({
          message: 'Файл загружен',
          color: 'positive',
        });
        return true;
      }
    } catch (error: any) {
      this.$q.notify({
        message: 'Файл не валиден, проверьте загружаемые параметры',
        color: 'negative',
      });
      return false;
    }

    return false;
  }

  async action(): Promise<void> {
    if (this.status) return;
    try {
      this.status = 'pending';
      this.descName = 'Загрузка..';

      const traceId = await this.startProcess({
        processTraceIds: [this.model.processTraceId],
        actionType: 'privateFileAccept',
        docInfo: this.formModel.file ? this.formModel.docInfo : null,
      });

      this.registerListener((message, removeListener) => {
        if (traceId !== message.traceId) return;
        if (message?.body?.type === 'finish') {
          this.status = 'success';
          this.descName = 'Файл загружен';
          removeListener();
        }
      });
    } catch (e) {
      console.log(e);
      this.status = 'error';
      this.descName = 'Ошибка';
    }
  }

  finish(): void {
    this.$emit('done');
  }

  resetStatus(): void {
    this.status = '';
    this.descName = '';
  }

  close(): void {
    if (this.status === 'success') this.$emit('refresh');
    this.resetStatus();
    this.isOpened = false;
  }
}
</script>

<style lang="scss" scoped>
.dialog-content {
  width: 600px !important;
  height: 100%;
  gap: 12px;
  display: grid;
  grid-template-rows: min-content min-content 1fr min-content;
  background: white;
  z-index: 10;
}

header {
  padding: 8px;
  font-family: 'Golos Text';
  font-style: normal;
  font-weight: 500;
  font-size: 20px;
  line-height: 24px;
  letter-spacing: -0.015em;
  color: rgba(2, 12, 18, 0.9);
  span {
    display: block;
    &._sub {
      color: #6c7276;
    }
  }
}

main {
  overflow: auto;
  padding: 8px;
}

footer {
  display: flex;
  justify-content: space-between;
  background: rgba(15, 32, 160, 0.08);
  position: sticky;
  bottom: 0;
  padding: 8px;
}

.title {
  font-family: 'Golos Text';
  font-style: normal;
  font-weight: 500;
  font-size: 20px;
  line-height: 24px;
  letter-spacing: -0.015em;
  color: rgba(2, 12, 18, 0.9);
  margin: 1em 0;
}
</style>
