<template>
  <div>
    <avue-map v-model="map" placeholder="请选择地图"></avue-map>
    <template v-if="typeof resultFormat === 'string'">
      <el-input size="small" :prop="value" @input="e => $emit('input',e)"></el-input>
    </template>
    <template v-else-if="resultFormat instanceof Array">
      <div class="loc-editor">
        <el-input :placeholder="item" v-for="(item, index) in resultFormat" size="small" :value="map[item]" @input="e => inputHandle(e,item)">
        </el-input>
      </div>
    </template>
    <template v-else>
      <el-input :placeholder="key" v-for="(value, key) of resultFormat" size="small" :value="map[key]" @input="e => inputHandle(e,key)">
      </el-input>
    </template>
  </div>
</template>

<script>
export default {
  props: {
    value: [String, Object, Array, Number, Boolean],
    resultFormat: {
      type: [String, Object, Array],
      default: () => ['longitude','latitude'] //latitude纬度，longitude经度,formattedAddress地址
    }
  },
  data() {
    return {
      map: {},
    }
  },
  methods: {
    inputHandle (e, key) {
      this.map[key] = e;
      this.map = Object.assign({}, this.map)
    }
  },
  computed: {},
  watch: {
    map(newVal) {
      if(!newVal) return
      let info = {
        ...newVal,
        latitude: newVal.location?.lat || newVal.latitude,
        longitude: newVal.location?.lng || newVal.longitude,
      }
      let res = ''
      if(typeof this.resultFormat === 'string') {
        res = info[this.resultFormat]
      }
      if(this.resultFormat instanceof Array) {
        res = this.resultFormat.map(i => info[i])?.toString()
      }
      if(typeof this.resultFormat === 'object' && (!this.resultFormat instanceof Array)) {
        let obj = {}
        for(let key in this.resultFormat) {
          obj[key] = info[this.resultFormat[key]]
        }
        res = obj;
      }
      console.log(res)
      this.$emit('input', res)
    },
    value: {
      handler: function(newVal) {
        if (newVal) {
          if(typeof this.resultFormat === 'string') {
            this.map[this.resultFormat] = newVal
          }
          if(this.resultFormat instanceof Array && newVal) {
            let valArr = newVal.split(',')
            this.resultFormat.forEach((i,index) => {
              this.map[i] = Number(valArr[index])
            })
          }
          if(typeof this.resultFormat === 'object' && (!this.resultFormat instanceof Array)) {
            for(let key in this.resultFormat) {
              this.map[key] = newVal[key]
            }
          }

          console.log(this.map)
        }
      },
      immediate: true
    }
  }
}
</script>

<style scoped lang="scss">
.loc-editor {
  display: flex;
  margin-top: 4px;

  & > ::v-deep.el-input {
    margin-left: 4px;
  }
  & > ::v-deep.el-input:first-child {
    margin-left: 0;
  }
}
</style>
