import rasterLayer from "../RasterLayer";
import layerEvents from "../../../lib/layerEvents";
import igsOptions from "./igsOptions";

export default {
  name: "IgsWmtsLayer",
  mixins: [rasterLayer],
  props: {
    ...igsOptions,
    wmtsLayer: {
      type: String,
      require: true
    },
    tileMatrixSet: {
      type: String,
      require: true
    },
    version: {
      type: String,
      default: "1.0.0"
    },
    wmtsStyle: {
      type: String,
      default: "default"
    },
    format: {
      type: String,
      default: "image/png"
    }
  },
  methods: {
    $_init() {
      if (!this.wmtsLayer || !this.tileMatrixSet) {
        return;
      }
      let baseUrl = "";
      if (this.url) {
        if (this.url.indexOf("?") > -1) {
          baseUrl = this.url.split("?")[0];
        } else {
          baseUrl = this.url;
        }
      } else {
        let tempUrl = "/igs/rest/ogc/WMTSServer";
        if (this.serverName && this.serverName !== "") {
          tempUrl = "/igs/rest/ogc/" + this.serverName + "/WMTSServer";
        }
        let domain = this.domain;
        if (!domain) {
          domain = this.protocol + "://" + this.ip + ":" + this.port;
        }
        baseUrl = domain + tempUrl;
      }
      this._zoomOffset = this.zoomOffset;
      if (baseUrl.toLowerCase().indexOf("ime-cloud") > -1) {
        //吉威的数据
        baseUrl += "?service=WMTS&REQUEST=GetTile";
      } else {
        baseUrl += "?service=WMTS&request=GetTile";
        if (this.map.getCRS().epsgCode.includes("4326")) {
          this._zoomOffset = -1;
        }
      }
      const partUrl = this.$_initAllRequestParams().join("&");
      this._url =
        encodeURI(baseUrl) +
        "&" +
        partUrl +
        "&tileMatrix={z}&tileRow={y}&tileCol={x}";
    },
    $_initAllRequestParams() {
      let params = [];
      params.push("version=" + this.version);
      params.push("style=" + this.wmtsStyle || "");
      params.push("tileMatrixSet=" + this.tileMatrixSet);
      params.push("format=" + this.format);
      params.push("layer=" + this.wmtsLayer);
      if (this.token) {
        params.push("token=" + this.token);
      }
      return params;
    },
    $_deferredMount() {
      this.$_init();
      let source = {
        type: "raster",
        tiles: [this._url],
        tileSize: this.tileSize,
        mapgisOffset: this._zoomOffset,
        ...this.source
      };

      this.map.on("dataloading", this.$_watchSourceLoading);
      try {
        this.map.addSource(this.sourceId, source);
      } catch (err) {
        if (this.replaceSource) {
          this.map.removeSource(this.sourceId);
          this.map.addSource(this.sourceId, source);
        }
      }
      this.$_addLayer();
      this.$_bindLayerEvents(layerEvents);
      this.map.off("dataloading", this.$_watchSourceLoading);
      this.initial = false;
    }
  }
};
