import LTBaseObject from './KBaseObject'
import TileLayer from 'ol/layer/Tile'
import sourceWMTS from 'ol/source/WMTS';
import WMTSTileGrid from 'ol/tilegrid/WMTS';
import * as olExtent from 'ol/extent';
/**
 * @description KMap.WMTSLayer WMS图层类
*/
class WMTSLayer extends LTBaseObject{
	/**
	 * @description 构造函数
	 * @param {String} url wms图层服务地址
	 * @param {LTMap.Map} [mapInstance=null] map对象，单地图的时候可不传，多地图时候需要传
	 * @memberof WMTSLayer
	 */
	constructor(wmtsData,projection,mapInstance = null){
		super(mapInstance)
		const vm = this;
		vm.initLayer(wmtsData,projection)
	}

	/**
		* @description 初始化ImageLayer
		* @memberof WMTSLayer
		*/
	initLayer(wmtsData,projection){
		const vm = this;
		let projectionExtent = projection.getExtent();
    let size = olExtent.getWidth(projectionExtent) / 256;
    let resolutions = new Array(19);
    let matrixIds = new Array(19);
    for (var z = 1; z < 19; ++z) {
        // generate resolutions and matrixIds arrays for this WMTS
        resolutions[z] = size / Math.pow(2, z);
        matrixIds[z] = z;
    }

    let source = new sourceWMTS({
        url: wmtsData.url,
        layer: wmtsData.layer,
        matrixSet: wmtsData.matrixSet,
        format: 'tiles',
        projection: projection,
		crossOrigin:'anonymous',
        tileGrid: new WMTSTileGrid({
            origin: olExtent.getTopLeft(projectionExtent),
            resolutions: resolutions,
            matrixIds: matrixIds
        }),
        style: 'default',
        wrapX: true
    })
    let layer = new TileLayer({
        zIndex:wmtsData.zIndex,
        source: source,
        // visible: false,
    });
    layer.id = wmtsData.layer+"_"+wmtsData.matrixSet;
		vm.layer = layer;
		vm.source = source;
		vm.map.addLayer(vm.layer)
    return layer;
    //地图加载WMS图层
	}

  /**
	* @description 添加WMS图层到地图
	* @memberof WMTSLayer
	*/
  add(){
		const vm = this
		if(!vm.state) {
			vm.map.addLayer(vm.layer)
			vm.state = true
		}
	}

	/**
	 * @description 从当前地图中移除WMS图层
	 * @memberof WMTSLayer
	 */
	remove() {
		const vm = this
		if(vm.state) {
			vm.map.removeLayer(vm.layer)
			vm.state = false
		}
	}

	/**
	 * @description 显示WMS图层数据
	 * @memberof WMTSLayer
	 */
	show(){
		const vm = this
		if(vm.state) {
			vm.layer.setVisible(true)
		}
	}

	/**
	 * @description 隐藏WMS图层数据
	 * @memberof WMTSLayer
	 */
	hide(){
		const vm = this
		if(vm.state) {
			vm.layer.setVisible(false)
		}
	}
}
export default WMTSLayer
