<template>
  <main>
    <section>
<!--       <p class="content"><b>Selected:</b> {{ selected }}</p>
      <p class="content"><b>Coord:</b> {{ coord }}</p>
 -->      <b-field label="Trouver mon Commerce par nom ou par SIREN">
          <b-autocomplete
            :data="data"
            placeholder="ex: Chambre du commerce d'Evry"
            field="title"
            :loading="isFetching"
            icon="magnify"
            @typing="getAsyncData"
            
            @select="fetchOSM"

          >
            <template slot-scope="props">
              {{ props.option.properties.name }} — {{ props.option.properties.context }} : {{ props.option.geometry.type }} {{ props.option.geometry.coordinates }}
          </template>
        </b-autocomplete>
      </b-field>
    </section>
    <br />
    <section class="map">
     <div id="map-wrap" style="height: 75vh">
        <client-only>
          <l-map ref="myMap" :zoom=18 :center=coord>
            <l-tile-layer url="https://proxy-ign.openstreetmap.fr/94GjiyqD/bdortho/{z}/{x}/{y}.jpg" name="BDOrtho IGN" attribution="© <a href='https://www.openstreetmap.org/copyright'>BDOrtho IGN</a>" layer-type="base"></l-tile-layer>
            <l-tile-layer url="http://{s}.tile.osm.org/{z}/{x}/{y}.png" name="OSM" attribution="© <a href='https://www.openstreetmap.org/copyright'>contributeurs OSM</a>" layer-type="base"></l-tile-layer>
            <l-tile-layer url="https://{s}.tile-cyclosm.openstreetmap.fr/cyclosm-lite/{z}/{x}/{y}.png" name="CyclOSM" attribution="© <a href='https://www.openstreetmap.org/copyright'>CyclOSM</a>" layer-type="overlay"></l-tile-layer>
            <l-tile-layer url="https://{s}.layers.openstreetmap.fr/bano/{z}/{x}/{y}.png" name="BANO" attribution="© <a href='https://www.openstreetmap.org/copyright'>BANO</a>" layer-type="overlay"></l-tile-layer>
            <l-marker ref="myMarker" :lat-lng=coord ></l-marker> <!-- rajouter draggable pour le déplacer-->
            <l-control-layers/>
          </l-map>
        </client-only>
      </div>
     </section>

    <section v-if="mockAddok" class="result">
      <div class="card-content">
        <div class="media">
          <div class="media-left">
            <figure class="image is-48x48">
              <img
                src="https://bulma.io/images/placeholders/96x96.png"
                alt="Placeholder image"
              />
            </figure>
          </div>
          <div class="media-content">
            <p class="title is-4">
              {{ mockAddok.features[0].properties.denominationunitelegale }}
              | {{ mockAddok.features[0].properties.enseigne1etablissement }}
            </p>
            <p class="subtitle is-6">
              {{ mockAddok.features[0].properties.context }}
            </p>
            <p class="title is-6">
              {{ mockAddok.features[0].properties.longitude }} ,
              {{ mockAddok.features[0].properties.latitude }}
            </p>
          </div>
        </div>

        <div class="content">
          NAF:
          {{
            mockAddok.features[0].properties
              .nomenclatureactiviteprincipaleunitelegale
          }}
          siret : {{ mockAddok.features[0].properties.siret }}
          <br />

          activité principale
          {{
            mockAddok.features[0].properties.activiteprincipaleetablissement
          }}, source {{ mockAddok.features[0].properties.source }},
          <time datetime="2016-1-1">
            enregistré le
            {{ mockAddok.features[0].properties.anneeeffectifsetablissement }},
            entreprise créé le {{ mockAddok.features[0].properties.datedebut }},
            dernirèe mise à jour
            {{ mockAddok.features[0].properties.updated_at }}
          </time>
        </div>
      </div>
    </section>
    <section v-if="xml" class="edit">
      <b-field label="Nom">
        <b-input
          v-model="xml.tags.name"
          placeholder="le nom de votre commerce"
          icon="pencil"
        ></b-input>
      </b-field>
      <b-field label="Site web">
        <b-input
          v-model="xml.tags.website"
          placeholder="www.monsite.com"
          icon="planet"
        ></b-input>
      </b-field>
      <b-field label="email officiel">
        <b-input
          v-model="xml.tags.email"
          placeholder="contact@monsite.com"
          icon="enveloppe"
        ></b-input>
      </b-field>
      <b-field label="Tel">
        <b-input
          v-model="xml.tags.phone"
          placeholder="012345"
          icon="planet"
          type="tel"
        ></b-input>
      </b-field>
      <b-field label="Description de votre activité">
        <b-input
          v-model="xml.tags.description"
          placeholder="description de votre activité"
          icon="planet"
          type="tel"
        ></b-input>
      </b-field>
      <b-field>
        <b-switch v-model="xml.tags.takeaway"> Vente à emporter</b-switch>
        <b-switch v-model="xml.tags['parking:velo']"> Parking vélo</b-switch>
        <b-switch v-model="xml.tags['webaccess']"> Accès Internet</b-switch>
        <b-switch v-model="xml.tags['elecborne']">
          borne de recharge électrique sur parking
        </b-switch>
        <b-switch v-model="xml.tags['access:public']">
          Accès autorisé au public
        </b-switch>
      </b-field>

      <h2 class="title is-2">Horaires d'ouverture</h2>
      <div class="padded">
        {{ xml.tags.opening_hours }}
      </div>

      <button class="btn button has-background-success">Enregistrer</button>
    </section>
  </main>
</template>

<script>
import debounce from 'lodash/debounce'
import * as resultsAddok from '../mocks/addok'
import * as resultsEntreprise from '../mocks/entreprise'
import * as nodeInfo from '../mocks/osm_larome'

export default {
  data() {
    
    return {
      data: [],
      //xml: null, 
      xml: nodeInfo.default.elements[1],
      mockEntreprise: null, //resultsEntreprise.default,
      mockAddok: null, //resultsAddok.default,
      selected: null,
      isFetching: false,
      coord: [45.902023,6.1207122], // Annecy ! repositionne la carte à chaque changement d'onglet
    }
  },
  mounted() {
    //this.getAsyncData('larome')
  },
  methods: {
    // You have to install and import debounce to use it,
    // it's not mandatory though.
    getAsyncData: debounce(function (name) {
      if (!name.length) {
        this.data = []
      }
      this.isFetching = true
      this.$axios
        //.get(`https://demo.addok.xyz/search?&type=poi&q=${name}`) // on filtre les POI ?!
        .get(`https://demo.addok.xyz/search?q=${name}`) // on filtre les POI ?!
        .then(({ data }) => {
          console.log('data', data)
          this.data = []
          data.features.forEach((item) => this.data.push(item))
        })
        .catch((error) => {
          this.data = []
          throw error
        })
        .finally(() => {
          this.isFetching = false
        })
    }, 500),

    fetchOSM: function (event) {
      console.log(event)
      this.selected = event
      this.coord[0] = event.geometry.coordinates[1]
      this.coord[1] = event.geometry.coordinates[0]
  
      // On déplace la carte
      const map = this.$refs.myMap
      //map.setCenter(this.coord)
      
      map.mapObject.setView(this.coord,18) // fonctionne
      // map.mapObject.panTo([10,10]) fonctionne aussi

      const marker = this.$refs.myMarker
      marker.setLatLng(this.coord)

      // test : change le nom
      this.xml.tags.name = event.properties.name
      this.xml.tags.website = event.properties.id.replace("https://osm.org/","")
      this.xml.tags.email = event.properties.type
    }
  },
}
</script>
