<template>
  <div class="register-new-recruit">
    <block-loader type="QBtn" :loading="loading">
      <r-btn
        dense
        action
        label="Загрузить документ"
        icon="pgs-import"
        :disable="disable"
        @click="open"
        no-wrap
      />
    </block-loader>
    <operation-dialog
      persistent
      ref="dialog"
      :title="title"
      process-key="milBaseRouteProcess"
      v-model="opened"
    >
      <r-select
        dense
        options-dense
        v-model="documentType"
        :options="options"
        placeholder=""
        label="Тип документа"
      />
      <r-input
        v-if="anyDocument"
        label="Наименование документа"
        v-model="customDocumentType"
        type="text"
        :rules="customDocumentTypeRules"
        ref="customDocumentType"
      />

      <r-file-loader
        class="q-my-md"
        supportedFile=".tiff,.png,.jpeg,.pdf"
        v-model="files"
        @change="addFile"
      />
      <r-input label="Описание" v-model="commentForFile" type="text" />

      <template #process>
        <result-block type="info" icon="pgs-document" header="processMessage">
        </result-block>
      </template>
      <template #result>
        <result-block icon="pgs-document" header="resultMessage">
        </result-block>
      </template>
      <template #right-actions>
        <r-btn
          label="Загрузить"
          :action='true'
          :disabled='isLoading'
          @click='loadFile'
          v-activity-recorder="activityRecorderOption"
        />
      </template>
      <template #right-actions-result>
        <r-btn
          action
          label="Продолжить"
          icon-right="pgs-shevron-right-off"
          @click="finish"
        />
      </template>
    </operation-dialog>
  </div>
</template>

<i18n>
  {
    "ru": {
      "Summon": {
        "selected": "не выбрано | один рекрут | {n} рекрута | {n} рекрутов",
        "process": " | Документ формируется | Документы формируются | Документы формируются",
        "result": " | Документ сформирован | Документы сформированы | Документы сформированы"
      }
    }
  }
</i18n>

<style lang="scss" scoped>
.SummonDateInput {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: flex-end;
  gap: 8px;
  &-Count {
    line-height: 32px;
    margin-top: 16px;
    align-self: end;
  }
}
</style>

<script lang="ts">
import { Component, Mixins, Prop, Ref } from 'vue-property-decorator';
import { DictionariesElement, PersonRegistryApi, RecruitV4 } from '@/recruits/openapi/person-registry';
import { Option } from '@/recruits/models';
import TaskButton from '@/mixins/TaskButton';
import OperationDialog from '@/components/common/operation-dialog/index.vue';
import Dialog from '@/mixins/Dialog';
import RDateTimeInput from '@/recruits/components/common/r-date-time-input.vue';
import RSelect from '@/recruits/components/common/r-select.vue';
import RInput from '@/recruits/components/common/r-input/index.vue';
import RFileLoader from '@components/common/r-file-loader/index.vue';

interface FileInfo {
  file: File;
  fileName: string;
  fileSize: string;
}

@Component({
  components: {
    RDateTimeInput,
    RSelect,
    RInput,
    RFileLoader,
  },
})
export default class AddDocument extends Mixins(TaskButton, Dialog) {
  registryApi = new PersonRegistryApi();
  isLoading = false;

  @Prop({ default: () => 'Добавление документа' })
  readonly title: string;

  @Prop({ default: () => ({}) })
  declare readonly model: RecruitV4;

  @Prop()
  activityRecorderOptions: any;

  @Ref('dialog') operationDialog: OperationDialog;

  @Ref('customDocumentType') documentTypeInput: RInput;

  @Prop() activityRecorderOption: any;

  opened = false;

  documentType: Option | null = null;
  customDocumentType = '';
  files: File[] | null = null;
  file: File | null = null;
  commentForFile = '';

  get anyDocument(): boolean {
    return this.documentType?.label === 'Иной документ';
  }

  get options(): Option[] {
    const types: DictionariesElement[] =
      this.$store.getters['ervuDictionaries/personalDocumentTypesDictionary'] ??
      [];
    return types.map(({ code, value }) => ({
      value: code,
      label: value,
    }));
  }

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

  async loadFile(): Promise<void> {
    if (this.anyDocument) {
      this.documentTypeInput.validate();

      if (!this.documentTypeInput.isValid) return;
    }

    if (this.file) {
      try {
        this.isLoading = true;
        const { data } = await this.registryApi.createRecruitAttachmentV1(
          this.documentType?.value,
          this.customDocumentType,
          this.model.id,
          this.commentForFile,
          this.file
        );
        if (data.createDate) {
          this.$recordActivity({
            buttonCode: 'doc_unload',
            extraInfo: {
              comment: this.commentForFile,
              documentType: this.documentType?.label || '',
              ...this.activityRecorderOptions,
            },
          });
          this.$emit('uploaded', data);
        }
      } catch (error) {
      } finally {
        this.close();
        this.documentType = null;
        this.customDocumentType = '';
        this.file = null;
        this.commentForFile = '';
        this.isLoading = false;
      }
    }
  }

  addFile([file]: FileInfo[]): void {
    this.file = file?.file || null;
  }

  customDocumentTypeRules: ((value: string) => true | string)[] = [
    (val: string): true | string =>
      (val && val.length > 0) || 'Обязательное поле',
  ];
}
</script>
