<template>
  <q-dialog v-model="open" @hide="cancelSave">
    <q-card class="full-width no-shadow" style="max-width: 800px">
      <q-form v-if="!digitalRegulationsModel">
        <q-card-section class="q-pb-md q-gutter-y-md">
          <div class="text-h6">Импорт из КЦР</div>
        </q-card-section>
        <q-card-section class="q-pb-md q-gutter-y-md">
          <q-btn-toggle
            v-model="mode"
            toggle-color="primary"
            :options="[
              { label: 'Файл', value: 'file' },
              { label: 'Сервис', value: 'service' },
            ]"
          />
          <q-file
            v-if="mode === 'file'"
            v-model="file"
            :rules="[() => file || 'Обязательное поле']"
            accept=".xml"
            clearable
            filled
            counter
            fille
            label="Загрузить"
          />
          <q-input
            v-if="mode === 'service'"
            v-model="kcrName"
            filled
            label="Номер услуги в КЦР"
          >
          </q-input>
          <q-expansion-item v-if="mode === 'service'">
            <q-input v-model="token" filled label="Токен" />
          </q-expansion-item>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            type="button"
            color="primary"
            :label="$t('registries.objectCard.cancel')"
            @click="cancelSave"
          />

          <q-btn
            label="Загрузить"
            color="primary"
            :loading="loading"
            @click="fileImport"
          />
        </q-card-actions>
      </q-form>
      <div v-else>
        <q-card-section
          v-if="digitalRegulationsModel.parsed"
          class="q-pb-md q-gutter-y-md"
        >
          <div class="text-h6">Услуга успешно импортирована</div>

          <div class="text-subtitle2">
            Услуга содержит
            {{ digitalRegulationsModel.processCount || 0 }} процесса(ов).
          </div>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn
            icon="create"
            label="Перейти к услуге"
            color="primary"
            @click="goToService"
          />
        </q-card-actions>
      </div>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">
import { Component, PropSync, Vue } from 'vue-property-decorator';
import axios from 'axios';
import { DigitalReglamentApi, ImportResult } from '@openapi/registry-service';
import { notifyError } from '@utils/notify';

interface KCRToken {
  // todo eslint rule
  // eslint-disable-next-line camelcase
  access_token: string;
  // eslint-disable-next-line camelcase
  expires_in: number;
  scope: string;
  // eslint-disable-next-line camelcase
  token_type: 'bearer';
}

const digitalReglamentApi = new DigitalReglamentApi();

@Component({})
export default class DigitalRegulationsFormDialog extends Vue {
  @PropSync('openDialog') open: boolean;
  private file: File | null = null;
  private mode = 'service';
  private digitalRegulationsModel: ImportResult | null = null;
  private loading = false;
  private kcrName = '';
  private token: string | null = null;

  async created(): Promise<void> {
    const res: KCRToken = await axios
      .request({
        method: 'POST',
        url:
          'https://kcr-test.test.gosuslugi.ru/uaa/oauth/token?grant_type=client_credentials',
      })
      .then(({ data }) => data)
      .catch((err) =>
        console.error(
          '[digital regulations form dialog][created] no token',
          err
        )
      );

    if (res?.access_token) {
      this.token = res.access_token;
    }
  }

  goToService() {
    this.$router.push({
      name: 'cards',
      params: {
        id: this.digitalRegulationsModel?.serviceId || '',
        path: 'services',
      },
      query: {
        active: 'digital_regulations',
        components: this.$store.getters['cardComponents/services/components'],
      },
    });
  }

  cancelSave() {
    this.open = false;
    this.kcrName = '';
    this.digitalRegulationsModel = null;
    this.file = null;
  }

  async fileImport() {
    try {
      this.loading = true;
      let file;
      if (this.mode === 'service') {
        if (!this.kcrName) {
          return;
        }
        axios.defaults.headers.common.Authorization = `Bearer ${this.token}`;
        // todo fix /microws
        const xml = await axios.get(
          `/microws/microws/kcr-core/container/${this.kcrName}`
        );
        file = new File([xml.data], `test.xml`);
      } else {
        if (!this.file) {
          this.loading = false;
          return;
        }
        file = this.file;
      }
      const {
        data: result,
      } = await digitalReglamentApi.importReglament(
        undefined,
        undefined,
        undefined,
        [file]
      );

      this.digitalRegulationsModel = {
        serviceId: result.serviceId,
        formCount: result.formCount,
        processCount: result.processCount,
        parsed: result.parsed,
      };

      if (!this.digitalRegulationsModel?.parsed) {
        throw new Error('Невозможно импортировать файл');
      }
    } catch (e) {
      notifyError(e.message.toString());
      this.cancelSave();
    } finally {
      this.loading = false;
    }
  }
}
</script>
