import Layer from 'ol/layer/VectorTile';
import Vector from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Source from 'ol/source/VectorTile';
import Common from './Common';
import MVT from 'ol/format/MVT';
import {createXYZ} from 'ol/tilegrid'
import KBaseObject from './KBaseObject'
/**
 * @description KMap.VectorLayer 矢量图层
 */
class VTLayer extends KBaseObject{
  /**
   * @param {string} name 图层名称
   * @param {string} zIndex 图层层级
  */
  constructor(url,options,zIndex,callback,mapInstance = null){
    super(mapInstance)
    const vm = this;
    let styleFunVT = options.styleFunVT;
    let styleFunV = options.styleFunV;
    let funThis = options.funThis;
    var source = new Source({
        format: new MVT(),
        url: url,
        tileGrid: createXYZ({
            tileSize: options.tileSize || 4096 // 瓦片大小
        }),
        tileLoadFunction:(tile, url)=>{
            tile.setLoader(function(extent, resolution, projection) {
                fetch(url).then(function(response) {
                    response.arrayBuffer().then(function(data) {
                        const format = tile.getFormat();
                        const features = format.readFeatures(data, {
                            extent: extent,
                            featureProjection: projection
                        });
                        tile.setFeatures(features);
                        callback(features);
                    });
                });
            });
        }
    });

    let ShowLevel = Common.ShowLevel
    let minZoom = ShowLevel[0]
    let maxZoom = ShowLevel[1]
    if(options && options.minZoom){
      minZoom = options.minZoom
    }
    if(options && options.maxZoom){
      maxZoom = options.maxZoom
    }
    let layer = new Layer({
      source: source,
      zIndex: zIndex,
      minZoom: minZoom,
      maxZoom: maxZoom,
      style:(evt)=>{
        return styleFunVT.call(funThis,evt);
      }
    })
    this.layer = layer
    this.source = source,
    this.vLayer = this.initVectorLayer(styleFunV,funThis,minZoom,maxZoom)
  }
  setMaxZoom(maxZoom){
    this.layer.setMaxZoom(maxZoom);
  }
  setMinZoom(minZoom){
    this.layer.setMinZoom(minZoom);
  }
  initVectorLayer(styleFunV,funThis,minZoom,maxZoom){
    let layer = new Vector({
        source:new VectorSource({}),
        style:(evt)=>{
            return styleFunV.call(funThis,evt);
        },
        minZoom: minZoom,
        maxZoom: maxZoom,
        zIndex:101
    })
    return layer;
  }
}

export default VTLayer
