<script>
import commonMixin from '@/base/mixins/common.js'
import OverviewMap from '@/controls/OverviewMap.js'
export default {
  name: 'bs-wtmslayer',
  render () { },
  mixins: [commonMixin('layer')],
  props: {
    showOverView: {
      type: Boolean,
      default: true
    }
  },
  watch: {
  },
  methods: {
    load () {
      const { ol, $rootComponent, showOverView, map } = this
      var layer = new ol.layer.Group({layers: [this.getTdtLayer('img_c'), this.getTdtLayer('cia_c')]})
      this.originInstance = layer
      map.addLayer(layer)
      if (showOverView) {
        const overview = new OverviewMap({
          collapsible: true,
          collapsed: false,
          view: new ol.View({
            projection: $rootComponent.projection,
            zoomFactor: $rootComponent.zoomFactor,
            center: $rootComponent.center,
            zoom: 2,
            resolutions: $rootComponent.resolutions
          })
        })
        $rootComponent.addControl(overview)
      }
    },
    getTdtLayer(lyr) {
      const {ol, $rootComponent} = this
      var url = 'http://t4.tianditu.com/DataServer?T=' + lyr + '&x={x}&Y={y}&L={z}'
      var projectionExtent = [ -180, -90, 180, 90 ]
      var maxResolution = (ol.extent.getWidth(projectionExtent) / (256 * 2))
      var resolutions = new Array(19)
      for (var z = 0; z < 19; ++z) {
        resolutions[z] = maxResolution / Math.pow(2, z)
      }
      var tileOrigin = ol.extent.getTopLeft(projectionExtent)
      var layer = new ol.layer.Tile({
        extent: projectionExtent,
        source: new ol.source.TileImage({
          crossOrigin: 'anonymous',
          tileUrlFunction: function(tileCoord) {
            var z = tileCoord[0] + 1
            var x = tileCoord[1]
            var y = -tileCoord[2] - 1
            var n = Math.pow(2, z + 1)
            x = x % n
            if (x * n < 0) {
              x = x + n
            }
            return url.replace('{z}', z.toString())
                                .replace('{y}', y.toString())
                                .replace('{x}', x.toString())
          },
          projection: $rootComponent.projection,
          tileGrid: new ol.tilegrid.TileGrid({
            origin: tileOrigin,
            resolutions: resolutions,
            tileSize: 256
          })
        })
      })
      layer.set('title', 'tdtMap')
      return layer
    }
  }
}
</script>
