<template>
  <div class="q-pa-md q-col-gutter-y-md redesigned Import">
    <div class="row" v-if="step === 1">
      <q-card class="Import-File">
        <q-card-section>
          <r-file-loader supportedFile=".csv" @change="addFile" />
          <div class="Import-FileInfo" v-if="files">
            <div class="Import-FileInfo__Icon">
              <q-icon class="" name="pgs-document" />
            </div>
            <div class="Import-FileInfo__FileName">{{ files.fileName }}</div>
            <div class="Import-FileInfo__FileSize">{{ files.fileSize }}Kb</div>
          </div>
        </q-card-section>
        <q-card-actions>
          <r-btn label="Загрузить" @click="loadFile" />
        </q-card-actions>
      </q-card>
    </div>
    <div class="row" v-if="step === 2">
      <!-- FIXME сделать компонент окна уведомления -->
      <q-dialog
        v-model="requestImportDialog"
        class="ImportDialogRequest"
        no-backdrop-dismiss
      >
        <q-card class="full-width no-shadow" style="max-width: 800px">
          <q-card-section class="ImportDialog-AttentionContent">
            <q-icon
              class="ImportDialog-AttentionContent__Icon"
              name="pgs-import"
            />
            <p class="ImportDialog-AttentionContent__Header">
              Загрузка файла завершена
            </p>
            <div class="ImportDialog-AttentionContent__Noty">
              <div>
                Успешно найденных записей: {{ result.successCount || '0' }}
              </div>
              <div>Не найдено записей: {{ result.errorsCount || '0' }}</div>
              <div>Обработано записей: {{ result.totalCount || '0' }}</div>
            </div>
            <q-expansion-item
              v-model="expansion"
              v-if="
                Array.isArray(result.idErnErrorsList) &&
                result.idErnErrorsList.length
              "
              :label="`ИД ЕРН записей с ошибками: ${result.idErnErrorsList.length}`"
              class="ImportDialog-AttentionContent__SysInfo full-width"
            >
              <q-card-section>
                <span>
                  {{ result.idErnErrorsList.join(', ') }}
                </span>
              </q-card-section>
            </q-expansion-item>
          </q-card-section>
          <q-card-actions class="ImportDialog-AttentionButtons">
            <r-btn
              class="ImportDialog-AttentionButton"
              label="Закрыть"
              v-close-popup
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
      <data-table
        :data="data"
        @row-selected="rowSelected"
        :resetSelect="resetSelect"
        :rows-per-page-options="[10, 25, 50, 100]"
      />
    </div>
    <q-dialog v-model="apiErrorShow">
      <process-api-error :errorObject="errorObject"/>
    </q-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import SortBar from '@/recruits/components/common/sort-bar.vue';
import DataTable from './data-table.vue';
import {
  PersonRegistryApi,
  CsvImportResult,
} from '@/recruits/openapi/person-registry';
import { ListRecordV2 } from '@/recruits/openapi/summon-list-service';
import ProcessApiError from '@/recruits/components/dialogs/ProcessApiError.vue';
interface FileInfo {
  file: File;
  fileName: string;
  fileSize: string;
}

@Component({
  components: {
    DataTable,
    SortBar,
    ProcessApiError,
  },
})
export default class CallListsImportCsv extends Vue {
  @Prop() resetSelect: boolean;
  PersonRegistryApi = new PersonRegistryApi();

  public data: Array<ListRecordV2> | undefined = [];
  public requestImportDialog = false;
  public expansion = false;

  public step = 1;
  files: FileInfo | null = null;
  public result: CsvImportResult | null = null;

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

  errorObject = {};
  apiErrorShow = false;

  async loadFile(): Promise<void> {
    if (this.files) {
      this.$q.loading.show({
        message: 'Файл загружается',
      });
      try {
        const { data } = await this.PersonRegistryApi.importFileForLists(
          this.files.file
        );

        this.result = data.resultInfo || null;
        this.data = data.data || [];
        this.step++;
        this.requestImportDialog = true;
      } catch (error) {
        this.apiErrorShow = true;
        this.errorObject = error.response;
      } finally {
        this.$q.loading.hide();
        this.files = null;
      }
    }
  }

  rowSelected(val: string[]): void {
    this.$emit('row-selected', val);
  }
}
</script>

