<!-- eslint-disable vue/valid-v-for -->
<template>
  <div>
    <div class="q-mt-md">
      <q-breadcrumbs class="q-mb-md" active-color="black">
        <template v-slot:separator>
          <q-icon size="1.5em" name="chevron_right" color="black" />
        </template>
        <q-breadcrumbs-el label="Laca" icon="home" to="/" />
        <q-breadcrumbs-el label="Thêm chỗ gửi xe" />
      </q-breadcrumbs>
      <div class="row justify-end q-pa-sm q-gutter-sm">
        <q-btn class="float-right q-mb-sm" :label="`${$route.query.id ? 'Sửa Bãi Đỗ' : 'Thêm Bãi Đỗ'}`"
          color="primary" @click="newParkingDialog = true" no-caps v-if="!$q.screen.gt.sm" />
        <div class="col-4 float-left">
          <q-btn class="float-right q-mb-sm" label="Bãi Xe Của Tôi" color="secondary" @click="gotoMyPacking" no-caps />
        </div>
      </div>
      <div class="row">
        <div class="col-4" v-if="$q.screen.gt.sm">
          <q-card style="width: 100%" class="bg-white text-black">
            <q-card-section>
              <div class="text-h6">Thông tin bãi xe</div>
            </q-card-section>
            <q-card-section class="row items-center">
              <q-form ref="form">
                <div class="col-12 q-py-xs ">
                  <q-input color="black" class="required" dense v-model="slotData.name"
                    :rules="[(val) => !!val || 'Không để trống Tên bãi đỗ']" label="Tên bãi đỗ" />
                </div>
                <div class="col-12 q-py-xs row q-col-gutter-md">
                  <q-input class="col-md-6 col-xs-12 required" color="black" dense type="number"
                    v-model="slotData.total" :rules="[(val) => !!val || 'Không để trống Tên Bãi Đỗ']" suffix="Chỗ"
                    label="Tổng vị trí" />
                  <q-input class="col-md-6 col-xs-12" color="black" dense type="number"
                    v-model="slotData.pricingPerHour" suffix="VND" label="Giá" />
                </div>
                <div class="col-12 q-py-xs row q-col-gutter-md">
                  <q-select class="col-12" color="black" dense :options="options" option-value="value"
                    option-label="label" v-model="slotData.slotType" label="Loại bãi đỗ" />
                </div>
                <div class="col-12 q-py-xs">
                  <q-input color="black" class="required" :rules="[(val) => !!val || 'Không để trống Quận/Huyện']"
                    readonly v-model="slotData.address" hint="Chọn vị trí trên bản đồ" label="Địa Chỉ" />
                </div>
                <div class="col-12 q-py-xs row q-col-gutter-md">
                  <q-input class="col-md-4 col-xs-12 required" color="black" dense v-model="slotData.city"
                    :rules="[(val) => !!val || 'Không để trống Thành Phố']" label="Thành Phố" />
                  <q-input class="col-md-4 col-xs-12 required" color="black" dense v-model="slotData.district"
                    :rules="[(val) => !!val || 'Không để trống Quận/Huyện']" label="Quận/Huyện" />
                  <q-input class="col-md-4 col-xs-12 required" color="black" dense v-model="slotData.ward"
                    :rules="[(val) => !!val || 'Không để trống Xã/Phường']" label="Xã/Phường" />
                </div>
                <div class="col-12 q-py-xs row q-col-gutter-md">
                  <q-input class="col-6 required" dense color="black" v-model="slotData.open" mask="time"
                    label="Thời gian mở" :rules="[(val) => !!val || 'Không để trống Thời gian mở', 'time']">
                    <template v-slot:append>
                      <q-icon name="access_time" class="cursor-pointer">
                        <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                          <q-time format24h v-model="slotData.open">
                            <div class="row items-center justify-end">
                              <q-btn v-close-popup label="Close" color="primary" flat />
                            </div>
                          </q-time>
                        </q-popup-proxy>
                      </q-icon>
                    </template>
                  </q-input>

                  <q-input class="col-6 required" dense color="black" v-model="slotData.close" mask="time" label="Thời gian đóng"
                    :rules="[(val) => !!val || 'Không để trống Thời gian đóng', 'time']">
                    <template v-slot:append>
                      <q-icon name="access_time" class="cursor-pointer">
                        <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                          <q-time format24h v-model="slotData.close">
                            <div class="row items-center justify-end">
                              <q-btn v-close-popup label="Close" color="primary" flat />
                            </div>
                          </q-time>
                        </q-popup-proxy>
                      </q-icon>
                    </template>
                  </q-input>
                </div>
                <div class="col-12 q-py-xs">
                  <q-input color="black" dense v-model="slotData.contact" label="Mô tả" />
                </div>
              </q-form>

            </q-card-section>
            <q-card-actions align="right">
              <q-btn color="secondary" @click="addSlotHandle">
                {{ $route.query.id ? 'Sửa' : 'Thêm' }}
              </q-btn>
            </q-card-actions>
          </q-card>
        </div>
        <div :class="`map ${$q.screen.gt.sm ? 'col-8' : 'col-12'}`">
          <div>
            <MglMap :map-style="mapStyle" :center="center" :zoom="15" height="calc(100vh - 120px)">
              <MglGeolocateControl :showAccuracyCircle="false" :showUserLocation="false" />
              <MglNavigationControl />
              <MglCustomControl position="top-right" v-if="false">
                <q-btn icon="list" @click="showListMarkerInfo = !showListMarkerInfo" />
              </MglCustomControl>
              <MglMarker :coordinates="currentPosition" />
            </MglMap>
          </div>
          <div :class="`w-full location-input location-input-${$q.screen.gt.sm ? 'md' : 'sm'}`">
            <div id="autocomplete" ref="autocomplete" class="gmap-input autocomplete-container w-full sm:w-1/1"></div>
          </div>
        </div>
      </div>
    </div>
    <q-dialog v-model="newParkingDialog" position="bottom" v-if="!$q.screen.gt.sm">
      <div class="diaglog-mobile">
        <q-card style="width: 100%;" class="bg-white text-black">
          <q-card-section>
            <div class="text-h6">Thông tin bãi xe</div>
          </q-card-section>
          <q-card-section class="row items-center">
            <q-form ref="form">
                <div class="col-12 q-py-xs ">
                  <q-input color="black" class="required" dense v-model="slotData.name"
                    :rules="[(val) => !!val || 'Không để trống Tên bãi đỗ']" label="Tên bãi đỗ" />
                </div>
                <div class="col-12 q-py-xs row q-col-gutter-md">
                  <q-input class="col-md-6 col-xs-12 required" color="black" dense type="number"
                    v-model="slotData.total" :rules="[(val) => !!val || 'Không để trống Tên Bãi Đỗ']" suffix="Chỗ"
                    label="Tổng vị trí" />
                  <q-input class="col-md-6 col-xs-12" color="black" dense type="number"
                    v-model="slotData.pricingPerHour" suffix="VND" label="Giá" />
                </div>
                <div class="col-12 q-py-xs row q-col-gutter-md">
                  <q-select class="col-12" color="black" dense :options="options" option-value="value"
                    option-label="label" v-model="slotData.slotType" label="Loại bãi đỗ" />
                </div>
                <div class="col-12 q-py-xs">
                  <q-input color="black" class="required" :rules="[(val) => !!val || 'Không để trống Quận/Huyện']"
                    readonly v-model="slotData.address" hint="Chọn vị trí trên bản đồ" label="Địa Chỉ" />
                </div>
                <div class="col-12 q-py-xs row q-col-gutter-md">
                  <q-input class="col-md-4 col-xs-12 required" color="black" dense v-model="slotData.city"
                    :rules="[(val) => !!val || 'Không để trống Thành Phố']" label="Thành Phố" />
                  <q-input class="col-md-4 col-xs-12 required" color="black" dense v-model="slotData.district"
                    :rules="[(val) => !!val || 'Không để trống Quận/Huyện']" label="Quận/Huyện" />
                  <q-input class="col-md-4 col-xs-12 required" color="black" dense v-model="slotData.ward"
                    :rules="[(val) => !!val || 'Không để trống Xã/Phường']" label="Xã/Phường" />
                </div>
                <div class="col-12 q-py-xs row q-col-gutter-md">
                  <q-input class="col-6 required" dense color="black" format24h v-model="slotData.open" mask="time"
                    label="Thời gian mở" :rules="[(val) => !!val || 'Không để trống Thời gian mở', 'time']">
                    <template v-slot:append>
                      <q-icon name="access_time" class="cursor-pointer">
                        <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                          <q-time format24h v-model="slotData.open">
                            <div class="row items-center justify-end">
                              <q-btn v-close-popup label="Close" color="primary" flat />
                            </div>
                          </q-time>
                        </q-popup-proxy>
                      </q-icon>
                    </template>
                  </q-input>

                  <q-input class="col-6 required" dense color="black" v-model="slotData.close" mask="time" label="Thời gian đóng"
                    :rules="[(val) => !!val || 'Không để trống Thời gian đóng', 'time']">
                    <template v-slot:append>
                      <q-icon name="access_time" class="cursor-pointer">
                        <q-popup-proxy cover transition-show="scale" transition-hide="scale">
                          <q-time format24h v-model="slotData.close">
                            <div class="row items-center justify-end">
                              <q-btn v-close-popup label="Close" color="primary" flat />
                            </div>
                          </q-time>
                        </q-popup-proxy>
                      </q-icon>
                    </template>
                  </q-input>
                </div>
                <div class="col-12 q-py-xs">
                  <q-input color="black" dense v-model="slotData.contact" label="Mô tả" />
                </div>
              </q-form>
          </q-card-section>
          <q-card-actions align="right">
            <q-btn color="secondary" @click="addSlotHandle">
              {{ $route.query.id ? 'Sửa' : 'Thêm' }}
            </q-btn>
          </q-card-actions>
        </q-card>
      </div>
    </q-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import { mapGetters, mapActions } from 'vuex';
