/**
 地图范围
 */


var mapMaxExtent=[-2.003750834E7, -2.003750834E7, 2.003750834E7,2.003750834E7];
/**
 地图投影
 */
var mapPro="EPSG:900913";
/**
 地图数据集
 */
var mapResoultion=[ 156543.03390625, 78271.516953125,39135.7584765625,19567.87923828125,9783.939619140625,4891.9698095703125 ,2445.9849047851562
  ,1222.9924523925781,611.4962261962891,305.74811309814453,152.87405654907226,76.43702827453613,38.218514137268066,19.109257068634033,
  9.554628534317017,4.777314267158508,2.388657133579254,1.194328566789627,0.5971642833948135,0.2985821416974068,0.1492910708487034,0.0746455354243517,0.0373227677121759];
/**
 创建地图
 */
import Map from 'ol/Map';
import View from 'ol/View';
import Tile from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import {addProjection, addCoordinateTransforms, transform} from 'ol/proj';
import ZoomSlider from 'ol/control/ZoomSlider';
import FullScreen from 'ol/control/FullScreen';
import Overlay from 'ol/Overlay';
import {getCenter,containsExtent,intersects} from 'ol/extent.js';

import {defaults as defaultControls, ZoomToExtent} from 'ol/control.js';


function createMap(){
  let  obj={};
  var map;
  let overlay ;

  /**
   创建图层
   */
  function createBaseLayerUrl(layerName,ex,url){
    var getLayer = new Tile({
      zoomOffset : 3,
      extent: ex,
      projection:mapPro,
      type : 'base',
      title : layerName,
      source: new XYZ({
        tileSize:[256,256],
        url:url
      })
    });
    getLayer.set("name",layerName);
    return getLayer;
  }

  let  limitExtent=null;
  function setLimitExtent(extent){
    limitExtent=extent
  }
  obj.setLimitExtent=setLimitExtent;


  var  limitCenter=null;
  function setLimitCenter(center){
    limitCenter=center
  }
  obj.setLimitCenter=setLimitCenter;

  function limtMoveFunc(){
    map.on('moveend', function(event) {
      let curentCenter=[map.getView().getCenter()[0],map.getView().getCenter()[1]];
      let endExtent= map.getView().calculateExtent(map.getSize());
      if(limitCenter){
        let isChange=false;
        if(limitCenter[0]<endExtent[0]||limitCenter[0]>endExtent[2]){
          curentCenter[0]=limitCenter[0];
          isChange=true;
        }
        if(limitCenter[1]<endExtent[1]||limitCenter[1]>endExtent[3]){
          curentCenter[1]=limitCenter[1];
          isChange=true;
        }
        if(isChange){
          map.getView().animate({center: curentCenter});
        }
      }else if(limitExtent){
        let endCenter= getCenter(limitExtent);
        //如果包含则没有关系
        if(intersects(endExtent,limitExtent)){
        }else{
          map.getView().animate({center: endCenter});
        }
      }


    });
  }
  /**
   添加地图事件
   */
  function addMapEvent(){
    //添加限制区域
    limtMoveFunc();
    //单击   并获取feature的属性
    map.on('singleclick', function(event) {
      var  l1=event.coordinate;
      var l2=transform(l1,mapPro, 'EPSG:4326')
      var isShow=false;

         closePopupWindow(); //点击的如果是地图的话 关闭弹出框  先把他关闭掉
      map.forEachFeatureAtPixel(event.pixel, function(feature, layer){
        // 为选中的到的feature发送自定义的mousemove消息
        if(isShow){
          return;
        }
        let canClick=feature.get('singleclick');
        if(feature&&canClick){
          feature.dispatchEvent({type: 'singleclick', event: event});
          isShow=true;
        }else{
        }
      });
    });


    var target = map.getTarget();
    var jTarget = typeof target === "string" ? $("#"+target) : $(target);
    var  lastTarget;
    //map移动事件
    map.on('pointermove', function(event){
      if (event.dragging) {
        return;
      }

      var hit=false;
      var tempe = map.forEachFeatureAtPixel(event.pixel, function (feature, layer) {

        return feature;
      });
      if(tempe){
        hit=true;
      }
      if(tempe){
        tempe.dispatchEvent({type: 'onMouseMoveOver', event: event});
        lastTarget=tempe;
      }else if(lastTarget){
        lastTarget.dispatchEvent({type: 'onMouseMoveOut', event: event});
        lastTarget=null;
      }
      if (hit) {
        jTarget.css("cursor", "pointer");
      } else {
        jTarget.css("cursor", "");
      }
    });

    map.getViewport().addEventListener('mouseout', function(evt) {
      jTarget.css("cursor", "");
    });


    //地图改变事件  地图移动以及地图 中心点改变
    map.on('moveend', function(event) {
      if(zoomFunc){
        var cc3857=map.getView().getCenter();
        var t1=[cc3857[0],cc3857[1]];
        zoomFunc(transform(t1,mapPro, 'EPSG:4326'),map.getView().getZoom());
      }
    });
  }
  var zoomFunc;
// 地图移动方法
  function setMapChangeFunc(callFunc){
    zoomFunc=callFunc;
  }

  obj.setMapChangeFunc=setMapChangeFunc;

  /**
   设置地图中心点以及级别 setCenterAndZoom([116.7,39.1],18);
   */
  function  setCenterAndZoom(lonlat,zoom){
    if(lonlat){
      map.getView().setCenter(transform( lonlat, 'EPSG:4326', 'EPSG:3857'));
    }
    if(zoom){
      map.getView().setZoom(zoom)
    }

  }


  /**
   最大最小级别
   */
  var maxResolution=611.4962261962891;
  var minResolution=0.0746455354243517;
  function  setMaxMinZoom(minL,maxL){
    if(mapResoultion[minL]){
      maxResolution=mapResoultion[minL]
    }

    if(mapResoultion[maxL]){
      minResolution=mapResoultion[maxL]
    }
  }
  //设置最大最小级别
  obj.setMaxMinZoom=setMaxMinZoom;

  var startZoom=5;
  //设置当前缩放级别
  function  setStartZoom(value){
    startZoom=value;
  }

  obj.setStartZoom=setStartZoom;
  /**
   设置中心点
   */
  var  startCenter= [0, 0];
  function  setStartCenter(value){
    startCenter=value;
  }

  obj.setStartCenter=setStartCenter;
  /**
   初始化方法
   */
  function init(targetStr) {
    map = new Map({
      layers : [

      ],
      target: targetStr,
      controls: defaultControls({
        attributionOptions: ({
          collapsible: false
        })
      }),
      view: new  View({
        center: transform(startCenter, 'EPSG:4326', mapPro),
        zoom:startZoom,
        minZoom: 8,
        maxZoom: 13,
        projection:mapPro,
        // maxResolution:maxResolution,
        // minResolution:minResolution//0.2985821416974068
      })
    });

    var  zoomslider = new  ZoomSlider();
    map.addControl(zoomslider);
    map.addControl(new  FullScreen());



//弹出气泡
    var container = document.getElementById('popup');
    var closer = document.getElementById('popup-closer');
    closer.onclick = function() {
      closePopupWindow();
      closer.blur();
      return false;
    }

    overlay=  new Overlay(/** @type {olx.OverlayOptions} */ ({
      element: container,
      autoPan: false,
      autoPanAnimation: {
        duration: 250
      }
    }));

    map.addOverlay(overlay);
    obj.overlay=overlay;
    addMapEvent();
  }

  function closePopupWindow(){
    overlay.setPosition(undefined);
  }

  obj.closePopupWindow=closePopupWindow;

  //恢复地图初始窗台   rezoom  boolean 是否恢复地图初始级别，reCenter 是否恢复地图中心点 boolean
  function recovery(reZoom,reCeter){
    if(reCeter){
      map.getView().setCenter(transform( startCenter, 'EPSG:4326', 'EPSG:3857'));
    }
    if(reZoom){
      map.getView().setZoom(startZoom)
    }
  }



  //恢复初始化方法
  obj.recovery=recovery;


  //设置中心点和级别
  obj.setCenterAndZoom=setCenterAndZoom;
  obj.init=init;

  function  getMap(){
    return map;
  }
  obj.getMap=getMap;
  //绘制多边形
  return obj;
}

//新增
export {createMap}
