import mapboxgl from 'mapbox-gl'
import MapboxDraw from '@mapbox/mapbox-gl-draw'
import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css'

/**
 * 自定义地图样式切换控件
 * 用于在 Mapbox 地图上添加一个控件，允许用户选择不同的地图样式
 */
export class MapboxStyleSwitcherControl {
  /**
   * 构造函数
   * @param {Array} styles - 可选的样式列表，每个样式包含 name 和 URI。默认为空数组。
   * @param {String} defaultIconClass - 自定义图标的 CSS 类名。默认为空字符串。
   * @param {Number} currentStyleIndex - 当前选中的样式索引。默认为 0。
   */
  constructor (styles = [], defaultIconClass = '', currentStyleIndex = 0) {
    this.styles = styles
    this.defaultIconClass = defaultIconClass
    this.currentStyleIndex = currentStyleIndex // 当前样式索引
    this.controlContainer = null // 控件容器
    this.map = null // 地图实例
    this.styleButton = null // 切换样式的按钮
    this.styleDropdown = null // 样式选择的下拉菜单
  }

  /**
   * 添加控件到地图上
   * @param {MapboxMap} map - Mapbox 地图实例
   * @returns {HTMLElement} 控件的容器元素
   */
  onAdd (map) {
    this.map = map

    // 创建控件的容器元素
    this.controlContainer = document.createElement('div')
    this.controlContainer.className = 'mapboxgl-ctrl mapboxgl-ctrl-group'
    this.controlContainer.style.display = 'flex'
    this.controlContainer.style.flexDirection = 'column'
    this.controlContainer.style.alignItems = 'center'
    this.controlContainer.style.justifyContent = 'center'
    this.controlContainer.style.overflow = 'hidden'

    // 创建切换样式的按钮
    this.styleButton = document.createElement('button')
    this.styleButton.className = this.defaultIconClass || 'style-switcher-button' // 如果提供了自定义类名，则使用它
    this.styleButton.onclick = this._toggleDropdown.bind(this) // 绑定按钮点击事件

    // 让按钮内容（图标）居中
    this.styleButton.style.display = 'flex'
    this.styleButton.style.alignItems = 'center'
    this.styleButton.style.justifyContent = 'center'
    this.styleButton.style.width = '29px' // 可以根据需要调整
    this.styleButton.style.height = '29px' // 可以根据需要调整

    // 创建样式选择的下拉菜单
    this.styleDropdown = document.createElement('div')
    this.styleDropdown.className = 'style-dropdown'
    this.styleDropdown.style.display = 'none' // 初始状态为隐藏
    this.styleDropdown.style.cursor = 'pointer' // 鼠标样式

    // 为每个样式创建选择项并添加到下拉菜单中
    this.styles.forEach((style, index) => {
      const styleOption = document.createElement('div')
      styleOption.className = 'style-option'
      styleOption.innerHTML = style.name // 使用 name 作为显示内容
      styleOption.style.padding = '5px 5px'
      styleOption.style.borderTop = '1px solid #ddd'
      styleOption.style.overflow = 'hidden'
      // 如果当前样式索引与选中样式索引匹配，添加高亮样式
      if (this.currentStyleIndex === index) {
        styleOption.style.color = '#409EFF' // 设置选中项字体颜色
      } else {
        styleOption.style.color = 'black' // 设置默认字体颜色
      }
      styleOption.onclick = () => this._changeStyle(style, index) // 绑定样式选择事件

      // 添加鼠标经过效果
      styleOption.addEventListener('mouseover', () => {
        styleOption.style.backgroundColor = '#f0f0f0' // 鼠标经过时的背景颜色
      })

      styleOption.addEventListener('mouseout', () => {
        styleOption.style.backgroundColor = 'transparent' // 鼠标移开时的背景颜色
      })

      this.styleDropdown.appendChild(styleOption)
    })

    // 将按钮和下拉菜单添加到控件容器中
    this.controlContainer.appendChild(this.styleButton)
    this.controlContainer.appendChild(this.styleDropdown)

    return this.controlContainer
  }

