/**
 * Created by cp on 2018/7/6.
 */
/**
 * Created by cp on 2018/7/2.
 */
// 定义类  修改地图基础图层类
import {BaseLayer} from '../layer/baseLayer';
import {FeatureStyle} from  '../front/FeatureStyle';
import Tile from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import OSM from 'ol/source/OSM';
import BingMaps from 'ol/source/BingMaps';
import {addProjection, transformExtent, transform} from 'ol/proj';

import ImageLayer from 'ol/layer/Image.js';
import Static from 'ol/source/ImageStatic.js';
import Projection from 'ol/proj/Projection.js';
import {getCenter} from 'ol/extent.js';
class ChangeBaseLayer {
  constructor(vueThis,objMap) {

    if(objMap.getMap()){
      this.map=objMap.getMap();//地图    有可能传的是最外层的map
      this.objMap=objMap;
    }else{
      this.map=objMap;//地图
    }
    this.vm = vueThis;//类中变量
    this.allLayers=[];
  }

  chanegMapLayer(value){
    if(value=="normalMap"){//   普通地图
      this.showBaseLayerByName(["矢量图层"],true);
    } else if(value=="earth"){//   earth地形图
      this.showBaseLayerByName(["遥感图层","标注"],true);
    } else if(value=="panorama"){//   热度图
    }
  }




  setImageLayer(extent,imageUrl,imageLayer){
    if(imageLayer){
      this.map.removeLayer(imageLayer);
    }
    imageLayer= new ImageLayer({
      zIndex:1,//所有的图层默认都是0 如果想要区别开 其他图层都需要进行设置
      source: new Static({
        url: imageUrl,
        imageExtent: transformExtent(extent, 'EPSG:4326', 'EPSG:3857')
      })
    })
    imageLayer.setZIndex(1);
    this.map.addLayer(imageLayer);

    // this.objMap.setLimitCenter(getCenter(transformExtent(extent, 'EPSG:4326', 'EPSG:3857')));
    this.objMap.setLimitExtent(transformExtent(extent, 'EPSG:4326', 'EPSG:3857'));
    return imageLayer;
  }


  //控制图层的显示影藏图层  图层名称 以及显示状态   isRemove  为true 是找到并且从系统中移除
  /***修改图层显示隐藏 ，同时语句isremove确认是否删除底图****/
  showBaseLayerByName(layerName,isRemoveBase){
    var arrGroup=this.map.getLayerGroup().getLayers().getArray();
    for(var j=0;j<arrGroup.length;j++){
      var tempobj=arrGroup[j];
      var  isArr=false;
      if(tempobj.getLayers&&tempobj.getLayers()){
        isArr=true;
      }
      if(!isArr){
        //适量图层
        this.changeBaseLayerByName(tempobj,layerName,isRemoveBase);
      }else if(isArr){
        //s数组
        var  arr1s=tempobj.getLayers().getArray();
        for(var i=0;i<arr1s.length;i++){
          this.changeBaseLayerByName(arr1s[i],layerName,isRemoveBase);
        }
      }
    }
  }


  changeBaseLayerByName(tempLayer,searchLayerName,isRemoveBase){
    if(tempLayer.get("type")=="base"){
      let layerName=tempLayer.get("name");
      if(searchLayerName&&searchLayerName!=null){
        if(layerName&&layerName==searchLayerName){
          if(isRemoveBase){
            this.map.removeLayer(tempLayer);
          }else{
            tempLayer.setVisible(true);
          }
        } else{
          tempLayer.setVisible(false);
        }

      }else{
        if(isRemoveBase){
          this.map.removeLayer(tempLayer);
        }
      }
    }


  }

  //控制图层的显示影藏图层  图层名称 以及显示状态
  changeLayerVisableByName(layerName,status){
    let layer=this.getLyaersByName(layerName);
    if(layer){
      layer.setVisible(status);
      return true;
    }
    return false;
  }


  //移除
  removeBaselayer(){
    this.showBaseLayerByName('',true);
  }


  startChange(mapTypes,showType){
    this.removeBaselayer();
    let typeUrlArr=ChangeBaseLayer.typeUrlArr
    let baseLayers=[];
    for(let i=0;i<typeUrlArr.length;i++){
      let tempObj=typeUrlArr[i];

      for(let k=0;k<mapTypes.length;k++){
        if(tempObj.type==mapTypes[k]){
          baseLayers.push(tempObj);
        }
      }
    }

    for(let i=0;i<baseLayers.length;i++){
      let tempLayer=baseLayers[i];
      let isShow=false;
      if(tempLayer.type==showType){
        isShow=true;
      }
      this.addBaseMapLayer(tempLayer,isShow);
    }

  }


