<template>
  <div class="withinLine">
    <el-button type="primary" size="mini" @click="open">地理定位</el-button>
    <el-dialog
      title="地理定位"
      :visible.sync="dialogVisible"
      :append-to-body="true"
      width="1000px"
      :before-close="handleClose"
    >
      <template v-if="dialogVisible">
        <div>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="24" :lg="24">
              <div class="teshubuju">
                <el-autocomplete
                  v-model="queryString"
                  style="width: 100%; margin-right: 10px"
                  placeholder="请输入内容"
                  :fetch-suggestions="querySearchAsync"
                  @select="handleSelect"
                />
                <el-button
                  size="mini"
                  type="primary"
                  @click="
                    () => {
                      querySearchAsync(queryString)
                    }
                  "
                >查询</el-button>
              </div>
            </el-col>
          </el-row>
        </div>
        <br>
        <div style="height: 60vh; position: relative">
          <zj-amap-polygon
            :markers="markers"
            :zoom="zoom"
            :isWheel="true"
            :center="center"
            :electronic-fence="false"
            @getGeocoder="getGeocoder"
          >
            <template #marker="{ marker }">
              <i class="el-icon-location-outline IP_font" />
              <div class="IP">
                <div>地址:{{ marker.name }}</div>
                <div>经度:{{ marker.center[0] }}</div>
                <div>维度:{{ marker.center[1] }}</div>
              </div>
            </template>
          </zj-amap-polygon>
          <!-- 周边数据 -->
          <div class="zhoubian">
            <div v-for="(item, index) in mapzhoubian" :key="index" class="zhoubianItem" @click="zhoubiandw(item)">
              <div class="zhoubianItemview">
                <i class="el-icon-location-outline" />
                <div>
                  <div style="font-weight: bold; margin-bottom: 8px; box-sizing: border-box; padding: 0px 5px">
                    {{ item.pname }}{{ item.cityname }}{{ item.adname }}{{ item.address }}
                  </div>
                  <div>地址：{{ item.name }}</div>
                </div>
                <div>
                  <img
                    v-for="(p, i) in item.photos || []"
                    v-if="i === 0"
                    :key="i"
                    :src="seturl(p.url)"
                    alt=""
                    srcset=""
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="handleClose">取 消</el-button>
          <el-button size="mini" type="primary" @click="sub">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getLocation, getAddress, supervisorChangeList, axiosMapZb } from '@/utils/lbs'
export default {
  props: { formData: { type: Object, default: () => ({}) }},
  data() {
    return {
      dialogVisible: false,
      loading: false,
      center: [113.36242, 23.1368425],
      zoom: 16.7,
      markers: [],
      mapSearchList: [],
      mapzhoubian: [],
      queryString: ''
    }
  },
  watch: {
    'formData.positionAddress'() {
      if (this.markers[0] && this.markers[0].name !== this.formData.positionAddress) {
        Object.assign(this.$data, this.$options.data())
      }
    }
  },
  methods: {
    seturl(url) {
      if (~url.indexOf('https://')) {
        return url
      } else {
        return url.replace('http://', 'https://')
      }
    },
    async open() {
      this.dialogVisible = true
      if (this.formData.lng && this.formData.lat && this.formData.positionAddress) {
        this.changeSearchMapFn(`${this.formData.lng}//${this.formData.lat}//${this.formData.positionAddress}`)
      } else {
        var str = ''
        if (!~(this.formData.positionAddress || '').indexOf(this.formData.province)) {
          str += this.formData.province || ''
        }
        if (!~(this.formData.positionAddress || '').indexOf(this.formData.city)) {
          str += this.formData.city || ''
        }
        if (!~(this.formData.positionAddress || '').indexOf(this.formData.area)) {
          str += this.formData.area || ''
        }
        if (!~(this.formData.positionAddress || '').indexOf(this.formData.street)) {
          str += this.formData.street || ''
        }
        str += this.formData.positionAddress || ''
        await this.remoteMethod(str)
        if (this.mapSearchList.length) {
          var v = this.mapSearchList[0]
          this.changeSearchMapFn(`${v.location.KL}//${v.location.kT}//${v.formattedAddress}`)
        }
      }
    },
    async querySearchAsync(queryString, cb) {
      if (!queryString) {
        cb && cb([])
      } else {
        var res = await supervisorChangeList(queryString)
        var list = res.tips.map(item => {
          return {
            ...item,
            value: item.district + item.name + item.address
          }
        })
        if (cb) {
          cb(list)
        } else if (list.length) {
          this.handleSelect(list[0])
        }
      }
    },
    async handleSelect(item) {
      this.center = [item.location.lng, item.location.lat]
      var data = await getAddress(this.center)
      this.markers = [
        {
          id: '',
          name: item.value,
          center: [item.location.lng, item.location.lat],
          data: {
            ...data,
            formattedAddress: item.value
          }
        }
      ]
      this.getAxiosMapZb(this.center)
    },
    zhoubiandw(item) {
      this.changeSearchMapFn(
        `${item.location.split(',').join('//')}//${
          item.pname + item.cityname + item.adname + item.name + item.address
        }`,
        false
      )
    },
    async changeSearchMapFn(value, bool = true) {
      const res = value.split('//')
      var data = await getAddress([Number(res[0]), Number(res[1])])
      this.queryString = res[2]
      this.markers = [
        {
          id: '',
          name: res[2],
          center: [res[0], res[1]],
          data
        }
      ]
      this.center = [res[0], res[1]]
      if (bool) {
        this.getAxiosMapZb(this.center)
      }
    },
    async remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        this.mapSearchList = await getLocation(query)
        this.loading = false
      } else {
        this.workerList = []
      }
    },
    async getAxiosMapZb(center = []) {
      axiosMapZb({
        location: center.join(',')
      })
        .then(res => {
          this.mapzhoubian = res.data.pois
        })
        .catch(err => {
          console.log(err)
        })
    },
    getGeocoder(data) {
      this.markers = [
        {
          id: '',
          name: data.formattedAddress,
          center: data.center,
          data
        }
      ]
      this.changeSearchMapFn(`${data.center[0]}//${data.center[1]}//${data.formattedAddress}`)
    },
    handleClose(done) {
      this.dialogVisible = false
    },
    sub() {
      this.$emit('selectPosi', this.markers[0])
      this.handleClose()
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .address_map {
  .el-dialog__body {
    padding: 0 20px;
  }
}
.IP_font {
  font-size: 28px;
  color: #409eff;
  position: absolute;
  left: -13px;
  top: -25px;
}
.IP {
  width: 15vw;
  background-color: #fff;
  padding: 6px 0 6px 6px;
}
.withinLine {
  display: inline-block;
  ::v-deep .el-button {
    margin-left: 10px;
  }
}
.teshubuju {
  display: flex;
}
.zhoubian {
  width: 320px;
  max-height: 100%;
  position: absolute;
  right: 0;
  top: 0;
  overflow-y: auto;
  .zhoubianItem {
    width: 100%;
    height: auto;
    box-sizing: border-box;
    padding: 16px 8px;
    border-bottom: 1px solid #aaa;
    background: #fff;
    cursor: pointer;
    .zhoubianItemview {
      display: flex;
      justify-content: space-between;
      img {
        width: 100px;
      }
    }
  }
}
</style>