  /**
   * 从地图上移除控件
   */
  onRemove () {
    this.controlContainer.parentNode.removeChild(this.controlContainer)
    this.map = null
  }

  /**
   * 切换下拉菜单的显示状态
   */
  _toggleDropdown () {
    if (this.styleDropdown.style.display === 'none') {
      this.styleDropdown.style.display = 'block' // 显示下拉菜单
      this.styleButton.style.width = '100%' // 可以根据需要调整
    } else {
      this.styleDropdown.style.display = 'none' // 隐藏下拉菜单
      this.styleButton.style.width = '29px' // 可以根据需要调整
    }
  }

  /**
   * 切换地图样式
   * @param {Object} style - 要切换到的样式对象
   * @param {Number} index - 要切换到的样式索引
   */
  _changeStyle (style, index) {
    this.map.setStyle(style) // 设置地图样式
    this.styleDropdown.style.display = 'none' // 隐藏下拉菜单
    this.styleButton.style.width = '29px' // 可以根据需要调整
    this.currentStyleIndex = index // 更新当前选中的样式索引
    this._updateStyleOptions() // 更新下拉菜单中的样式选项
  }

  /**
   * 更新下拉菜单中的样式选项
   */
  _updateStyleOptions () {
    const styleOptions = this.styleDropdown.querySelectorAll('.style-option')
    styleOptions.forEach((option, index) => {
      if (this.currentStyleIndex === index) {
        option.style.color = '#409EFF' // 高亮选中项
      } else {
        option.style.color = 'black' // 默认字体颜色
      }
    })
  }
}

// 飞机跟随控件
export class FollowControl {
  constructor ({ defaultIconClass, activeIconClass, onClick }) {
    this._defaultIconClass = defaultIconClass
    this._activeIconClass = activeIconClass
    this._onClick = onClick
    this._isActive = false // 控件是否激活的状态
  }

  onAdd (map) {
    this._map = map
    this._container = document.createElement('div')
    this._container.className = 'mapboxgl-ctrl mapboxgl-ctrl-group'

    this._button = document.createElement('button')
    this._button.className = this._defaultIconClass // 初始化时使用默认图标
    this._button.onclick = this._handleClick.bind(this) // 绑定点击事件处理函数

    this._container.appendChild(this._button)

    // 监听地图 mousedown 事件
    this._map.on('mousedown', this._handleMapMouseDown.bind(this))

    // 监听触摸事件
    this._map.getCanvasContainer().addEventListener('touchstart', this._handleMapMouseDown.bind(this))
    this._map.getCanvasContainer().addEventListener('touchmove', this._handleMapMouseDown.bind(this))
    this._map.getCanvasContainer().addEventListener('touchend', this._handleMapMouseDown.bind(this))

    return this._container
  }

  _handleClick () {
    this._isActive = !this._isActive
    this._button.className = this._isActive
      ? this._activeIconClass
      : this._defaultIconClass

    // 执行传入的点击回调函数
    if (this._onClick) {
      this._onClick(this._isActive) // 传递控件的当前激活状态
    }
  }

  _handleMapMouseDown () {
    if (this._isActive) {
      this._isActive = false
      this._button.className = this._defaultIconClass

      if (this._onClick) {
        this._onClick(false) // 停止跟随
      }
    }
  }

  onRemove () {
    this._map.off('mousedown', this._handleMapMouseDown.bind(this))
    this._container.parentNode.removeChild(this._container)
    this._map = undefined
  }
}

// 全屏控制控件 ps:官方全屏子类 添加一个回调
export class CustomFullscreenControl extends mapboxgl.FullscreenControl {
  constructor (handleResize) {
    super()
    this.handleResize = handleResize
  }

  _onClickFullscreen () {
    super._onClickFullscreen() // 调用原始的全屏切换行为
    this.handleResize() // 调用自定义的 handleResize 方法
  }
}

// 禁飞区控件
export class NoFlyControl {
  constructor (options = {}) {
    this._map = null
    this._container = null
    this._draw = null
    this._onDrawFinish = options.onDrawFinish || function () {}
    this._defaultPolygons = options.defaultPolygons || []
    this._onSave = options.onSave || function () {}
  }