  addBaseMapLayer(tempLayer,isShow){
    //OSM地图
    let urls=tempLayer.layers;
    for(let i=0;i<urls.length;i++){
      let url=urls[i].url;
      let  mapSrc={};
      if(tempLayer.type=='osmNomal'||tempLayer.type=='osmDx'||tempLayer.type=='osmZxc'){
        if(tempLayer.type=='osmNomal'){
          mapSrc=new OSM()
        }else{
          mapSrc=new OSM({url:url})
        }
      }else if( tempLayer.type=='bymap'){
        mapSrc =new  BingMaps({
          key:tempLayer.layers[0].key,
          imagerySet: 'Road',
          tileSize:[256,256]
        })
      }else {
        mapSrc= new XYZ({
          url: url
          ,tileSize:[256,256],
          maxZoom:20,
          wrapX:false
        })
      }
      let layer;
      layer= new Tile({
        source:mapSrc,
        visible:isShow,
        zoomOffset : 3,
        extent: ChangeBaseLayer.mapMaxExtent,
        projection:ChangeBaseLayer.mapPro,
        type : 'base',
        title : url[i].name,
        zIndex:0
      });
      layer.set("name",url[i].name);
      this.map.addLayer(layer);
    }

  }


//判断图层是否存在
  getLyaersByName(layerName){
    var arrGroup=this.map.getLayerGroup().getLayers().getArray();
    for(var j=0;j<arrGroup.length;j++){
      var tempobj=arrGroup[j];
      var  isArr=false;

      if(tempobj.getLayers&&tempobj.getLayers()){
        isArr=true;
      }
      if(!isArr){
        //适量图层
        if(tempobj.get("name")&&tempobj.get("name")==layerName){
          //存在
          return tempobj;
        }
      }else if(isArr){
        //s数组
        var  arr1s=tempobj.getLayers().getArray();
        for(var i=0;i<arr1s.length;i++){
          var  layer1=arr1s[i];
          if(layer1.get("name")&&layer1.get("name")==layerName){
            //存在
            return layer1;
          }
        }
      }
    }
    return null;
  }



  getFeatureById(layerId,featureId){
    let layerItem=this.getLayerClassById(layerId);
    let features;
    //存在并显示
    if(layerItem&&layerItem.getLayer().getVisible()){
      features= layerItem.getFeatureById(featureId);
      //找打对应的featureId
      if(features.length>0){
        let feItem=features[0];
        let feExtent= feItem.getGeometry().getExtent();
        this.map.getView().fit(feExtent, {duration:1000})
      }
    }

  }

  removeFeatureFromLayer(layerId,featureId){
    let layerItem=this.getLayerClassById(layerId);
    if(layerItem){
      layerItem.removeFeatureById(featureId);
    }
  }

  getFeatureByLayerId(layerId,success,fail){
    let layerFeature= new FeatureStyle(this.vm,null);
    layerFeature.setToken(this.vm.frontToken);
    layerFeature.getFeatureByLayerId(layerId,{},success,fail)
  }



  getLayerClassById(dataId){
    let layerArr=this.allLayers;
    for(let i=0;i<layerArr.length;i++){
      if(layerArr[i].id==dataId){
        return layerArr[i].layer;
      }
    }
    return null;
  }
  changeLayerVisable(data,isShow,callBackFunc){
    let status= this.changeLayerVisableByName(data.id,isShow);
    if(status){
      //true 说明有图层layerId
    }else if(isShow){
      //说明没有图层  并且还需要显示图层 需要新增  以图层id为名称 ，id是不可变的值
      let layer= BaseLayer(this.map,1,20,data.id,this.vm);
      layer.setCallbackFunc(callBackFunc);
      if(data.featureList){
        layer.addFeatureArr(data.featureList);
      }
      this.allLayers.push({id:data.id,layer:layer});
    }
  }
}


/***地图配置文件****/
ChangeBaseLayer.typeUrlArr=[
  {type:'tdtyg',name:'天地图遥感',
    layers:[
      {
        url:'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}',
        name:'天地图遥感'
      },
      {
        url:'http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}',
        name:'天地图标注'
      }
    ]
  },
  {type:'tdtsl',name:'天地图矢量',
    layers:[
      {url:'http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}',name:'天地图矢量'},
      {
        url:'http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}',
        name:'天地图标注'
      }
    ]},{type:'gdyg',name:'高德遥感',
    layers:[
      {url:'http://webst04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=6&x={x}&y={y}&z={z}',name:'高德遥感'},
      {url:'https://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=8&ltype=11',name:'高德标注'}
    ]},
  {type:'gdsl',name:'高德矢量',
    layers:[
      {url:'http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',name:'高德矢量'}
    ]},


  {type:'osmNomal',name:'osm',
    layers:[
      {name:'osm'}
    ]},
  {type:'osmDx',name:'osm地形图',
    layers:[
      {url:'http://tile-{a-c}.openstreetmap.fr/hot/{z}/{x}/{y}.png',name:'osm地形图'}
    ]},
  {type:'osmZxc',name:'osm自行车地图',
    layers:[
      {url:'http://{a-c}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png',name:'osm自行车地图'}
    ]},
  {type:'bymap',name:'必应地图',
    layers:[
      {key:'AkjzA7OhS4MIBjutL21bkAop7dc41HSE0CNTR5c6HJy8JKc7U9U9RveWJrylD3XJ',url:'',name:'必应地图'}
    ]},
  {type:'googleJt',name:'google交通底图',
    layers:[
      {url:'http://www.google.cn/maps/vt/pb=!1m4!1m3!1i{z}!2i{x}!3i{y}!2m3!1e0!2sm!3i345013117!3m8!2szh-CN!3scn!5e1105!12m4!1e68!2m2!1sset!2sRoadmap!4e0',name:'google交通底图'}
    ]},
  {type:'googleDX',name:'google地形图',
    layers:[
      {url:'http://mt3.google.cn/vt/lyrs=t@131,r@216000000&hl=zh-CN&gl=CN&src=app&x={x}&y={y}&z={z}&s=Gal',name:'google地形图'}
    ]},  {type:'googleWXT',name:'google卫星图',
    layers:[
      {url:'http://mt2.google.cn/vt/lyrs=y&hl=zh-CN&gl=CN&src=app&x={x}&y={y}&z={z}&s=G',name:'google卫星图'}
    ]}
];
/**
 边界
 */
ChangeBaseLayer.mapMaxExtent=[-2.003750834E7, -2.003750834E7, 2.003750834E7,2.003750834E7];
/**
 地图投影
 */
ChangeBaseLayer.mapPro="EPSG:900913";

export {ChangeBaseLayer};
