import * as L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import 'leaflet-editable/src/Leaflet.Editable'
import 'leaflet-draw/dist/leaflet.draw'
import 'leaflet-draw/dist/leaflet.draw.css'
import visualization_icon_camera from '@/assets/images/visualControl/visualization_icon_camera.png'
import visualization_icon_equipments from '@/assets/images/visualControl/visualization_icon_equipments.png'

export default function(config) {
  const defaultConfig = {
    el: 'map',
    defaultColor: '#11b9e8',
    activeColor: 'orange',
    addColor: '#f90',
    editColor: '#ff0000',
    maxBounds: [[-40000, -40000], [40000, 40000]],
    mapReadonly: false,
    zoomControl: true,
    updateDataEvent: function() {
      return true
    },
    clickDataEvent: function() {
    },
    contextmenu: function() {

    },
    saveResult: function() {

    },
    mapclick: function() {

    }
  }

  const currentConfig = {}

  for (const key in defaultConfig) {
    try {
      if (config[key] !== undefined) {
        currentConfig[key] = config[key]
      } else {
        currentConfig[key] = defaultConfig[key]
      }
    } catch (e) {
      currentConfig[key] = defaultConfig[key]
    }
  }

  const _this = this
  const DATA_CONST = {
    READ_ONLY: -1,
    DEFAULT: 0,
    ADD: 1,
    EDITOR: 2
  }

  this.editType = 0
  let currentEditorCover = null

  if (currentConfig.mapReadonly) {
    this.editType = DATA_CONST.READ_ONLY
  }

  function setCurrentEditorCover(editorCover) {
    if (editorCover) {
      currentEditorCover = editorCover
    }
  }

  function disableCurrentEditorCover() {
    if (currentEditorCover) {
      currentEditorCover.disableEdit()
    }
  }

  function getDataMap(layerItem) {
    const dataMap = new LayerItem()
    dataMap.set('type', layerItem.options.type)
    dataMap.set('options', layerItem.options)
    switch (layerItem.options.type) {
      case 'polygon': // 多边形
        dataMap.set('latlngs', layerItem._latlngs[0])
        break
      case 'marker':
        dataMap.set('latlngs', layerItem._latlngs || layerItem['_latlng'])
        break
    }
    return dataMap
  }

  this.saveEditorCover = function(callback) {
    const dataMap = new LayerItem()
    var type = 'polygon'
    var latlngs = null
    if (_this.layerType === 'facility' || _this.layerType === 'camera' || _this.layerType === 'marker') {
      type = 'marker'
      latlngs = currentEditorCover._latlng
    } else {
      latlngs = currentEditorCover._latlngs[0]
    }
    dataMap.set('type', type)
    dataMap.set('latlngs', latlngs)
    dataMap.set('options', currentEditorCover.options)
    dataMap.set('layerType', _this.layerType)
    currentConfig.updateDataEvent(dataMap).then((flag) => {
      if (flag) {
        disableCurrentEditorCover()
        _this.editType = DATA_CONST.DEFAULT
        arr.push(dataMap)
        if (callback) {
          callback(dataMap)
          return
        }
        addData()
      }
    })
  }

  this.getEditType = function() {
    return _this.editType
  }

  this.addArea = function() {
    _this.layerType = 'area'
    _this.editType = DATA_CONST.ADD
  }
  /** 更换标记点 */
  this.changeLayerType = function(type, _editType = DATA_CONST.ADD) {
    _this.layerType = type
    _this.editType = _editType
  }

  this.setEditType = function(type) {
    _this.editType = type
  }

  const map = L.map(currentConfig.el, {
    crs: L.CRS.Simple, // 一个简单的CRS，可将经度和纬度直接映射到x其中y。可用于平面地图（例如游戏地图）
    zoom: 0,
    center: L.latLng(0, 0),
    maxBounds: currentConfig.maxBounds,
    doubleClickZoom: false,
    drawControl: false,
    attributionControl: false,
    zoomControl: currentConfig.zoomControl,
    editable: true
  })

  // L.EditControl = L.Control.extend({
  //
  //     options: {
  //         position: 'topleft',
  //         callback: null,
  //         kind: '',
  //         html: ''
  //     },
  //
  //     onAdd: function (mapLayer) {
  //         var container = L.DomUtil.create('div', 'leaflet-control leaflet-bar'),
  //             link = L.DomUtil.create('a', '', container);
  //
  //         link.href = '#';
  //         link.title = 'Create a new ' + this.options.kind;
  //         link.innerHTML = this.options.html;
  //         L.DomEvent.on(link, 'click', L.DomEvent.stop)
  //             .on(link, 'click', function () {
  //                 window.LAYER = this.options.callback.call(mapLayer.editTools);
  //             }, this);
  //
  //         return container;
  //     }
  //
  // });
  //
  //
  // var drawnItems = new L.FeatureGroup();
  // mapLayer.addLayer(drawnItems);
  // var drawControl = new L.Control.Draw({
  //     edit: {
  //         featureGroup: drawnItems
  //     }
  // });
  // mapLayer.addControl(drawControl);

  let arr = []
  function LayerItem() {
    this.type = null
    this.latlngs = null
    this.options = null

    this.set = (key, value) => {
      this[key] = value
    }

    this.get = (key) => {
      return this[key]
    }
  }

  var layerGroup = L.layerGroup().addTo(map)
  var layerImageCoverGroup = L.layerGroup().addTo(map)

  this.setRasterLayer = function(imagePath) {
    const imageFile = new Image()
    imageFile.src = imagePath
    imageFile.onload = function() {
      // 设定图片视图的范围为当前的图片宽高
      const height = imageFile.height; const width = imageFile.width
      const imageOverlay = L.imageOverlay(imagePath, [[-(height / 2), -(width / 2)], [(height / 2), (width / 2)]])
      layerImageCoverGroup.clearLayers()
      imageOverlay.addTo(layerImageCoverGroup)
    }
    clearData()
  }

  this.setMapData = function(layerArr) {
    arr = []
    layerArr.forEach((item) => {
      const tempLayerItem = new LayerItem()
      for (const k in item) {
        tempLayerItem.set(k, item[k])
      }
      arr.push(tempLayerItem)
    })
    addData(arr)
  }

  // mapLayer.on(L.Draw.Event.CREATED, function (e) {
  //     var type = e.layerType,
  //         layer = e.layer;
  //     let dataMap = new Map();
  //     dataMap.set("type", type);
  //     switch (type) {
  //         case 'polyline':
  //         case 'polygon':
  //         case 'rectangle':
  //             dataMap.set("latlngs", layer._latlngs);
  //             break;
  //         case 'marker':
  //         case 'circlemarker':
  //             dataMap.set("latlngs", layer._latlng);
  //             break;
  //         case 'circle':
  //             dataMap.set("latlngs", layer._latlng);
  //             dataMap.set("radius", layer._mRadius);
  //             break;
  //     }
  //     arr.push(dataMap);
  //     console.log(e.layer)
  //     console.log(type)
  //     // 由于部分其他效果直接每次重绘
  //     addData();
  //
  //     // 图层组
  //     // layerGroup.addLayer(layer)
  //     // 直接在地图添加不方便管理，所以选择图层组存放数据
  //     // mapLayer.addLayer(layer);
  // });

  function clearData() {
    layerGroup.clearLayers()
    L.popup()
      .setLatLng([1, 2])
      .setContent(`<p>1212</p>`)
      .openOn(map)
      .remove()
  }

  function addData() {
    // 默认先清楚数据
    clearData()
    const fn = function(ary, key) {
      return ary.reduce((total, next) => {
        const index = total.findIndex((item) => {
          return item[key] === 'marker'
        })
        return index === -1 ? total.push(next) && total : total.splice(index, 0, next) && total
      }, [])
    }
    arr = fn(arr, 'type')// 按照类型组合arr
    var items = document.getElementById(currentConfig.el)
      .getElementsByClassName('leaflet-interactive')
    for (let i = 0; i < arr.length; i++) {
      switch (arr[i].get('type')) {
        case 'polyline': // 折线
          L.polyline(arr[i].get('latlngs'), { color: 'red' }).addTo(layerGroup)
          break
        case 'marker': // 标记
          // eslint-disable-next-line no-case-declarations
          const layerType = arr[i].layerType
          // eslint-disable-next-line no-case-declarations
          const title = layerType === 'camera' ? '摄像头' : '设备'
          var myimage = L.icon({
            iconUrl: layerType === 'camera' ? visualization_icon_camera : visualization_icon_equipments,
            iconSize: [38, 38],
            popupAnchor: [50, 0]
          })
          L.marker(arr[i].get('latlngs'), {
            layerId: arr[i].get('layerId'),
            id: arr[i].get('id'),
            equipId: arr[i].get('equipId'),
            icon: myimage,
            title: title
            // draggable:true
          }).on('click', function(item) {
            for (let j = 0; j < items.length; j++) {
              items[j].classList.remove('stroke-dasharray')
            }
            this.options.type = 'marker'
            const tempDataMap = getDataMap(this)
            currentConfig.clickDataEvent(tempDataMap)
            L.popup()
              .setLatLng(item.latlng)
              .setContent(`<p>${title}</p>`)
              .openOn(map)
          }).on('mouseover', function() {
            // L.popup()
            //     .setLatLng(item.latlng)
            //     .setContent('<p>Hello world!<br />This is a nice popup.</p>')
            //     .openOn(mapLayer);
          }).on('dragend', function() {
            // 拖拽回调
            // let latlng=item.target['_latlng'];
            // this.setLatLng([latlng.lat,latlng.lng]);
            // setCurrentEditorCover(this)
            // _this.layerType='marker';
            // currentConfig.saveResult();
          })
            .addTo(layerGroup)
          break
        case 'polygon':
          break
        case 'rectangle': // 矩形
          L.rectangle(arr[i].get('latlngs'), { color: 'red' }).addTo(layerGroup)
          break
        case 'circle': // 圆圈
          L.circle(arr[i].get('latlngs'), { radius: arr[i].get('radius') }).addTo(layerGroup)
          break
        case 'circlemarker': // 圆圈标记
          L.circleMarker(arr[i].get('latlngs'), { radius: 10 }).addTo(layerGroup)
          break
        default:
          break
      }
    }
  }
  // 点击添加点位
  map.on('click', function(ev) {
    const x1 = {
      lat: ev.latlng.lat - 50,
      lng: ev.latlng.lng
    }

    const x2 = {
      lat: ev.latlng.lat + 50,
      lng: ev.latlng.lng
    }

    const y1 = {
      lat: ev.latlng.lat,
      lng: ev.latlng.lng - 50
    }
    const y2 = {
      lat: ev.latlng.lat,
      lng: ev.latlng.lng + 50
    }

    const latlngs = []
    latlngs.push(x1)
    latlngs.push(y1)
    latlngs.push(x2)
    latlngs.push(y2)

    if (_this.editType === DATA_CONST.ADD) {
      const layerType = _this.layerType
      console.log(layerType)
      if (layerType === 'facility' || layerType === 'camera' || layerType === 'marker') {
        var myimage = L.icon({
          iconUrl: layerType === 'camera' ? visualization_icon_camera : visualization_icon_equipments,
          iconSize: [38, 38],
          popupAnchor: [50, 0]
        })
        var marker = L.marker([ev.latlng.lat, ev.latlng.lng], {
          icon: myimage,
          title: layerType === 'camera' ? '摄像头' : '设备点',
          // draggable:true,
          type: _this.layerType
        }).addTo(layerGroup)
        setCurrentEditorCover(marker)
        currentConfig.mapclick({ marker, type: 'marker', layerType: layerType, remove: function() {
          marker.remove()
        } })
      } else {
        const polygon = L.polygon(latlngs, { color: currentConfig.addColor }).on('click', function() {
        }).on('dblclick', function() {
          if (_this.editType === DATA_CONST.EDITOR) {
            this.disableEdit()
            this.enableEdit()
            this.setStyle({
              color: currentConfig.editColor
            })
            this.redraw()
          }
        })
          .addTo(layerGroup)
        setCurrentEditorCover(polygon)
        currentConfig.mapclick({ polygon, type: 'polygon' })
      }
      _this.editType = DATA_CONST.EDITOR
    }
  })
}
