<template>
  <el-container class="map-sub-container">
    <el-header height="50px" class="operation-header">
      <div class="left-tip">
        <i class="el-icon-info" />
        <span>点击地图触发操作</span>
      </div>
      <div class="right-actions">
        <el-button
          :type="enableAddPath ? 'success' : 'primary'"
          size="small"
          icon="el-icon-plus"
          @click="addPath"
        >
          {{ addPathText }}
        </el-button>
        <el-button type="info" size="small" icon="el-icon-guide" @click="onPathNavigator">
          路径巡航
        </el-button>
        <el-button type="danger" size="small" plain icon="el-icon-delete" @click="clearCircle">
          清除圆形
        </el-button>
      </div>
    </el-header>

    <el-main class="map-main-wrapper">
      <div id="container" class="amap-instance" />
    </el-main>

    <el-dialog
      :visible.sync="showPositionDialog"
      width="400px"
      custom-class="custom-map-dialog"
      center
      append-to-body
    >
      <div slot="title" class="dialog-title">
        <i class="el-icon-location-information"></i>
        <span>位置详情与操作</span>
      </div>

      <div class="dialog-body">
        <div class="coord-display">
          <div class="label">选定坐标：</div>
          <div class="value" v-if="positionForm.lng !== null && positionForm.lat !== null">
            {{ positionForm.lng.toFixed(6) }}, {{ positionForm.lat.toFixed(6) }}
          </div>
          <div class="value" v-else>-- , --</div>
        </div>

        <el-divider></el-divider>

        <div v-if="showInput" class="radius-setter">
          <p class="input-tip">设置绘制半径 (米)</p>
          <div class="input-row">
            <el-input-number
              v-model="radius"
              :min="10"
              :max="10000"
              controls-position="right"
              style="width: 100%"
            />
            <el-button type="primary" @click="handleNumChange" style="margin-top: 15px; width: 100%">确定半径并绘制</el-button>
          </div>
        </div>

        <div v-else class="action-grid">
          <el-button icon="el-icon-document-add" @click="onSavePosition">保存坐标</el-button>
          <el-button icon="el-icon-magic-stick" type="success" @click="onDrawCircle">绘制圆形</el-button>
          <el-button icon="el-icon-star-off" type="warning" @click="onSaveMyPosition">设为我的位置</el-button>
        </div>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import {addGeoPosition, addMyPosition, addPath, getGeoPoint} from '@/api/map'

