<template>
  <div class="app-content">
    <el-input
      v-model="addressLocation"
      @input="searchValue"
      v-if="showInput"
      :placeholder="placeholder || '如：北京市延庆区延庆镇莲花池村前街50夕阳红养老院'"
    ></el-input>
    <div class="mapDiv" id="mapDiv" style="width: 100%;height: 300px;"></div>
  </div>
</template>

<script>
import {debounce} from '@/util/util';

const script = document.createElement('script')
let origin = ''
if (window.location.origin.search('localhost') > 0) {
  origin = 'http://10.165.0.173'
} else {
  origin = window.location.origin
}
script.src = origin + '/tianditu/api?v=4.0&tk=' + process.env.VUE_APP_TIANDITU_APIKEY
script.onload = () => console.warn('-----------天地图加载完成-----------')
document.head.appendChild(script)
let Tmap = null;
export default {
  data() {
    return {
      options: [],
      addressLocation: '',
      baseUrl: '',
      isInput: true,
    }
  },
  props: {
    placeholder: String,
    latitude: {
      required: false,
      // default: 31.126855,
    },
    longitude: {
      required: false,
      // default: 104.397894,
    },
    zoom: {
      type: Number,
      required: false,
      default: 10,
    },
    maxZoom: {
      type: Number,
      required: false,
      default: 20,
    },
    minZoom: {
      type: Number,
      required: false,
      default: 0,
    },
    ScaleZoom: {
      type: Boolean,
      required: false,
      default: false,
    },
    MapUrl: { // 瓦片地图URL
      type: String,
      required: false,
      default: process.env.VUE_APP_SUPPER_MAP,
    },
    flagTip: {
      type: Boolean,
      required: false,
      default: false,
    },
    open: {
      type: Boolean,
      required: false,
      default: false,
    },
    isCanEdit: {
      type: Boolean,
      required: false,
      default: false,
    },
    address: {
      required: false,
      default: '',
    },
    type: {
      required: false,
      default: 'custom',
    }
  },
  computed: {
    showInput() {
      if (this.type === 'view' || this.type === 'select') {
        return false
      }
      if (this.type === 'add') {
        this.addressLocation = ''
      }
      return true
    }
  },
  watch: {
    address() {
      if (!this.isInput) return;
      console.log(2, this.type, this.address, this.longitude, this.latitude)
      if (this.longitude > 0 && this.latitude > 0) {
        this.addressLocation = this.address
        this.createTmap(this.longitude, this.latitude)
      } else {
        this.getlocation()
      }
    }
  },
  created() {
    console.log(1, this.type, this.address, this.longitude, this.latitude)
    this.baseUrl = origin;
    T.Protocol.value = this.baseUrl + '/'
  },
  mounted() {
    if (this.longitude > 0 && this.latitude > 0) {
      this.addressLocation = this.address
      this.createTmap(this.longitude, this.latitude)
    } else {
      this.getlocation()
    }
  },
  methods: {
    geolocation() {
    },
    getlocation() {
      const _this = this
      // 31.12494749933168, 经度： 104.40371173671055
      // 内网环境无法获取位置
      _this.createTmap(104.40371173671055, 31.12494749933168)
      // if (navigator.geolocation) {
      //   navigator.geolocation.getCurrentPosition(function (position) {
      //     let latitude = position.coords.latitude;
      //     let longitude = position.coords.longitude;
      //     _this.createTmap(longitude, latitude)
      //   }, function (error) {
      //
      //     // _this.$message.info('无法获取地理位置，请授权页面定位权限')
      //     console.warn('无法获取地理位置，请授权页面定位权限' + error)
      //   });
      // } else {
      //   _this.$message.info('浏览器不支持地理定位')
      // }
    },
    searchValue: debounce(function (val) {
      if (!this.isInput) {
        this.isInput = true
        return
      }
      if (this.type !== 'view') {
        this.$emit('input', val)
      }
      let params = {
        ds: {
          keyWord: val,
        },
        tk: process.env.VUE_APP_TIANDITU_APIKEY
      }
      const _this = this
      axios({
        method: 'get',
        url: this.baseUrl + '/tianditu/geocoder',
        params: params,
      }).then(({data}) => {
        if (data.status === '0') {
          const {keyWord, lon, lat, level} = data.location
          if (!Tmap) {
            this.createTmap(lon, lat)
          } else {
            Tmap.centerAndZoom(new T.LngLat(lon, lat), 15);
            this.setIcon(lon, lat);
            this.$emit('addAddress', {
              address: this.addressLocation,
              lng: lon,
              lat: lat
            })
          }
        }
      }).catch((err) => {
        _this.$message.info('无法获取该位置地理坐标')
      })
    }, 1000),
    createTmap(lng, lat) {
      const _this = this
      this.$nextTick(() => {
        console.log(Tmap)
        if (!Tmap) {
          Tmap = new T.Map('mapDiv', {
            projection: 'EPSG:4326',
            minZoom: this.minZoom,
            maxZoom: this.maxZoom
          });
          Tmap.addEventListener('click', (e) => {
            _this.nextPoint(e.lnglat)
          });
        }
        Tmap.centerAndZoom(new T.LngLat(lng, lat), 15);
        this.setIcon(lng, lat);
      })
    },
    setIcon(lng, lat) {
      Tmap.clearOverLays()
      const icon = new T.Icon({
        iconUrl: '/img/point.png',
        iconSize: new T.Point(30, 30),
        iconAnchor: new T.Point(15, 30)
      });
      const marker = new T.Marker(new T.LngLat(lng, lat), {
        icon
      });
      Tmap.addOverLay(marker);
    },
    nextPoint(lnglat) {
      var that = this;
      let params = {
        postStr: JSON.stringify({
          lon: lnglat.lng,
          lat: lnglat.lat,
          ver: 1,
        }),
        type: 'geocode',
        tk: process.env.VUE_APP_TIANDITU_APIKEY
      }
      axios({
        method: 'get',
        url: this.baseUrl + '/tianditu/geocoder',
        params: params,
      }).then((res) => {
        if (res.data.status === '0') {
          that.setIcon(lnglat.lng, lnglat.lat)
          const info = that.formatterAdressLocation(res.data.result, 1)
          this.isInput = false
          this.$emit('addAddress', {
            address: info.address,
            lng: info.location.lon,
            lat: info.location.lat
          })
          this.addressLocation = info.address
          this.$nextTick(() => {
            this.isInput = true
          })
        }
      })
    },
    formatterAdressLocation(obj, type) {
      switch (type) {
        case 1:
          return {
            address: obj.formatted_address,
            name: '',
            location: obj.location,
            infomation: obj.addressComponent
          }
          break;
        case 2:
          const [lon, lat] = obj.lonlat.split(',')
          return {
            address: obj.address,
            name: obj.name,
            location: {
              lon,
              lat
            },
            infomation: obj
          }
          break
        case 3:
          return {
            address: obj.location.keyWord,
            name: '',
            location: {
              lon: obj.location.lon,
              lat: obj.location.lat,
            },
            infomation: obj.location
          }
        default:
          break;
      }
    }
  }
}
</script>

<style scoped>
.mapDiv {
  width: 100%;
  height: fit-content;
}
</style>