import { GeocoderAutocomplete } from '@geoapify/geocoder-autocomplete';

import {
  MglMap,
  MglMarker,
  MglNavigationControl,
  MglGeolocateControl,
  MglCustomControl,
} from '@indoorequal/vue-maplibre-gl';

export default defineComponent({
  name: 'ParkingMap',
  components: {
    MglMap,
    MglMarker,
    MglNavigationControl,
    MglGeolocateControl,
    MglCustomControl,
  },

  data() {
    return {
      options: [
        {
          value: 'All',
          label: 'Tất cả',
        },
        {
          value: 'Motobike',
          label: 'Xe máy',
        },
        {
          value: 'Car',
          label: 'Ô Tô',
        },
      ],
      currencyFormatter: new Intl.NumberFormat('vi-VN', {
        style: 'currency',
        currency: 'VND',
      }),
      slotData: {
        id: -1,
        name: '',
        lat: 0,
        lng: 0,
        address: '',
        district: '',
        city: '',
        destination: '',
        total: 5,
        pricingPerHour: 50000,
        ward: '',
        bookingType: 'All',
        slotType: '',
        open: new Date(),
        close: new Date(),
        images: [],
        addressHolder: '',
      },
      newParkingDialog: true,
      showListMarkerInfo: true,
      mapStyle: `https://api.maptiler.com/maps/streets/style.json?key=${process.env.VUE_APP_API_KEY_STYLE_MAP}`,
      center: { lat: 21.028511, lng: 105.804817 },
      currentPosition: { lat: 0, lng: 0 },
      origin: '',
      destination: '',
      map: null,
      mapKey: process.env.VITE_APP_GEO_MAP_API_KEY,
      listMarker: [],
      activeMarker: {
        marker: null,
        id: null,
        position: { lat: 0, lng: 0 },
      },
    };
  },
  mounted() {
    this.initMap();
    const autocomplete = document.getElementById('autocomplete');
    if (autocomplete) {
      const geoAutocomplete = new GeocoderAutocomplete(
        autocomplete,
        this.mapKey,
        {
          lang: 'vi',
        }
      );
      geoAutocomplete.on('select', (location) => {
        this.center = {
          lat: parseFloat(location?.geometry?.coordinates[1]),
          lng: parseFloat(location?.geometry?.coordinates[0]),
        };
        this.currentPosition = this.center;
        const properties = location.properties;

        this.center = {
          lat: location.geometry.coordinates[1],
          lng: location.geometry.coordinates[0],
        };
        this.currentPosition = this.center;
        this.slotData = {
          ...this.slotData,
          lat: location.geometry.coordinates[1],
          lng: location.geometry.coordinates[0],
          address: properties?.formatted || properties?.street,
          addressHolder: properties?.formatted,
          city: properties?.state || properties?.city || '',
          district: properties?.suburb || '',
          ward: properties?.country || '',
          slotType: this.slotData.value,
        };
        if (!this.$q.screen.gt.sm) {
          this.newParkingDialog = true
        }
        if (!this.slotData.address?.length) {
          this.slotData.address = [this.slotData.ward, this.slotData.district, this.slotData.city].filter((item) => item.length).join(', ');
        }
      });

      geoAutocomplete.on('suggestions', (suggestions) => {
        console.log(suggestions);
      });
    }
  },
  computed: {
    ...mapGetters({
      getUser: 'userModule/getUser',
    }),
  },
  methods: {
    ...mapActions({
      getListSlotNear: 'slotModule/getListSlotNear',
      addSlot: 'slotModule/addSlot',
      updateSlot: 'slotModule/updateSlot',
      detailSlot: 'slotModule/detailSlot',
    }),
    async initMap() {
      await navigator.geolocation.getCurrentPosition(this.showPosition);
    },
    async showPosition(position: any) {
      let detailSelect = null;
      this.center = {
        lat: parseFloat(position.coords.latitude),
        lng: parseFloat(position.coords.longitude),
      };
      this.currentPosition = this.center;
      if (this.getUser) {
        const res = await this.getListSlotNear(this.center);
        this.listMarker = res.data.slots;
      }
      if (this.$route.query.id) {
        const resDetail = await this.detailSlot({ id: this.$route.query.id });
        detailSelect = resDetail.data;
        this.listMarker = [detailSelect];
        this.center = {
          lat: parseFloat(detailSelect.lat),
          lng: parseFloat(detailSelect.lng),
        };
        this.showListMarkerInfo = false;
        this.slotData = {
          id: resDetail.data.id,
          name: resDetail.data.name,
          lat: resDetail.data.lat,
          lng: resDetail.data.lng,
          address: resDetail.data.address,
          district: resDetail.data.district,
          city: resDetail.data.city,
          destination: resDetail.data.destination,
          total: resDetail.data.total,
          pricingPerHour: resDetail.data.pricing_per_hour,
          ward: resDetail.data.ward,
          bookingType: resDetail.data.alow_booking_type,
          slotType: resDetail.data.slot_type,
          open: resDetail.data.open,
          close: resDetail.data.close,
          images: resDetail.data.images,
          addressHolder: `${resDetail.data.address}, ${resDetail.data.ward}, ${resDetail.data.district}, ${resDetail.data.city}`,
        };
        // if (!isExistSlot) this.listMarker.push(detailSelect);
      }
      const mapOptions = {
        center: this.center,
        zoom: 20,
      };
    },
    selectMarker(location: any, marker: any, idx: any) {
      this.activeMarker = {
        marker: marker,
        id: location.id,
        position: {
          lat: parseFloat(location.lat),
          lng: parseFloat(location.lng),
        },
      };
      this.center = this.activeMarker.position;
    },
    gotoMyPacking() {
      this.$router.push({ name: 'my-parking' });
    },
    async addSlotHandle() {
      this.slotData.total = Number(this.slotData.total);
      if (!this.$refs.form.validate()) {
        this.$q.notify({
          badgeClass: 'hide-badge',
          message: 'Vui lòng nhập đầy đủ thông tin',
          color: 'negative',
          multiLine: true,
          position: 'top',
          html: true,
          classes: 'notify-error',
          timeout: 1000,
        });
        return;

      }
      try {
        if (this.$route.query.id) {
          await this.updateSlot(this.slotData);
        } else {
          await this.addSlot(this.slotData);
        }
        this.slotData.id = -1;
        this.$q.notify({
          badgeClass: 'hide-badge',
          message: 'Thêm thông tin thành công',
          color: 'positive',
          multiLine: true,
          position: 'top',
          html: true,
          timeout: 1000,
        });
        setTimeout(() => {
          this.$router.push({ name: 'my-parking' });

        }, 1000);
      } catch (e) {
        this.$q.notify({
          badgeClass: 'hide-badge',
          message: this.$t(`${e.response.data.message}`),
          color: 'negative',
          multiLine: true,
          position: 'top',
          html: true,
          classes: 'notify-error',
          timeout: 1000,
        });
        console.log(e);
      }
    },
    getImageUrl(images: [], index: number | null = null) {
      if (!images?.length) {
        return '/icons/logos/LACA_transparent2.png';
      }
      if (index == null) {
        const random = Math.floor(Math.random() * images.length);
        return `${process.env.VUE_APP_API_SERVER}/files/upload/${images[random]}`;
      }
      return `${process.env.VUE_APP_API_SERVER}/files/upload/${images[index]}`;
    },
    drag() {
      console.log([this.slotData.lng, this.slotData.lat]);
    },
  },
});
</script>

