<template>
  <div class="q-pa-lg bg-background">
    <div class="q-mb-lg">
      Номер будет добавлен в очередь на проверку, данные обновляются каждые 3
      часа
    </div>
    <ui-input
      v-model="trackNumber"
      label="Трэк номер"
      name="trackNumber"
      class="q-mb-sm bg-white"
    />
    <track-carrier-select v-model="carrierCode" class="bg-white" />

    <div class="q-pt-md q-gutter-x-sm">
      <ui-btn @click="submitForm" label="Добавить" />
      <ui-btn-cancel @click="cancel" />
    </div>
    <div v-if="hasError" class="text-negative q-mt-md">
      Укажите номер и выберите отправителя
    </div>
    <ui-page-loading :showing="isLoading" />
  </div>
</template>

<script lang="ts">
import { Emit, Vue, Component, Prop, Watch } from 'vue-property-decorator'
import UiPageLoading from '../../../../../lib-components/UiPageLoading.vue'
import UiBtnClose from '../../../../../lib-components/buttons/UiBtnClose.vue'
import UiPageHeader from '../../../../../lib-components/UiPageHeader.vue'
import UiInput from '../../../../../lib-components/form/UiInput.vue'
import UiBtn from '../../../../../lib-components/buttons/UiBtn.vue'
import UiBtnCancel from '../../../../../lib-components/buttons/UiBtnCancel.vue'
import TrackCarrierSelect from './TrackCarrierSelect.vue'
import { getDeliveryTrackingStore } from '../../store/DeliveryTrackingStore'
import { Track } from '../../dto/Track'

@Component({
  components: {
    UiPageLoading,
    UiBtnCancel,
    UiBtn,
    TrackCarrierSelect,
    UiInput,
    UiPageHeader,
    UiBtnClose,
  },
})
export default class TrackForm extends Vue {
  @Prop(String) projectHost!: string

  trackNumber = ''
  carrierCode = ''
  hasError = false
  isLoading = false

  deliveryTrackStore = getDeliveryTrackingStore(this.$store)

  created() {
    this.trackNumber = ''
    this.carrierCode = ''
  }

  get isEmpty() {
    return !this.trackNumber || !this.carrierCode
  }

  async submitForm() {
    if (this.isEmpty) {
      this.hasError = true
    } else {
      this.isLoading = true

      const track: Track = await this.deliveryTrackStore.loadTrack({
        trackNumber: this.trackNumber,
        carrierCode: this.carrierCode,
        projectHost: this.projectHost,
      })

      this.isLoading = false

      this.submit(track)
    }
  }

  @Emit()
  submit(track: Track) {
    return track
  }

  @Emit()
  cancel() {
    return true
  }

  @Watch('isEmpty')
  resetError() {
    if (!this.isEmpty) {
      this.hasError = false
    }
  }
}
</script>
