<template>
  <el-dialog :title="title" :visible="show" width="70%" top="2vh" @close="close" :append-to-body="true">
    <el-row v-if="selected != null" style="margin-bottom: 0.5em">
      当前选择： {{selected.address}}, {{selected.lng}}, {{selected.lat}}
    </el-row>

    <location-map
      v-if="show"
      ref="map"
      height="800px"
      @select-changed="onSelectChange"
      @map-geo="onMapGeo"
      :init-lat="initLat"
      :init-lng="initLng"
    />

    <template #footer>
      <el-button type="primary" @click="onSubmit()">确定</el-button>
      <el-button @click="onCancel()">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import LocationMap from '@/components/Map/location/LocationMap.vue'

export default {
  name: "PlaceSearchDialog",
  components: { LocationMap },
  props: {
    title: {
      type: String,
      default: '选择定位'
    },
    show: {
      type: Boolean,
      default: false,
    },
    initLng: {
      type: Number,
      default: 120.250452
    },
    initLat: {
      type: Number,
      default: 27.101745
    },
  },
  data() {
    return {
      selected: null,
    }
  },
  methods: {
    onMapGeo(data, lat, lng) {
      console.log("onMapGeo", data)
      let component = data.regeocode.addressComponent;
      this.selected = {
        address: data.regeocode.formattedAddress,
        lng: lat,
        lat: lng,
        province: component.province,
        city: component.city === '' ? '市辖区' : component.city,
        county: component.district,
        name: component.street + component.streetNumber
      }
    },
    onSelectChange(addr) {
      console.log("onSelectChange", addr)
      let data = addr.selected.data;
      this.selected = {
        address: data.pname + (data.cityname === data.pname ? '' : data.cityname) + data.adname + data.address + data.name,
        lng: data.location.lng,
        lat: data.location.lat,
        province: data.pname,
        city: data.cityname === data.pname ? '市辖区' : data.cityname,
        county: data.adname,
        name: data.address + data.name,
      }
    },
    // 确定
    onSubmit() {
      this.$emit('submit', this.selected);
      this.close();
    },
    // 取消
    onCancel() {
      this.close();
    },
    // 关闭弹窗
    close() {
      this.selected = null;
      this.$emit('update:show', false);
    },
  }
}
</script>

<style scoped lang="scss">

</style>
