<template>
  <q-card class="LoadDialog no-right-border-radius">
    <q-card-section class="LoadDialog-Content" v-if="showForm">
      <p class="text-h5">Формирование запроса</p>
      <q-list>
        <q-item tag="label" v-ripple>
          <q-item-section avatar>
            <q-radio v-model="action" val="actual" />
          </q-item-section>
          <q-item-section>
            <q-item-label>Актуализация сведений воинского учёта</q-item-label>
          </q-item-section>
        </q-item>
        <q-item tag="label" v-ripple>
          <q-item-section avatar>
            <q-radio v-model="action" val="file" />
          </q-item-section>
          <q-item-section>
            <q-item-label>Получить из файла</q-item-label>
          </q-item-section>
        </q-item>
      </q-list>
      <q-card class="LoadDialog-Forms">
        <q-card-section v-if="action === 'file'">
          <r-file-loader @change="addFile" />
        </q-card-section>
      </q-card>
    </q-card-section>
    <q-card-section class="LoadDialog-ResultBlock" v-else>
      <q-icon
        class="LoadDialog-ResultBlockIcon"
        name="pgs-double-check"
        color="positive"
      />
      <p class="LoadDialog-ResultBlockText">Список сформирован</p>
      <p class="LoadDialog-ResultBlockInfo">
        Загружено {{ resultData }} записей из ЕРВУ
      </p>
    </q-card-section>
    <q-card-actions class="LoadDialog-Actions" v-if="showForm">
      <q-btn
        outline
        label="Отмена"
        icon="pgs-close"
        color="primary"
        class="redesigned-outline-btn button-text"
        v-close-popup
      />
      <q-btn
        label="Сформировать запрос"
        icon="pgs-sign-2"
        class="redesigned-action-btn button-text"
        @click="ListFormation"
      />
    </q-card-actions>
    <q-card-actions class="LoadDialog-Actions" v-else>
      <q-btn
        outline
        label="Закрыть"
        icon="pgs-close"
        color="primary"
        class="redesigned-outline-btn button-text"
        v-close-popup
      />
    </q-card-actions>
  </q-card>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import dataBlock from '@components/cards/statements/components/dataBlock.vue';
import RFileLoader from '@components/common/r-file-loader/index.vue';
import { startWithFiles } from '@services/wf';
import get from 'lodash/get';
import { notifySuccess } from '@utils/notify';

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

@Component({
  components: {
    RFileLoader,
    dataBlock,
  },
})
export default class RegisterNewRecruitForm extends Vue {
  action = '';
  files: FileInfo | null = null;
  showForm = true;
  resultData = '';

  ListFormation(): void {
    switch (this.action) {
      case 'file':
        if (this.files) {
          startWithFiles({
            file: this.files.file,
            json: {
              userId: this.$store.getters['oidcClient/currentUser'].sub,
              processKey: 'milBaseImportProcess',
              data: {
                domainId: this.$store.getters['oidcClient/currentUser']
                  .domain_id,
              },
            },
          })
            .then(({ data: { msg = '' } }) => {
              const traceIdMatch = msg.match(/traceId=[a-zA-Z0-9-]+/);
              let traceId = '';
              if (traceIdMatch) {
                traceId = traceIdMatch[0].slice(8);
              }
              const handler = (e: any) => {
                const data = JSON.parse(get(e, 'data', '{}'));
                if (data.traceId === traceId) {
                  if (data.body.type !== 'info') {
                    if (data.body.userTask.outData.success) {
                      this.$q.loading.hide();
                      this.showForm = false;
                      this.resultData = data.body.userTask.outData.count;
                    }
                    this.$websockets.removeListener(handler);
                  } else if (data.body.type === 'info') {
                    this.$q.loading.show({
                      message: 'Идет обработка данных',
                    });
                  }
                }
              };
              this.$websockets.addListener(handler);
            })
            .catch((err) => {
              console.log(err);
            });
        }
        break;
      case 'actual':
        console.log('Актуализация');
        break;
    }
  }

  addFile([file]: FileInfo[]): void {
    this.files = file || null;
  }
}
</script>

<style lang="scss" scoped>
.no-right-border-radius {
  border-top-right-radius: 0;
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 0;
}
.LoadDialog {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  &-Content {
    font-family: 'Golos Text', sans-serif;
  }
  &-Actions {
    background: rgba(15, 32, 160, 0.08);
    display: flex;
    justify-content: space-between;
  }
  &-Forms {
    box-shadow: none;
  }
  &-ResultBlock {
    flex-basis: 80%;
    font-family: 'Golos UI', sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
  &-ResultBlockIcon {
    border-radius: 50%;
    background-color: rgba(1, 72, 116, 0.11);
    font-size: 50px;
    margin-bottom: 10px;
  }
  &-ResultBlockText {
    font-size: 14px;
    margin: 0;
  }
  &-ResultBlockInfo {
    font-size: 20px;
    font-weight: bold;
    margin: 0;
  }
}
.button-text {
  font-family: 'Golos UI', sans-serif;
  text-transform: initial;
}
</style>
