<i18n>
{
  "en": {
    "visitTime": "Visit time"
  },
  "ru": {
    "visitTime": "Время записи наприем"
  }
}
</i18n>

<template>
  <div v-if="slotHasLoaded || loading">
    <div class="q-mt-lg">
      <div class="row q-gutter-x-md items-center">
        <div class="col-4 text-grey-9">{{ $t('visitTime') }}</div>
        <div class="col text-primary">
          <q-skeleton v-if="loading" type="text" />
          <q-chip v-else dense icon="event">
            {{ displayDate(slot.visitTime) }}
          </q-chip>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import FormGeneratorWrapper from '@components/common/node-generator/FormGeneratorWrapper.vue';
import { notifyError } from '@utils/notify';
import preorderService from '@services/preorder';
import { SlotDTO, TicketDTO } from '@/openapi/preorder-pgs';
import get from 'lodash/get';
import { isEmpty } from 'lodash';
import { convertDateFormat, DateFormat } from '@/utils/format-date';

interface Model {
  id: string;
  common: {
    orderId: string;
    dueDate: string;
  };
  statement: {
    formTarget: {
      id: string;
    };
  };
  system: {
    startDate: string;
    startDateIso: string;
  };
  documents: any[];
}

@Component({
  components: {
    FormGeneratorWrapper,
  },
  methods: {
    get,
  },
})
export default class PreorderInfo extends Vue {
  get: typeof get;

  @Prop({ default: () => ({}) }) model: Model;

  @Watch('model', { immediate: true })
  onModelChange(): void {
    if (isEmpty(this.slot)) {
      this.fetchSlot();
    }
  }

  loading = false;
  ticket: TicketDTO = {};

  get slotHasLoaded(): boolean {
    return !isEmpty(this.slot);
  }

  get slot(): SlotDTO {
    return this.ticket?.timeSlot || {};
  }

  get resDocument(): any {
    return this.model?.documents?.find((el) =>
      el.resNumber ? el.resNumber : el.number
    );
  }

  displayDate(dateString?: string): string {
    if (!dateString) return '';
    return convertDateFormat(
      new Date(dateString),
      DateFormat.backend,
      DateFormat.dateTimeFull
    );
  }

  async fetchSlot(): Promise<void> {
    this.loading = true;
    try {
      const orderId = this.model?.common?.orderId;
      const startDate = this.model?.system?.startDateIso;
      const endDate = convertDateFormat(
        this.resDocument?.resDate || this.model?.common?.dueDate,
        DateFormat.date,
        DateFormat.invertedDate
      );
      const serviceId = this.model?.statement?.formTarget?.id;
      console.log(orderId, startDate, endDate, serviceId);

      if (!orderId) return;

      const [ticket] = await preorderService.getTickets({
        serviceId,
        orderId,
        startDate,
        endDate,
      });

      this.ticket = ticket;
    } catch (error) {
      console.error({ error });
      notifyError('Не удадлсь загрузить время записи клинта на прием');
    }
    this.loading = false;
  }
}
</script>
