<template>
  <div class="map-select">
    <div @click="()=> showAmapDialog = true">
      <el-input
        readonly
        v-model="address"
        :placeholder="placeholder"
      ></el-input>
    </div>

    <el-dialog
      title="选择地图位置"
      width="800px"
      :visible.sync="showAmapDialog"
    >
      <div
        v-if="showAmapDialog"
        class="map-box"
      >
        <AMapComponent
          :config="config"
          :amap-key="amapKey"
          @change="handleLocationChange"
        />
      </div>
      <div class="dialog-footer text-r">
        <el-button @click="onCancel">取消</el-button>
        <el-button
          type="primary"
          @click="saveLocation"
        >确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import MapComponent from './MapComponent.vue'


export default {
  name: "MapSelect",
  components: {
    MapComponent
  },
  props: {
    amapKey: {
      type: String,
      required: true
    },
    placeholder: {
      type: String,
      default: function () {
        return "请选择位置"
      }
    },
    value: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data() {
    return {
      showAmapDialog: false,
      config: {
        id: new Date().getTime(),
        width: 720,
        height: 500,
        zoom: 20,
        lng: this.value.lng,
        lat: this.value.lat,
        liteStyle: false
      },
      currentLocation: {
        lng: this.value.lng,
        lat: this.value.lat,
        address: this.value.address
      },
      tempLocation: undefined
    }
  },

  watch: {
    value: {
      handler(newVal) {
        this.currentLocation = {
          lng: newVal.lng,
          lat: newVal.lat,
          address: newVal.address
        }
        this.config = {
          ...this.config,
          lng: newVal.lng,
          lat: newVal.lat,
        }
      },
      deep: true
    }
  },

  computed: {
    address: {
      get() {
        return this.currentLocation.address || ''
      },
      set(val) {
        this.currentLocation = val
      }
    }
  },

  methods: {
    saveLocation() {
      if (this.tempLocation) {
        this.currentLocation = this.tempLocation
        this.$emit('update:value', this.currentLocation)
        this.showAmapDialog = false
      }else{
         this.$message('请选择地址！')
      }
      this.tempLocation = undefined
    },

    onCancel() {
      this.showAmapDialog = false
      this.tempLocation = undefined
    },

    handleLocationChange(location) {
      this.tempLocation = location
    }
  }
}
</script>

<style lang='scss' scoped>
.map-select{
    cursor: pointer;
    .map-box {
      margin-bottom: 16px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
}

</style>