<template>
  <div :id="id">
    <map-type ref="cescMapType" v-show="mapTypeVisible"></map-type>
    <layer-control ref="layerControl" v-show="layerControlVisible"></layer-control>
    <locate-tool ref="locateTool" v-show="locateToolVisible"></locate-tool>
  </div>
</template>

<script>
import arcgisAPI from './arcgis/arcgisAPI';
import mapType from './MapType.vue';
import layerControl from './LayerControl.vue';
import locateTool from './LocateTool.vue';
import serviceHelper from "./services/serviceHelper";
import facilityModel from "./model/facilityModel";
import MapConfigHelper from './arcgis/mapConfigHelper';

export default {
  name: 'cesc-map',
  data() {
    return {
      id: '',
      locateToolVisible: false,
      mapTypeVisible: false,
      layerControlVisible: false,
    }
  },
  methods: {
    getAllLayers: function () {
      return this.map.allLayers.items;
    },
    removeLayerById: function (id) {
      this.map.remove(this.arcgisAPI.getLayerById(this.map, id))
    },
    removeAllLayers: function () {
      this.map.removeAll();
    },
    setCenter: function (x, y, zoom) {
      this.arcgisAPI.setCenter(this.view, x, y, zoom)
    },
    zoom: function (zoom) {
      this.arcgisAPI.setCenter(this.view, undefined, undefined, zoom);
    },
    getLayerById: function (id) {
      return this.arcgisAPI.getLayerById(this.map, id);
    },
    addWebTileLayer: function (config, id, click) {
      var layer = this.arcgisAPI.createWebTileLayer(this.map, config, id, click);
      return layer;
    },
    addMapImageLayer: function (config) {
      var layer = this.arcgisAPI.createMapImageLayer(this.map, this.view, config);
      return layer;
    },
    getSubComponent: function (id) {
      return this.$refs[id];
    },
    addGraphicLayer: function (id, graphics, click, index) {
      var layer;
      if (!index) {
        layer = this.arcgisAPI.createGraphicsLayer(this.map, this.view, id, click);
      } else {
        layer = this.arcgisAPI.createGraphicsLayer(this.map, this.view, id, click, index);
      }

      if (!!graphics) {
        graphics.forEach(function (graphic) {
          layer.add(graphic);
        })
      }
      return layer;
    },
    addClusterLayer: function (id, markerSymbol, index) {
      var layer = this.arcgisAPI.createClusterLayer(id, markerSymbol, this.view, this.map);
      if (!!index) {
        this.map.add(layer, index)
      } else {
        this.map.add(layer)
      }
      return layer;
    },
    getFacilityLayer: function () {
      return this.arcgisAPI.getLayerById(this.map, 'facility-graphicLayer');
    },
    changeBaseMap: function (layerID) {
      var openLayer;
      for (var key in this.initedLayers.baseMaps) {
        if (key !== layerID + '') {
          this.initedLayers.baseMaps[key].forEach(function (layer) {
            layer.visible = false;
          })
        } else {
          this.initedLayers.baseMaps[key].forEach(function (layer) {
            layer.visible = true;
            openLayer = layer;
          }.bind(this));
        }
      }
      this.$emit('base-map-change', layerID);
      return openLayer;
    },
    locateToExtent: function (extent, expand) {
      this.arcgisAPI.locateToExtent(this.view, extent, expand);
    },
    showLayerById: function (layerid, index) {
      //监测设备图层
      let showLayer = true
      if (!!this.initedLayers.facilityLayers && layerid.indexOf('facility-graphicLayer') > -1) {
        var newAddLayer = this.initedLayers.facilityLayers;
        if (!this.getFacilityLayer() && !!newAddLayer) {
          this.map.add(newAddLayer, this.map.allLayers.length - 1);
        }
      }
      //业务图层
      else if (!!this.initedLayers.customerLayers) {
        var newAddLayer = this.initedLayers.customerLayers[layerid];
        var scaleExtent = ''
        if(newAddLayer){
          scaleExtent = newAddLayer.config.layer.scaleExtent
        }
        if(scaleExtent){
          let logicParam = scaleExtent.split('-');
          if(this.view.zoom<logicParam[0]){
            showLayer = false;
          }else if(this.view.zoom>logicParam[1]){
            showLayer = false;
          }else {
            showLayer = true;
          }
        }

        if (!this.getLayerById(layerid) && !!newAddLayer) {
          //用户主动配置次序
          if (index) {
            this.map.add(newAddLayer.layer, index);
          }
          //图层次序
          else if (!!newAddLayer.index) {
            this.map.add(newAddLayer.layer, newAddLayer.index + 3);//1、2 一般是底图
          } else {
            this.map.add(newAddLayer.layer);
          }
        } else {
          //  console.error('获取图层失败')
        }
      }

      if(showLayer){
        this.arcgisAPI.showLayer(this.map, layerid);
      }

      //重置下顺序
      setTimeout(function () {
        if (index) {
          this.map.reorder(this.getLayerById(layerid), index)
        }
      }.bind(this), 100)
    },
    hideLayerById: function (layerid) {
      this.arcgisAPI.hideLayer(this.map, layerid);
    },
    getAllBaseLayers: function () {
      return this.initedLayers.baseMaps;
    },
    refreshFacilityLayer: function (cb) {
      this.arcgisAPI.refreshFacilityLayer(this.map, this.configHelper, cb)
    },
     init: function (id, mapConfig, sueecss) {
      this.id = id;
      if(!this.configHelper )this.configHelper = MapConfigHelper.getInstance(mapConfig);
      this.configHelper.lods = mapConfig.lods;
      this.configHelper.tileInfo = mapConfig.tileInfo;
      this.configHelper.serviceMode = mapConfig.serviceMode;
      this.configHelper.mapToken = mapConfig.mapToken;
      this.configHelper.facilityImgObj = mapConfig.facilityImgObj || null
      this.configHelper.isJMMap = mapConfig.isJMMap//用判断江门市地图
      this.configHelper.tdtToken = mapConfig.tdtToken || null//配置天地图token
      mapConfig.isFilterFacilityLayer = mapConfig.isFilterFacilityLayer || false
      mapConfig.isFirstInitFacility = mapConfig.isFirstInitFacility === undefined ? true : mapConfig.isFirstInitFacility; //是否初始化地图时加载测站图层
      this.$nextTick(function () {
        arcgisAPI.getInstance( function (api) {
          this.arcgisAPI = api;
          if(!!mapConfig ){
            serviceHelper.setBasicPath(mapConfig.serverURL);
            serviceHelper.setToken(mapConfig.token);
            MapConfigHelper.getArcgisKey({
              webNetWorkName: mapConfig.webNetWorkName !== undefined ? mapConfig.webNetWorkName : '',
            },(res)=>{
              if(!!res.restUrl){
                this.arcgisAPI.esriId.registerToken({server: res.restUrl, token: res.token});
              }else if( mapConfig.arcgisLoginConf){
                this.arcgisAPI.esriId.registerToken({server: mapConfig.arcgisLoginConf.serverString, token: res.token});
              }

            })

          }

          if (!!mapConfig && mapConfig.identityInfo)
            this.arcgisAPI.registerServer(mapConfig.identityInfo);


          if (!!mapConfig && mapConfig.registerTokenInfo)
            this.arcgisAPI.esriId.registerToken({server: mapConfig.registerTokenInfo.server, token: mapConfig.registerTokenInfo.token});

          if (!!mapConfig && mapConfig.fromServer) {
            serviceHelper.setBasicPath(mapConfig.serverURL);
            serviceHelper.setIOTPath(mapConfig.iotURL);
            serviceHelper.setToken(mapConfig.token);
            api.initMapWithConfig(id, this.configHelper, function (map, view, initedLayers) {
              this.map = map;
              this.view = view;
              this.initedLayers = initedLayers;
              if (mapConfig.mapType == 0) {
                this.mapTypeVisible = false;
              } else {
                this.mapTypeVisible = true;
                this.$nextTick(function () {
                  this.$refs.cescMapType.$emit('init-map-type', this.configHelper);
                }.bind(this))
              }
              if (mapConfig.layerControl == 0) {
                this.layerControlVisible = false;
              } else {
                this.layerControlVisible = true;
                this.facilityLayer = initedLayers.facilityLayer;
                this.$nextTick(function () {
                  //initedLayers.customerLayers
                  this.$refs.layerControl.init(this, initedLayers.customerLayers, mapConfig.layerControl, this.configHelper);
                }.bind(this))
              }
              if (!mapConfig.locateTool) {

              } else {
                this.locateToolVisible = true;
                this.$nextTick(function () {
                  this.$refs.locateTool.init(this, mapConfig);
                }.bind(this))
              }
              this.$nextTick(function () {
                sueecss(api, map, view, initedLayers);
              }.bind(this))
            }.bind(this), mapConfig.click, mapConfig.isFirstLoad, mapConfig.projectId);
          } else {
            api.initMap(id, mapConfig.x, mapConfig.y, mapConfig.zoom, mapConfig.wkid, function (map, view) {
              this.map = map;
              this.view = view;
              sueecss(api, map, view);
            }.bind(this), mapConfig.click)
          }
        }.bind(this))
      }.bind(this))
    },
    getFacilityConfigByType: function (facilityTypeName) {
      return facilityModel.getFacilityByTypeName(facilityTypeName);
    },
    setBaseMapConfig(maps){
      this.configHelper.setBaseMapConfig(maps)
    }
  }
  ,
  mounted() {
    var self = this;
    this.$on('map:show-layer', function (layerid) {
      if (!this.getLayerById(layerid) || !this.getLayerById(layerid).visible) {
        this.showLayerById(layerid);
      } else {
        console.log("图层已经显示")
      }
    }.bind(this));
    this.$on('map:add-layer', function (layerid) {
      if (!this.initedLayers.customerLayers) {
        return;
      }
      var newAddLayer = this.initedLayers.customerLayers[layerid];
      if (!!newAddLayer) {
        if (!!newAddLayer.index) {
          this.map.add(newAddLayer.layer)//默认隐藏的图层第一次显示时需要重新添加到地图
        } else {
          this.map.add(newAddLayer.layer, newAddLayer.index)
        }
      }
    }.bind(this));
    this.$on('map:hide-layer', function (layerid) {
      this.hideLayerById(layerid);
    }.bind(this));
    var timmer;
    this.$on('openMapLegend', legend => {
      var facilityLayer = this.getLayerById('facility-graphicLayer');
      if(!facilityLayer) {
        this.arcgisAPI.setFacilityLayer({visibleWay: 1})
        return
      };
      facilityLayer.graphics.items.forEach(item => {
        if (!item.attributes && !item.attributes.layerConfig) return false;
        if (item.attributes.layerConfig.facilityTypeName == legend.facilityTypeName) item.visible = legend.showIcon;
      })
      let flag = facilityLayer.graphics.items.findIndex(v => v.visible) != -1
      facilityLayer.visible = flag
      setTimeout(() => {
        this.view.onresize(this.view)
      }, 500);
    });

    function displayFacility(legend, cacheFacilities) {
      if (!!legend.showIcon) {
        var spatialReference = self.facilityLayer.spatialReference;
        cacheFacilities.graphics.forEach(function (graphic) {
          graphic.geometry.spatialReference = spatialReference;
        })
        self.facilityLayer.addMany(cacheFacilities.graphics);
      } else {
        self.arcgisAPI.removeGraphics(self.facilityLayer, cacheFacilities.graphics);
      }
    }
  }
  ,
  components: {
    'map-type':
    mapType,
    'layer-control':
    layerControl,
    'locate-tool':
    locateTool
  }
}
</script>

<style>
</style>
