<template>
  <div class="column">
    <div class="row items-center">
      <kyb-area
        v-show="isEditInner"
        :showonly="showonly"
        v-model="areaCode"
        class="q-pa-xs"
        @all-value="areaAllValue"
      />
      <kyb-input
        v-if="isEditInner"
        ref="addressName"
        v-model="name"
        completion
        outlined
        dense
        module="common"
        entity="Address"
        :readonly="areaNotOk"
        :showonly="showonly"
        :class="areaNotOk?'disabled':''"
        label="输入详细地址"
        :items="addressList"
        :queryParam="{_areaCode:areaCode}"
        class="q-pa-xs"
        @blur="blurInput"
      ></kyb-input>
      <kyb-btn
        v-if="isEditInner&&!showonly"
        icon="check"
        dense
        color="primary"
        class="q-ma-xs q-pr-sm"
        label="确定"
        :disabled="areaNotOk||!(!!name&&name.length>0)"
        :click-action="saveAddress"
      >
        <q-tooltip>确认填写的地址</q-tooltip>
      </kyb-btn>
      <div class="q-pa-md" v-text="fullName" v-if="!isEditInner"></div>
      <q-btn
        v-if="!isEditInner&&!readonly&&!showonly"
        icon="edit"
        dense
        flat
        color="primary"
        class="q-mt-sm q-mb-sm"
        @click="isEditInner=!isEditInner"
      >
        <q-tooltip>修改地址</q-tooltip>
      </q-btn>
      <kyb-btn
        v-if="!showonly||name"
        icon="place"
        flat
        dense
        class="q-ma-xs"
        color="grey-7"
        :disabled="areaNotOk||!(!!name&&name.length>0)"
        @click="showMap=!showMap"
      ></kyb-btn>
      <!-- <q-btn flat dense round icon="cancel" color="grey-7" @click.stop="clear" /> -->
    </div>
    <baidu-map
      v-if="showMap"
      class="baidu-map q-ma-xs rounded-borders no-scroll bordered"
      :style="mapStyle"
      :center="center"
      :zoom="zoom"
      @ready="handler"
      :ak="baiduKey"
      :scroll-wheel-zoom="true"
    >
      <bm-scale anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-scale>
      <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
      <bm-marker
        :position="markerPoint"
        :dragging="true"
        @click="infoWindowOpen"
        animation="BMAP_ANIMATION_BOUNCE"
      >
        <bm-info-window
          :show="show"
          @close="infoWindowClose"
          @open="infoWindowOpen"
          v-text="fullName"
        ></bm-info-window>
      </bm-marker>
    </baidu-map>
  </div>
</template>
<script>
// import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
import {
  BaiduMap,
  BmScale,
  BmNavigation,
  BmMarker,
  BmInfoWindow
} from 'vue-baidu-map'
const baiduKey = '4FdND1DGrcxs7vIe5B4SudF1'
export default {
  name: 'kyb-address',
  model: {
    prop: 'value',
    event: 'input'
  },
  props: {
    value: String,
    isEdit: Boolean,
    readonly: Boolean,
    showonly: Boolean,
    mapStyle: {
      type: Object,
      default: () => {
        return { height: '200px' }
      }
    }
  },
  components: {
    BaiduMap,
    BmScale,
    BmNavigation,
    BmMarker,
    BmInfoWindow
  },
  data() {
    return {
      valueInner: this.value,
      name: '',
      isEditInner: this.isEdit,
      areaCode: null,
      areaValue: [],
      center: { lng: 0, lat: 0 },
      zoom: 15,
      markerPoint: { lng: 116.404, lat: 39.915 },
      show: false,
      showMap: false,
      baiduKey: baiduKey,
      addressList: []
    }
  },
  computed: {
    areaNotOk() {
      let notOk = true
      if (this.areaValue) {
        notOk =
          this.areaValue.filter(v => v._id && v._id.length > 0).length !== 3
      }
      return notOk
    },
    fullName() {
      return [...this.areaValue, { name: this.name }]
        .map(v => v.name)
        .join(', ')
    }
  },
  watch: {
    value(old) {
      this.valueInner = old
      this.fixData()
    },
    isEdit(old) {
      this.isEditInner = old
      this.fixData()
    }
  },
  created() {
    this.fixData()
  },
  methods: {
    async fixData() {
      if (this.valueInner && this.valueInner.length) {
        let re = await this.$axios.get(
          `/common/Address/show?_id=${this.valueInner}`
        )
        let obj = re.data
        this.name = obj.name
        this.areaCode = obj.areaCode
        this.markerPoint = this.center = { lng: obj.lon, lat: obj.lat }
        this.versionNum = obj.versionNum
      } else {
        this.isEditInner = true
      }
      if (this.readonly) {
        this.isEditInner = false
      }
    },
    async handler({ BMap, map }) {
      console.log(BMap, map)
      await this.getAddressMap()
      this.zoom = 15
    },
    setByIp() {
      this.$jsonp('https://api.map.baidu.com/location/ip', {
        ak: this.baiduKey,
        coor: 'bd09ll'
      }).then(json => {
        console.log(json)
        if (json.content && json.content.point) {
          this.center.lng = json.content.point.x
          this.center.lat = json.content.point.y
        } else {
          // 北京
          this.center.lng = 116.404
          this.center.lat = 39.915
        }
      })
    },
    async saveAddress() {
      if (!this.areaNotOk && this.name && this.name.length) {
        await this.getAddressMap()
        let data = {
          _id: this.valueInner ? this.valueInner : ''.genUUID(),
          name: this.name,
          areaCode: this.areaCode,
          lon: this.center.lng,
          lat: this.center.lat,
          versionNum: this.versionNum
        }
        let re = await this.$axios.post(`/common/Address/save`, data)
        this.versionNum = re.data.versionNum
        this.$q.showNotifi('保存地址成功！')
        this.isEditInner = false
        this.$emit('input', data._id)
      }
    },
    infoWindowClose() {
      this.show = false
    },
    infoWindowOpen() {
      this.show = true
    },

    selectedAddress(v) {
      console.log(v)
    },
    createValue(val, done) {
      console.log(val)
      done(val)
    },
    getAddressMap() {
      return new Promise((resolve, reject) => {
        let url = `http://api.map.baidu.com/geocoding/v3/?address=${this.areaValue
          .map(v => v.name)
          .join('')}${this.name}&output=json&ak=${this.baiduKey}`
        this.$jsonp(url).then(json => {
          console.log('address', json)
          if (json.result && json.result.location) {
            this.center = json.result.location
            this.markerPoint = json.result.location
            resolve(json.result.location)
          } else {
            reject(json)
          }
        })
      })
    },
    async blurInput($event) {
      console.log('---blur', this.name)
      await this.getAddressMap()
    },
    areaAllValue($event) {
      this.areaValue = $event
    }
  }
}
</script>