  onAdd (map) {
    this._map = map

    // 创建按钮容器
    this._container = document.createElement('div')
    this._container.className = 'mapboxgl-ctrl mapboxgl-ctrl-group'

    // 绘制按钮
    const drawButton = document.createElement('button')
    drawButton.className = 'mapboxgl-ctrl-icon'
    drawButton.type = 'button'
    drawButton.innerHTML = '✏️'
    drawButton.title = '绘制禁飞区'
    drawButton.onclick = () => this._enableDraw()
    this._container.appendChild(drawButton)

    // 保存按钮（磁盘图标）
    const saveButton = document.createElement('button')
    saveButton.className = 'mapboxgl-ctrl-icon'
    saveButton.type = 'button'
    saveButton.innerHTML = '💾'
    saveButton.title = '保存禁飞区'
    saveButton.onclick = () => this._savePolygons()
    this._container.appendChild(saveButton)

    // 删除按钮（仅删除选中的图形）
    const deleteButton = document.createElement('button')
    deleteButton.className = 'mapboxgl-ctrl-icon'
    deleteButton.type = 'button'
    deleteButton.innerHTML = '🗑️'
    deleteButton.title = '删除选中图形'
    deleteButton.onclick = () => this._deleteSelected()
    this._container.appendChild(deleteButton)

    // 初始化 Draw 控件
    this._draw = new MapboxDraw({
      displayControlsDefault: false,
      styles: [
        {
          id: 'gl-draw-polygon-fill',
          type: 'fill',
          filter: ['all', ['==', '$type', 'Polygon'], ['!=', 'mode', 'static']],
          paint: {
            'fill-color': '#ff0000',
            'fill-opacity': 0.3
          }
        },
        {
          id: 'gl-draw-polygon-stroke-active',
          type: 'line',
          filter: ['all', ['==', '$type', 'Polygon'], ['!=', 'mode', 'static']],
          paint: {
            'line-color': '#ff0000',
            'line-width': 2
          }
        },
        {
          id: 'gl-draw-polygon-and-line-vertex-halo-active',
          type: 'circle',
          filter: ['all', ['==', 'meta', 'vertex'], ['==', '$type', 'Point']],
          paint: {
            'circle-radius': 7,
            'circle-color': '#FFF'
          }
        },
        {
          id: 'gl-draw-polygon-and-line-vertex-active',
          type: 'circle',
          filter: ['all', ['==', 'meta', 'vertex'], ['==', '$type', 'Point']],
          paint: {
            'circle-radius': 5,
            'circle-color': '#f00'
          }
        }
      ]
    })

    map.addControl(this._draw)

    // 加载默认禁飞区
    if (this._defaultPolygons.length > 0) {
      const features = this._defaultPolygons.map(coords => ({
        type: 'Feature',
        geometry: {
          type: 'Polygon',
          coordinates: [coords]
        },
        properties: {}
      }))
      this._draw.set({
        type: 'FeatureCollection',
        features
      })
    }

    map.on('draw.create', this._handleDraw.bind(this))

    return this._container
  }

  onRemove () {
    if (this._map && this._draw) {
      this._map.removeControl(this._draw)
    }
    if (this._container?.parentNode) {
      this._container.parentNode.removeChild(this._container)
    }
    this._map = null
  }

  _enableDraw () {
    if (this._draw && this._map) {
      this._draw.changeMode('draw_polygon')
    }
  }

  _handleDraw (e) {
    const features = this._draw.getAll()
    if (features.features.length > 0) {
      const coordinates = features.features.map(f => f.geometry.coordinates)
      this._onDrawFinish(coordinates)
    }
  }

  _deleteSelected () {
    if (this._draw) {
      const selected = this._draw.getSelectedIds()
      if (selected.length > 0) {
        this._draw.delete(selected)
      }
    }
  }

  _savePolygons () {
    if (!this._draw) return
    const allFeatures = this._draw.getAll()
    const polygons = allFeatures.features.map(f => f.geometry.coordinates)
    // 调用传入的保存回调
    this._onSave(polygons)
  }
}