<style lang="scss">
@import '@geoapify/geocoder-autocomplete/styles/minimal.css';
@import 'maplibre-gl/dist/maplibre-gl.css';

.map {
  min-height: calc(100vh - 140px);
}

.q-page-container {
  position: relative;

  .map {
    position: relative;

    .location-input {
      position: absolute;
      top: 0;
      padding: 20px;

      &-md {
        width: 500px;
      }

      &-sm {
        width: 70vw;
      }
    }
  }

  .maplibregl-popup {
    border-radius: 16px;

    .maplibregl-popup-content {
      padding: 0;
      border-radius: 16px;

      .q-card {
        border-radius: 16px;
      }

      .maplibregl-popup-close-button {
        background: #fff;
        border-radius: 20px;
        top: 5px;
        right: 5px;
        font-size: 15px;
      }
    }
  }
}

.list-parking {
  z-index: 9999;

  .q-dialog__inner {
    padding: 0;
    top: unset;
  }

  .markers {
    &-md {
      min-width: 660px;
      height: calc(100vh - 62px);
    }

    &-sm {
      max-height: 50vh !important;
      width: 100vw;
    }
  }

  .q-card {
    // width: 300px;
    height: 300px;
    min-width: 300px;
    border-radius: 15px;

    &.active {
      border: 1px solid #0499a8;
    }

    .price {
      font-weight: bold;
      color: #0499a8;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }

}

.location-input {
  background-color: white;
  border-radius: 5px;
  margin: 10px;
  padding: 5px !important;
  box-sizing: initial;

}

.geoapify-autocomplete-input {
  border: 1px solid;
  border-radius: 5px;

  &::placeholder {
    // color: #f69801;
    font: 1rem sans-serif;
    font-style: italic;
    display: none;
    // background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='50px' width='120px'><text x='0' y='15' fill='gray' font-size='15'>Type Something...</text></svg>");
    // background-repeat: no-repeat;
  }

  focus {
    background-image: none;
  }
}

.diaglog-mobile {
  max-height: 60vh !important;
}
</style>
