<template>
  <div class="auto">
    <label>{{f_user_name}}足迹</label>
    <button type="button" class="btn btn-default" @click="this.$back('asd')">&lt;&lt;</button>
    <div>
      <label>开始时间：</label>
      <input type="datetime-local" v-model="f_datetime_from"></input>
    </div>
    <div>
      <label>结束时间：</label>
      <input type="datetime-local" v-model="f_datetime_to"></input>
      <button type="button" class="btn btn-default" @click="refresh">刷新</button>
    </div>
    <div :style="mapStyle">
      <div id="allmap" :style="mapStyle" class="auto"></div>
    </div>
  </div>
</template>

<script>
import * as Util from '../Util'
import co from 'co'
import Vue from 'vue'
// because of some weired behavior of baidu map, logic cant be extracted out and factored into a map component
let fetchPrints = function * (self) {
    let result = yield self.$post('rs/sql/获取足迹?pageNo=1&pageSize=9999', {
        data: {
            f_userinfoid: self.f_userinfoid,
            startDate: self.f_datetime_from.replace('T', ' '),
            endDate: self.f_datetime_to.replace('T', ' ')
        }
    }, {
        resolveMsg: null,
        rejectMsg: '提取地图信息出错'
    })
    self.$set('markers', result.data)
    self.render()
}

export default {
  title: '足迹图',
  props: ['f_userinfoid', 'f_user_name'],
  data () {
    return {
      markers : [],
      f_datetime_from: Util.format3339TimeString(new Date(Date.now() - 24 * 3600 * 1000)),
      f_datetime_to: Util.to3339TimeString(),
      mapStyle: {
        width: (this.$parent.$el.clientWidth -30) + 'px',
        height: (this.$parent.$el.clientHeight - 110) + 'px'
      }
    }
  },
  ready () {
    console.log('map loaded:' + Vue.mapLoaded)
    if(Vue.mapLoaded) {
      this.refresh()
    } else {
      window.__mapCallback__ = this.mapCallback
      let element = document.createElement('script')
      element.setAttribute("type","text/javascript")
      element.setAttribute("src", 'http://api.map.baidu.com/api?v=2.0&ak=CAErfbr2DatVA6rHdoUELPynrdPh9A6S&callback=__mapCallback__')
      document.body.appendChild(element)
    }
  },
  methods: {
    verify () {
      let HostApp = HostApp || window
      let interval = Util.parse3339String(this.f_datetime_to).getTime() - Util.parse3339String(this.f_datetime_from).getTime()
      if (interval > 24 * 3600 * 1000) {
        HostApp.alert('时间段不能超过24小时，否则地图渲染过慢!')
        return false
      } else if (interval < 0){
        HostApp.alert('结束时间不能小于开始时间！')
        return false
      } else {
        return true
      }
    },
    refresh () {
      if(!this.verify())
        return
      let gen = fetchPrints(this)
      co(gen)
    },
    mapCallback () {
      console.log('map callback')
      Vue.mapLoaded = true
      console.log('map loaded:' + Vue.mapLoaded)
      this.refresh()
    },
    patch () {
      let a = document.getElementById('allmap').getElementsByClassName('BMap_cpyCtrl BMap_noprint anchorBL')
      if(a.length != 0) {
        a[0].style.height = 'auto'
      } else {
        window.setTimeout(this.patch, 500)
      }
    },
    render () {
      window.map = new BMap.Map("allmap")
      window.map.clearOverlays();
      window.map.addControl(new BMap.NavigationControl())
      let points = []
      this.markers.forEach(function(pos) {
        var point = new BMap.Point(pos.longitude,pos.latitude)
        console.log(pos.longitude + ',' + pos.latitude)
        points.push(point)
      	var marker = new BMap.Marker(point)  // 创建标注
      	window.map.addOverlay(marker)             // 将标注添加到地图中
      	var infoWindow = new BMap.InfoWindow(pos.hint)  // 创建信息窗口对象
      	marker.addEventListener("click", function(){
          console.log(point.lng + ',' + point.lat)
      		window.map.openInfoWindow(infoWindow, point) //开启信息窗口
      	})
      })
      if(points.length >0) {
        var polyline=new BMap.Polyline(points, {strokeColor:"blue",strokeWeight:6,strokeOpacity:0.5})
        window.map.addOverlay(polyline)             // 将标注添加到地图中
      }
      if(this.markers.length == 0)
        window.map.centerAndZoom(new BMap.Point(116.404, 39.915), 11)
      else
        window.map.centerAndZoom(new BMap.Point(this.markers[0].longitude, this.markers[0].latitude), 11)
      this.patch()
    }
  }
}
</script>
