<template>
  <ui-select
    @popup-hide="isPopupShow = false"
    @popup-show="isPopupShow = true"
    v-bind="$attrs"
    v-on="$listeners"
    v-model="shipmentPoint"
    :option-label="option => getOptionLabel(option)"
    :options="groups"
    label="Откуда"
    name="source.country"
  >
    <template v-slot:option="scope">
      <q-item v-bind="scope.itemProps" dense class="no-pointer-events q-mt-md">
        <q-item-section>
          <q-item-label
            class=" text-caption text-blue-grey"
            v-html="scope.opt.countryName"
          />
        </q-item-section>
      </q-item>
      <q-item
        v-for="point in scope.opt.points"
        @click="shipmentPoint = point"
        :key="point.id"
        v-ripple
        v-close-popup
        clickable
        class="q-pl-lg"
        :active="shipmentPoint !== null && shipmentPoint.id === point.id"
      >
        <q-item-section>
          <q-item-label v-html="getOptionLabel(point)" />
        </q-item-section>
      </q-item>
    </template>
    <template slot="after-options">
      <div class="q-pt-md"></div>
    </template>
  </ui-select>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import ShipmentPoint from '../dto/ShipmentPoint'
import ShipmentPointsGroup from '../dto/ShipmentPointsGroup'
import UiSelect from '../../../form/UiSelect.vue'
import DeliveryCalculatorStore, {
  getDeliveryCalculatorStore,
} from '../utils/DeliveryCalculatorStore'
import { ClosePopup, QItem, QItemLabel, QItemSection, Ripple } from 'quasar'

@Component({
  directives: { Ripple, ClosePopup },
  components: { UiSelect, QItem, QItemSection, QItemLabel },
  inheritAttrs: false,
})
export default class FromShipmentPointSelect extends Vue {
  isPopupShow = false
  calculatorStore!: DeliveryCalculatorStore

  created() {
    this.calculatorStore = getDeliveryCalculatorStore(this.$store)
    this.calculatorStore.loadShipmentPoints()
  }

  get shipmentPoint(): ShipmentPoint | null {
    return this.calculatorStore.shipmentPoint
  }

  set shipmentPoint(point: ShipmentPoint | null) {
    if (point) {
      this.calculatorStore.setShipmentPoint(point)
    }
  }

  get groups(): ShipmentPointsGroup[] {
    return this.calculatorStore.shipmentPointGroups
  }

  getOptionLabel(point: ShipmentPoint): string {
    return this.isPopupShow && point
      ? point.city.name
      : `${point.city.name} / ${point.country.name}`
  }
}
</script>