export default {
  name: 'AMap',
  data() {
    return {
      amap: null,
      plugins: ['Scale'],
      mapCenter: [114.0000, 30.0000],
      // zoom=16 的比例尺为 100m
      zoom: 16,
      // zoom=6 的比例尺为 100km
      zoom1: 6,
      province: '',
      provinces: [],
      city: '',
      citys: [],
      district: '',
      districts: [],
      path1: [{
        path: [
          [116.361904, 39.913423],
          [116.367904, 39.913423]
        ]
      }],
      path: [],
      mapCircle: null,
      circleEditor: null,
      showPositionDialog: false,
      showInput: false,
      radius: 1000,
      positionForm: {
        lng: null,
        lat: null
      },
      pointArr: [],
      mapKeys: {
        securityJsCode: '983d6ee43bab3edf3693e91508f94aa9',
        key: '7b75ab2839ce68b884c7a682501ea774'
      },
      addPathText: '添加路径',
      enableAddPath: false,
      pathPointList: []
    }
  },
  mounted() {
    this.initAMap()
  },
  unmounted() {
    this.map?.destroy()
  },
  created() {
    document.title = '地图'
  },
  methods: {
    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: this.mapKeys.securityJsCode
      }
      AMapLoader.load({
        key: this.mapKeys.key, // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '1.4.15', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar',
          'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor', 'AMap.MassMarks', 'AMap.Size',
          'AMap.Pixel'], // 需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
        AMapUI: { // 重点就是这个
          version: '1.0',
          plugins: ['misc/PathSimplifier', 'overlay/SimpleMarker']// SimpleMarker设置自定义图标，PathSimplifier轨迹展示组件
        }
      }).then((AMap) => {
        // 设置地图容器id
        this.map = new AMap.Map('container', {
          viewMode: '2D', // 是否为3D地图模式
          zoom: this.zoom, // 初始化地图级别
          center: [104.065753, 30.657462] // 初始化地图中心点位置
        })

        const that = this
        // 点击事件
        this.map.on('click', (e) => {
          // 获取经纬度
          var lng = e.lnglat.getLng()
          var lat = e.lnglat.getLat()
          const pointArr = [lng, lat]
          if (that.enableAddPath) {
            const point = { lng: lng, lat: lat }
            this.pathPointList.push(point)
            this.$message.info('add point -> (' + lng + ', ' + lat + ')')
          } else {
            that.pointArr = pointArr
            that.positionForm.lng = lng
            that.positionForm.lat = lat
            that.showPositionDialog = true
          }
        })

        // 缩放事件
        this.map.on('zoomchange', (e) => {
          console.log('当前缩放级别: ' + this.map.getZoom())
        })

        // this.onPathNavigator()
      }).catch((e) => {
        console.log(e)
      })
    },
    getDistrict(map) {
      // 创建行政区查询对象
      var district = new AMap.DistrictSearch({
        // 返回行政区边界坐标等具体信息
        extensions: 'all',
        // 设置查询行政区级别为 区
        level: 'street',
        subdistrict: 3
      })

      this.zoom = 11
      const area = '双流'
      district.search(area, function(status, result) {
        var bounds = result.districtList[0].boundaries
        var polygons = []
        if (bounds) {
          for (var i = 0, l = bounds.length; i < l; i++) {
            // 生成行政区划polygon
            var polygon = new AMap.Polygon({
              map: map,
              strokeWeight: 1,
              path: bounds[i],
              fillOpacity: 0.7,
              fillColor: '#CCF3FF',
              strokeColor: '#CC66CC'
            })
            polygons.push(polygon)
          }

          // 地图自适应
          map.setFitView()
        }
      })
    },
    drawCircle(pointArr, radius) {
      // 设置圆形位置
      // var center = new AMap.LngLat(104.065753, 30.657462)
      var center = new AMap.LngLat(pointArr[0], pointArr[1])
      // 设置圆的半径大小
      // var radius = 1000
      // 创建圆形 Circle 实例
      var circle = new AMap.Circle({
        center: center, // 圆心
        radius: radius, // 半径
        borderWeight: 3, // 描边的宽度
        strokeColor: '#ff3333', // 轮廓线颜色
        strokeOpacity: 1, // 轮廓线透明度
        strokeWeight: 1, // 轮廓线宽度
        fillOpacity: 0.4, // 圆形填充透明度
        strokeStyle: 'line', // 轮廓线样式
        strokeDasharray: [10, 10],
        fillColor: '#1791fc', // 圆形填充颜色
        zIndex: 50 // 圆形的叠加顺序
      })

      // 圆形 Circle 对象添加到 Map
      this.map.add(circle)
      // 根据覆盖物范围调整视野
      this.map.setFitView([circle])
      this.mapCircle = circle

      // 鼠标移入事件
      circle.on('mouseover', function() {
        console.log('鼠标移入')
      })

      var that = this
      // 引入圆形编辑器插件
      this.map.plugin(['AMap.CircleEditor'], function() {
        // 实例化圆形编辑器，传入地图实例和要进行编辑的圆形实例
        var circleEditor = new AMap.CircleEditor(that.map, circle)
        // 开启编辑模式
        circleEditor.open()
        that.circleEditor = circleEditor
      })
    },
    // 轨迹巡航
    onPathNavigator() {
      getGeoPoint().then(resp => {
        if (resp.code === 0) {
          const pathList = resp.data
          if (pathList.length === 0) {
            return
          }

          this.path = pathList
          AMapUI.load(['ui/misc/PathSimplifier'], (PathSimplifier) => {
            if (!PathSimplifier.supportCanvas) {
              alert('当前环境不支持 Canvas！')
              return
            }
            // 创建组件实例
            var pathSimplifierIns = new PathSimplifier({
              map: this.map,
              zIndex: 100, // 图层叠加顺序
              data: this.path, // 巡航路径
              // 获取巡航路径中的路径坐标数组
              getPath: (pathData, pathIndex) => {
                return pathData.path
              }
            })
            // 创建巡航器
            var pathNavigator = pathSimplifierIns.createPathNavigator(0, {
              loop: false, // 是否循环
              speed: 3600 // 速度(km/h)
            })
            pathNavigator.start()
          })
        }
      })
    },
    addPath() {
      if (!this.enableAddPath) {
        this.enableAddPath = true
        this.addPathText = '完成添加'
      } else {
        this.enableAddPath = false
        this.addPathText = '添加路径'
        addPath(this.pathPointList).then(resp => {
          if (resp.code === 0) {

          }
        }).finally(() => {
          this.pathPointList = []
        })

        const pathTrail = { path: [] }
        for (const item of this.pathPointList) {
          const arr = []
          arr.push(item.lng)
          arr.push(item.lat)
          pathTrail.path.push(arr)
        }
        this.path.push(pathTrail)
      }
    },
    onSavePosition() {
      this.showPositionDialog = false
      addGeoPosition(this.positionForm).then(resp => {
        if (resp.code !== 0) {
          this.$message.info('添加坐标失败')
        }
      })
    },
    onSaveMyPosition() {
      this.showPositionDialog = false
      addMyPosition(this.positionForm).then(resp => {
        if (resp.code !== 0) {
          this.$message.info('设置位置失败')
        }
      }).catch(error => {
        this.$notify({
          message: error.message,
          type: 'warning',
          duration: 1000
        })
      })
    },
    onDrawCircle() {
      this.showInput = true
    },
    handleNumChange() {
      if (this.radius < 10) {
        this.$message.error('半径至少应大于 10m')
        return
      }
      this.showInput = false
      this.showPositionDialog = false
      console.log(this.pointArr)
      this.drawCircle(this.pointArr, this.radius)
    },
    clearCircle() {
      this.$message.info('清除图形')
      if (this.mapCircle !== null) {
        this.map.remove(this.mapCircle)
        this.mapCircle = null
      }

      if (this.circleEditor !== null) {
        this.circleEditor.close()
        this.circleEditor = null
      }
    }
  }
}
</script>

