<template>
  <div class="corporate-customers">
    <div class="table-page">
      <div class="table-page-content">
        <div class="left-tree">
          <tree-side
            ref="treeSide"
            :dataLoading="treeLoading"
            :default-expand-all="false"
            :defaultProps="defaultProps"
            :tabList="['行政维度']"
            :treeData="treeData"
            isDeselect
            @currentChange="currentChange"
          ></tree-side>
        </div>
        <div class="right-table">
          <div class="full-page bg">
            <div class="main-table-container" style="margin: 0 !important">
              <div
                id="mapContainer"
                v-loading="mapLoading"
                style="width: 100%; height: 100%"
              ></div>

              <div v-if="isplot" class="drawBtns">
                <!--                <el-button @click="enableEditing">编辑</el-button>-->
                <el-button
                  v-if="isEdit"
                  round
                  type="primary"
                  @click="clearAllApi"
                >清空
                </el-button
                >
                <el-button v-else round type="primary" @click="clearAll"
                >清空
                </el-button
                >
                <el-tooltip
                  class="item"
                  content="点击鼠标右键，退出绘图模式"
                  effect="dark"
                  placement="top-start"
                >
                  <el-button
                    :disabled="!isPolygon"
                    round
                    type="primary"
                    @click="polygonClick"
                  >{{ isPolygon ? '绘图' : '绘图中' }}
                  </el-button
                  >
                </el-tooltip>
                <el-button round type="primary" @click="preservation"
                >保存
                </el-button
                >
              </div>
              <div
                class="search-style"
                style="display: flex; align-items: center"
              >
                <el-input
                  id="tipinput"
                  v-model="mapAddress"
                  placeholder="请输入搜索地址"
                  style="width: 100%"
                >
                  <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="searchKeyWord"
                  ></el-button>
                </el-input>
              </div>
              <div v-if="showsearchResult" class="map_search">
                <ul>
                  <li
                    v-for="(item, index) in poiListData"
                    :key="index"
                    class="li-style"
                    style="cursor: pointer"
                    @click="markerResult(item)"
                  >
                    {{ item.name }}
                  </li>
                </ul>
              </div>
              <div class="lnglat-input-text">WGS84坐标转高德坐标</div>
              <el-input
                v-model="lnglat"
                class="lnglat-input"
                clearable
                placeholder="106.5478767, 29.5647398"
                @clear="clearLnglat"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="changeLngLat"
                ></el-button>
              </el-input>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {lazyAMapApiLoaderInstance} from 'vue-amap'
import {
  editPointSaving,
  getFenec,
  getTree,
  pointSaving,
  tableDelete
} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/electronicFence'
import treeSide from '@/components/treeSide/index.vue'