<style lang="scss" scoped>
.ImportDialogRequest {
  &-Header {
    color: rgba(2, 12, 18, 0.9);
    font-size: 20px;
    font-family: 'Golos Text', sans-serif;
    font-weight: 500;
    line-height: 24px;
    letter-spacing: -0.3px;
  }
  &-Content {
    &__Info {
      margin-bottom: 20px;
    }
    &__Message {
      font-size: 16px;
      font-family: 'Golos Text', sans-serif;
    }
  }
  &-Total,
  &-New,
  &-Update {
    color: rgba(2, 12, 18, 0.8);
    font-size: 18px;
    font-family: 'Golos Text', sans-serif;
    font-weight: 500;
    line-height: 24px;
    letter-spacing: -0.3px;
    &:not(:last-child) {
      margin-right: 15px;
    }
  }
  &-FileInfo {
    &__File,
    &__Time {
      color: rgba(2, 12, 18, 0.8);
      font-size: 16px;
      font-family: 'Golos Text', sans-serif;
      line-height: 24px;
      letter-spacing: -0.3px;
      & > span {
        font-weight: 500;
      }
    }
  }
  &-Dialog {
    min-width: 1000px;
    background-color: rgb(245 248 251);
  }
  &-TableHeader {
    padding: 6px 0;
    color: rgba(2, 12, 18, 0.58);
    overflow: hidden;
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 600;
    font-size: 10px;
    line-height: 12px;
    letter-spacing: 0.05em;
    text-transform: uppercase;
  }
  &-TableRow {
    display: grid;
    grid-template-columns: 2fr 2fr 2fr 3fr;
    border-bottom: 1px solid rgba(1, 72, 116, 0.11);
    padding: 4px 0;
  }
  &-TableCell {
    color: rgba(2, 12, 18, 0.58);
    font-size: 12px;
    font-family: 'Golos UI', sans-serif;
    line-height: 14px;
    font-weight: 500;
  }
  &-ErrorString {
    &:not(:first-child) {
      padding: 2px;
    }
  }
  &-Actions {
    background-color: rgb(245 245 245);
    display: flex;
    justify-content: flex-end;
  }
}
.ImportDialog {
  &-AttentionContent {
    * {
      margin: 0;
      padding: 0;
    }
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 30px 40px;
    &__SysInfo {
      color: #6c7276;
    }
    &__Icon {
      color: #1491cf;
      font-size: 40px;
      margin-bottom: 10px;
    }
    &__Header {
      font-family: 'Golos Text', sans-serif;
      font-style: normal;
      font-weight: 500;
      font-size: 20px;
      line-height: 24px;
      text-align: center;
      letter-spacing: -0.015em;
      color: #015e98;
      margin-bottom: 24px;
    }
    &__Noty {
      background: #e2f0ff;
      border-left: 2px solid #015e98;
      padding: 8px;

      font-family: 'Golos UI', sans-serif;
      font-style: normal;
      font-weight: 400;
      font-size: 14px;
      line-height: 16px;
      text-align: left;
      width: 100%;
      color: #015e98;
      margin-bottom: 20px;
    }
  }
  &-AttentionButtons {
    display: flex;
    justify-content: space-between;
    padding: 12px 20px;
  }
  &-AttentionButton {
    padding: 0 10px;
  }
}
.Import {
  &-File {
    width: 100%;
  }
  &-FileInfo {
    display: grid;
    grid-template-columns: 38px 1fr;
    grid-template-rows: 1fr 1fr;
    grid-template-areas:
      'icon name'
      'icon size';
    &__Icon {
      align-self: center;
      grid-area: icon;
      color: rgba(2, 12, 18, 0.7);
      font-size: 35px;
    }
    &__FileName {
      grid-area: name;
      font-family: 'Golos UI', sans-serif;
      font-style: normal;
      font-weight: 500;
      font-size: 12px;
      line-height: 14px;
      color: rgba(2, 12, 18, 0.9);
      align-self: end;
    }
    &__FileSize {
      grid-area: size;
      font-family: 'Golos UI', sans-serif;
      font-style: normal;
      font-weight: 400;
      font-size: 12px;
      line-height: 14px;
      color: rgba(2, 12, 18, 0.58);
    }
  }
}
.flip-icon::v-deep {
  i {
    transform: scaleX(-1);
  }
}
</style>