<style scoped lang="scss">
.map-sub-container {
  height: 100%;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.operation-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fcfcfc;
  border-bottom: 1px solid #ebeef5;
  padding: 0 15px !important;

  .left-tip {
    color: #f56c6c;
    font-size: 13px;
    display: flex;
    align-items: center;
    i { margin-right: 5px; }
  }

  .right-actions {
    display: flex;
    gap: 10px;
  }
}

.map-main-wrapper {
  padding: 0 !important;
  position: relative;
}

.amap-instance {
  width: 100%;
  height: calc(100vh - 180px); // 动态计算高度，适配父级 MapIndex
}

/* 对话框美化 */
::v-deep .custom-map-dialog {
  border-radius: 12px;
  .el-dialog__header {
    padding: 20px;
    border-bottom: 1px solid #f2f6fc;
  }
  .el-dialog__body {
    padding: 10px 25px 30px;
  }
}

.dialog-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-weight: bold;
  color: #303133;
}

.coord-display {
  background: #f0f7ff;
  padding: 15px;
  border-radius: 8px;
  text-align: center;
  .label { font-size: 12px; color: #79bbff; margin-bottom: 5px; }
  .value { font-family: 'Courier New', Courier, monospace; font-weight: bold; color: #409EFF; font-size: 16px; }
}

.action-grid {
  display: flex;
  flex-direction: column;
  gap: 10px;
  .el-button {
    margin-left: 0 !important;
    justify-content: flex-start;
  }
}

.radius-setter {
  .input-tip { font-size: 13px; color: #909399; margin-bottom: 10px; }
}

/* 按钮悬浮动画 */
.el-button {
  transition: all 0.2s ease;
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }
}
</style>