window._AMapSecurityConfig = {
  securityJsCode: window.context.securityJsCode //你的秘钥
}
export default {
  name: 'TablePage',
  components: {
    treeSide
  },
  data() {
    return {
      mapLoading: false,
      roadId: '',
      roadList: [],
      treeLoading: false,
      treeData: [], //左边树
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      center: [106.5478767, 29.5647398], // 地图中心点
      zoom: 11,
      map: undefined,
      polygon: null,
      //当前的绘制图层
      currentOverlay: undefined,
      //控制绘制圆形的变量
      isCircle: true,
      //控制绘制多变型的变量
      isPolygon: true,
      activeEditor: undefined,
      editorOptions: undefined,
      path: [],
      isplot: false,
      isEdit: false,
      mapAddress: '',
      poiListData: [],
      autoCompleteComponent: undefined,
      placeSearchComponent: undefined,
      showsearchResult: false,
      showInfo: false,
      infoWindowPosition: {},
      infoWindowContent: '点击右键保存',
      lnglat: '',
      isFirst: false
    }
  },
  created() {
    // 获取树形目录
    this.getOrgTreeData((treeData) => {
      // 回调中默认选中第一项并将其id作为参数请求表格
      this.treeItem = treeData[0] || {}
      if (this.treeItem.children.length > 0) {
        this.isplot = false
        this.roadList = this.extractIds(this.treeItem)
      }
      this.drawSavedPolygon()
      this.$nextTick((_) => {
        this.$refs.treeSide?.setCurrentKey(treeData[0]?.id)
        this.$refs.treeSide?.expandHandle(true, 2)
        this.isFirst = true
      })
    })
  },
  mounted() {
    lazyAMapApiLoaderInstance.load().then((response) => {
      this.initMap()
    })
  },
  methods: {
    clearLnglat() {
      this.map.clearMap() // 清除所有覆盖物（点标志）
    },
    extractIds(node) {
      let ids = []
      // 如果当前节点有 children，则递归提取
      if (node.children) {
        ids = node.children.map(child => child.id) // 提取当前节点的 id
        // 递归提取子节点的 id
        node.children.forEach(child => {
          ids = ids.concat(this.extractIds(child))
        })
      }
      return ids
    },
    changeLngLat() {
      if (!this.lnglat) return
      const [lng, lat] = this.lnglat.split(',')
      AMap.convertFrom([Number(lng), Number(lat)], 'GPS', (status, result) => {
        console.log('转换成功', result)
        if (result.info === 'ok') {
          const resLnglat = result.locations[0]
          this.markerResult(
            {
              name: '高德坐标：' + resLnglat.lng + ',' + resLnglat.lat,
              location: {
                lng: resLnglat.lng,
                lat: resLnglat.lat
              }
            },
            'gpsTransform'
          )
        }
      })
    },
    /** 初始化搜索 */
    mapSearchInit() {
      let autoOptions = {
        input: 'tipInput'
      }
      this.autoCompleteComponent = new AMap.Autocomplete(autoOptions)
      // 注册placeSearch组件
      this.placeSearchComponent = new AMap.PlaceSearch({
        city: '重庆' //城市
      })
    },
    searchKeyWord() {
      if (this.mapAddress !== '') {
        this.placeSearchComponent.search(this.mapAddress, (status, result) => {
          if (status === 'complete' && result.info === 'OK') {
            this.showsearchResult = true
            this.poiListData = result.poiList.pois
          } else {
            this.showsearchResult = false
            this.poiListData = []
            this.$message({
              message: '没有查到结果',
              type: 'warning'
            })
          }
        })
      } else {
        this.poiListData = []
        this.showsearchResult = false
        this.map.clearMap()
      }
    },
    markerResult(data, type) {
      this.showsearchResult = false
      this.address = data.name
      var marker = new AMap.Marker({
        position: [Number(data.location.lng), Number(data.location.lat)]
      })
      this.map.clearMap() // 清除所有覆盖物（点标志）
      this.map.add(marker) // 添加点标志
      this.showInfoWindow(marker, type)
      setTimeout(() => {
        this.map.setCenter(data.location)
        this.map.setZoom(15)
      }, 50)
      let thisPosition = {
        address: this.address,
        lng: data.location.lng,
        lat: data.location.lat
      }
      this.$emit('select', thisPosition)
    },
    showInfoWindow(marker, type) {
      let infoWindow = new AMap.InfoWindow({
        isCustom: true, //是否自定义信息窗体
        content: `<div style="background-color: white;color:#000000; padding: 10px; border-radius: 5px;border: 1px solid #cccccc;"> ${
          type === 'gpsTransform' ? '' : '地址：'
        }${this.address}</div>`,
        closeWhenClickMap: true,
        zIndex: 999,
        offset: new AMap.Pixel(16, -35)
      })
      infoWindow.open(this.map, marker.getPosition())
    },
    // 获取路段树
    async getOrgTreeData(callback) {
      try {
        this.treeLoading = true
        let {value} = await getTree()
        this.treeData = [this.transformTreeData(value)]
      } finally {
        this.treeLoading = false
        callback && callback(this.treeData)
      }
    },
    transformTreeData(data) {
      return {
        name: data.name,
        id: data.id,
        children: data.children.reduce((acc, child) => {
          acc.push({
            id: child.id,
            name: child.name,
            children: child.teamList.map(road => ({
              id: road.id,
              isDraw: road.isDraw,
              name:
                road.name + '(' + (road.isDraw === '1' ? '已绘图' : '未绘图') + ')'
            }))
          })
          return acc
        }, [])
      }


      // return data.map((item) => ({
      //   id: item.id,
      //   name: item.name, // 一级目录的 label
      //   children: item.teamList.map((grid) => ({
      //     id: grid.id,
      //     isDraw: grid.isDraw,
      //     name:
      //       grid.name + '(' + (grid.isDraw === '1' ? '已绘图' : '未绘图') + ')' // 二级目录的 label
      //   }))
      // }))
    },
    currentChange(nodeItem) {
      if (nodeItem.id === '1766017468444450816') {
        this.isplot = false
        this.roadId = ''
        this.roadList = this.extractIds(nodeItem)
      } else if (nodeItem.children && nodeItem.children.length > 0) {
        this.isplot = false
        this.roadId = ''
        this.roadList = nodeItem.children.map(item => item.id)
      } else {
        this.isplot = true
        this.isEdit = nodeItem.isDraw === '1'
        this.roadList = []
        this.roadId = nodeItem?.id
      }


      // if (nodeItem.children && nodeItem.children.length > 0) {
      //   this.isplot = false
      //   this.roadId = ''
      //   this.roadList = nodeItem.children.map((item) => item.id)
      // } else {
      //   this.isplot = true
      //   this.isEdit = nodeItem.isDraw === '1'
      //   this.roadList = []
      //   this.roadId = nodeItem?.id
      // }
      this.isPolygon = true
      this.clearAllDrawings()
      this.clearPolygons()
      this.drawSavedPolygon()
    },
    //地图初始化
    initMap() {
      this.map = new AMap.Map('mapContainer', {
        center: this.center,
        zoom: this.zoom,
        layers: [
          new AMap.TileLayer() // 默认普通地图图层
        ]
      })
      // 搜索
      this.mapSearchInit()
      // 回显  判断第一次走created里面 之后走这
      if (this.isFirst) {
        this.drawSavedPolygon()
      }
      // 初始化 MouseTool
      AMap.plugin('AMap.MouseTool', () => {
        this.drawingManager = new AMap.MouseTool(this.map) // 初始化 MouseTool
      })
      // //editorOptions 是一个配置对象，专门用于控制地图上编辑功能的样式和行为，尤其是与 MouseTool 配合使用时，能够对绘制的图形进行编辑（例如移动标记点、修改多边形节点等）。
      this.editorOptions = {
        editMarkerOptions: {
          icon: new AMap.Icon({
            size: new AMap.Size(16, 16), // 图标大小
            image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png'
          }),
          offset: new AMap.Pixel(-8, -8) // 图标偏移量
        },
        // 配置可移动的标记点的样式
        moveMarkerOptions: {
          icon: new AMap.Icon({
            size: new AMap.Size(20, 20),
            image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png'
          }),
          offset: new AMap.Pixel(-10, -10)
        },
        // 配置多边形/线条中间节点的样式
        midMarkerOptions: {
          icon: new AMap.Icon({
            size: new AMap.Size(14, 14),
            image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png'
          }),
          offset: new AMap.Pixel(-7, -7)
        }
      }
      // 监听圆形绘制完成事件
      this.drawingManager.on('draw', (event) => {
        if (this.currentOverlay) {
          this.map.remove(this.currentOverlay)
        }

        this.currentOverlay = event.obj
        const shape = event.obj // 获取绘制的图形对象

        if (shape instanceof AMap.Polygon) {
          shape.setOptions({draggable: true})
          shape.on('dragend', function() {
            const newPath = shape.getPath() // 获取拖拽后的路径
            console.log('拖拽后的多边形', newPath)
          })
          this.path = shape.getPath() // 获取多边形的路径点
          console.log('绘制完成的图形类型: 多边形或矩形')
          console.log('顶点经纬度数组:', this.path)
          // this.drawingManager.close();
          this.drawPolygon()
        }
      })
    },
    //多边形绘制开启
    polygonClick() {
      this.drawingManager.close()
      this.isPolygon = !this.isPolygon
      if (this.isPolygon) {
        this.drawingManager.close() // 关闭绘图模式
        this.enableEditing()
      } else {
        // if (this.currentOverlay) {
        //   this.clearAllDrawings();
        // }
        this.drawPolygon()
      }
    },
    //开启绘制图形编辑模式
    enableEditing() {
      if (!this.currentOverlay) {
        alert('请先绘制图形！')
        return
      }
      if (this.currentOverlay instanceof AMap.Polygon) {
        if (this.activeEditor) {
          this.activeEditor.close() // 关闭之前的编辑器
        }
        this.activeEditor = new AMap.PolyEditor(
          this.map,
          this.currentOverlay,
          this.editorOptions
        )
        this.activeEditor.open()
      }
    },
    //清空所有绘制图形
    clearAllApi() {
      this.$confirm('确定删除该区域吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const {state} = await tableDelete(this.roadId)
          if (state) {
            this.isPolygon = true
            this.$message.success(`删除成功`)
            await this.getOrgTreeData((treeData) => {
              this.drawSavedPolygon()
              this.isEdit = false
              this.$nextTick((_) => {
                this.$refs.treeSide?.setCurrentKey(this.roadId)
                this.$refs.treeSide?.expandHandle(true, 2)
              })
            })
            this.clearAllDrawings()
            this.clearPolygons()
          }
        })
        .catch((_) => _)
    },
    clearAll() {
      this.isPolygon = false
      this.isEdit = false
      this.enableEditing()
      this.clearAllDrawings()
      this.clearPolygons()
    },
    //用来清空所有的绘制图形
    clearAllDrawings() {
      this.map.clearMap()
    },
    //用来清空绘制多边形图形
    clearPolygons() {
      this.map.clearMap()
    },
    //多边形回显
    drawPolygon() {
      this.drawingManager.polygon({
        strokeColor: 'red', // 描边颜色
        strokeOpacity: 1, // 描边透明度
        strokeWeight: 3, // 描边宽度
        fillColor: 'red', // 填充颜色
        fillOpacity: 0.5 // 填充透明度
      })
    },
    // 保存
    async preservation() {
      let param = {
        id: this.isEdit ? this.id : '',
        teamId: this.roadId,
        coordinate: JSON.stringify(this.path)
      }
      const {state} = this.isEdit
        ? await editPointSaving(param)
        : await pointSaving(param)
      if (state) {
        this.isPolygon = true
        this.clearAllDrawings()
        this.clearPolygons()
        await this.getOrgTreeData((treeData) => {
          this.drawSavedPolygon()
          this.drawingManager.close()
          this.isEdit = true
          this.$nextTick((_) => {
            this.$refs.treeSide?.setCurrentKey(this.roadId)
            this.$refs.treeSide?.expandHandle(true, 2)
          })
        })
        this.$message.success('保存成功')
      }
    },
    // 回显 详情
    async drawSavedPolygon() {
      this.mapLoading = true
      let teamIds = []
      let dealPolygonArr = []
      if (this.roadList.length > 0) {
        teamIds = this.roadList
      } else {
        teamIds.push(this.roadId)
      }
      const {state, value} = await getFenec(teamIds)
      if (state) {
        this.mapLoading = false
        // 判断如果是编辑时
        if (this.isEdit) {
          this.id = value[0].id
        }
        for (let i = 0; i < value.length; i++) {
          let array = JSON.parse(value[i]?.coordinate)
          const path = array.map(
            (coord) => new AMap.LngLat(coord.lng, coord.lat)
          )
          this.polygon = new AMap.Polygon({
            path: path, // 使用保存的顶点坐标数组来绘制多边形
            strokeColor: 'red', // 描边颜色
            strokeOpacity: 1, // 描边透明度
            strokeWeight: 3, // 描边宽度
            fillColor: 'red', // 填充颜色
            fillOpacity: 0.5
          })
          dealPolygonArr.push(this.polygon)
          this.polygon.setMap(this.map)
          this.map.add(dealPolygonArr)
          this.map.setFitView(dealPolygonArr)
          this.currentOverlay = this.polygon
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.drawBtns {
  position: absolute;
  top: 140px;
  right: 110px;
  z-index: 999;
  width: 200px;
  height: 40px;
  display: flex;
  justify-content: space-between;
}

.search-style {
  position: absolute;
  top: 55px;
  right: 60px;
  z-index: 999;
  width: 250px;
  height: 40px;
}

.lnglat-input-text {
  position: absolute;
  top: 22px;
  left: 60px;
  z-index: 1;
  width: 300px;
  height: 40px;
  background: rgb(17, 64, 102);
  border-radius: 6px;
  color: #f0f0f0 !important;
  padding-top: 6px;
  text-align: center;
  font-size: 14px;
  box-sizing: border-box;
}

.lnglat-input {
  position: absolute;
  top: 55px;
  left: 60px;
  z-index: 1;
  width: 300px;
  height: 40px;
}

.map_search {
  position: absolute;
  top: 95px;
  right: 60px;
  z-index: 999;
  width: 250px;
  height: 200px;
  overflow-y: scroll;
  background: #ffffff;
  color: #000000;
}

.li-style {
  padding: 6px 15px;
}

.li-style:hover {
  background: #11406610;
}
</style>
