<template>
  <div id="mapContainer"></div>

  <LeftMenu :dataList="dataList"></LeftMenu>

  <VueJsonEditor v-if="editWinFlag" :editDataList="editDataList"></VueJsonEditor>

  <Table :tableData="tableData" :columnModel="columnModel" :searchText="tableSearchText" v-if="tableShow" :isview="tableShow" :close="handleClose"></Table>

  <editManage
    v-if="isContentShow"
    :isShow="isContentShow"
    :column-model="columnModel"
    :column="columnData"
    :dialog-title="dialogTitle"
    :item="contentItem"
    :is-view="isContentView"
    :close="handleEditClose"
  ></editManage>

   <!-- 十字准线元素 -->
  <div class="map-center-crosshair" v-if="btn_Aim_show"></div>

  <div class="tips">
    <div id="tipsText" @click="copyDivText('#tipsText')">位置信息：{{mouseCenter}}</div>
  </div>

  <div class="select-item" v-if="btn_data_show">
    <el-select
      v-model="selectText"
      multiple
      collapse-tags
      collapse-tags-tooltip
      placeholder="请选择"
      size="small"
      @change="handleSelChange"
      style="width: 270px"
    >
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
  </div>

  <div class="right-btn">
      <el-icon size="20" :color="btn_Aim_show == true ? '#067bc9' : '#000'" title="中心基准线" class="icon" @click="toggleItem('1');">
        <Aim />
      </el-icon>
      <el-divider></el-divider>
      <el-icon size="20" :color="btn_data_show == true ? '#067bc9' : '#000'" title="图层数据" class="icon" @click="toggleItem('2');">
        <Coin />
      </el-icon>
      <el-divider></el-divider>
       <el-icon size="20" :color="editFlag == true ? '#067bc9' : '#000'" title="编辑图层数据" class="icon" @click="toggleItem('3');">
        <Edit />
      </el-icon>
      <el-divider></el-divider>
       <el-icon size="20" :color="btn_area_show == true ? '#067bc9' : '#000'" title="辖区数据" class="icon" @click="toggleItem('4');">
        <PictureRounded />
      </el-icon>
  </div>
  
</template>

<script>
import axios from 'axios'
import qs from 'qs'
import { ElMessage } from "element-plus";
import LeftMenu from "@/components/LeftMenu.vue";
import VueJsonEditor from '@/components/JsonEditor.vue';
import Table from '@/components/Table.vue';
import UTIL from '@/utils/util'
import commonAPI from '@/api/common'
import api from '@/api/content'
import editManage from '@/components/editManage.vue';
export default {
  name: "Map",
  components: {
    VueJsonEditor,
    LeftMenu,
    Table,
    editManage,
    },
  data() {
    return {
      mouseCenter: "121.184665, 31.158609",
      center: [121.184665, 31.158609],
      dataList: "",
      areaDataList: [],
      tableData:[],
      columnModel:[],
      tableShow:false,
      tableSearchText:"",
      hoveredPolygonId: null,
      areaMarkers: [],
      btn_data_show: true,
      btn_Aim_show: false,
      btn_area_show: true,
      mapEditDraw: null,
      editDataList: {},
      editFlag: false,
      editWinFlag: false,

      dialogTitle: "员工信息",
      isContentShow: false,
      isContentView: false,
      // columnModel: {},
      columnData: {
        title: "",
      },
      contentItem: {},

      arrParam: ["补查查询串","补查相似度","补查原因","补查匹配地址","补查点坐标","补查匹配名称","补查buffer_m","补查状态"], //过滤字段
      selectText: [],
      options: [],
      fontText:["concat"]// "concat", ["get", "GUID"], "\n", ["get", "match_status"],"\n", ["get", "range_shape"]
    };
  },
  mounted() {
    let that = this;
    that.initData();
  },
  methods: {
    saveFeature(data){
      if(!data.properties.dms_id){
        ElMessage.error("请选择正确数据进行保存");
        return;
      }
      let content = {};
      content["id"] = data.properties.dms_id;
      content["c_polygon"] = UTIL.geojsonToWkt(data.geometry);
      content["c_properties"] = data.properties;
      let params = {
        content: JSON.stringify(content),
        columnId: 1719,
        modelId: 1753,
      };
      // console.log(params);
      commonAPI.updateContent(params).then(res => {
        if(res.code == 200){
          ElMessage.success("保存成功");
          this.getVectorData();
          // 清空绘制工具
          this.mapEditDraw.clearAll();
        }else{
          ElMessage.error(res.msg);
        }
      })
    },
    closeJsonEditor(){
      // 清空编辑数据
      this.editDataList = {};
      this.editWinFlag = false;
      // 确保vector-data数据源存在且为有效的GeoJSON对象
      if (window.mapboxMap.getSource('vector-data') && this.dataList) {
        window.mapboxMap.getSource('vector-data').setData(this.dataList);
      }
      // 确保states数据源存在且为有效的GeoJSON对象
      if (window.mapboxMap.getSource('states') && this.areaDataList) {
        window.mapboxMap.getSource('states').setData(this.areaDataList);
      }
      // 清空绘制工具
      this.mapEditDraw.clearAll();
    },
    toggleItem(item){
      if(item == "1"){
        if(this.btn_Aim_show){
          this.btn_Aim_show = false;
        }else{
          this.btn_Aim_show = true;
        }
      }else if(item == "2"){
        if(this.btn_data_show){
          this.btn_data_show = false;
          window.mapboxMap.setLayoutProperty('data-fill-layer', 'visibility', 'none')
          window.mapboxMap.setLayoutProperty('data-line-layer', 'visibility', 'none')
          window.mapboxMap.setLayoutProperty('data-symbol-layer', 'visibility', 'none')
        }else{
          this.btn_data_show = true;
          window.mapboxMap.setLayoutProperty('data-fill-layer', 'visibility', 'visible')
          window.mapboxMap.setLayoutProperty('data-line-layer', 'visibility', 'visible')
          window.mapboxMap.setLayoutProperty('data-symbol-layer', 'visibility', 'visible')
        }
      }else if(item == "3"){
        this.editDataList = {};
        this.editFlag = !this.editFlag;
        if(!this.editFlag){
          this.editWinFlag = false;
        }
        this.toggleEditMode(this.editFlag);
        window.mapboxMap.getSource('states').setData(this.areaDataList);
        window.mapboxMap.getSource('vector-data').setData(this.dataList);

        this.btn_area_show = false;
        window.mapboxMap.setLayoutProperty('state-fills', 'visibility', 'none')
        window.mapboxMap.setLayoutProperty('state-borders', 'visibility', 'none')
        window.mapboxMap.setLayoutProperty('state-borders-layer-3', 'visibility', 'none')
        window.mapboxMap.setLayoutProperty('state-borders-layer-2', 'visibility', 'none')
        window.mapboxMap.setLayoutProperty('state-borders-layer-1', 'visibility', 'none')
      }else if(item == "4"){
        if(this.btn_area_show){
          this.btn_area_show = false;
          window.mapboxMap.setLayoutProperty('state-fills', 'visibility', 'none')
          window.mapboxMap.setLayoutProperty('state-borders', 'visibility', 'none')
          window.mapboxMap.setLayoutProperty('state-borders-layer-3', 'visibility', 'none')
          window.mapboxMap.setLayoutProperty('state-borders-layer-2', 'visibility', 'none')
          window.mapboxMap.setLayoutProperty('state-borders-layer-1', 'visibility', 'none')
        }else{
          this.btn_area_show = true;
          window.mapboxMap.setLayoutProperty('state-fills', 'visibility', 'visible')
          window.mapboxMap.setLayoutProperty('state-borders', 'visibility', 'visible')
          window.mapboxMap.setLayoutProperty('state-borders-layer-3', 'visibility', 'visible')
          window.mapboxMap.setLayoutProperty('state-borders-layer-2', 'visibility', 'visible')
          window.mapboxMap.setLayoutProperty('state-borders-layer-1', 'visibility', 'visible')
        }
      }
    },
    initData() {
      this.creatMap();
      this.getModelById();
    },
     //根据模型id查询模型详情
    getModelById() {
      let that = this;
      let requestParams = {
        modelId: webConfig.columnArr[0].mid, // 申勤员工ID
      };
      api.getColumnModel(requestParams).then((res) => {
        // console.log(res);
        
        if (res.code === 200) {
          that.columnModel = res.content;
          that.columnModel.modelId = webConfig.columnArr[0].mid;
          that.columnModel.columnId = webConfig.columnArr[0].id;
          that.columnData = that.columnModel;
        }
      });
    },
    //根据内容id查询内容详情
    getContentById(item) {
      let that = this;
      let requestParams = {
        columnId: item.column_id,
        contentId: item.id,
      };
      // console.log(item);
      api.getContentById(requestParams).then((data) => {
        if (data.code === 200) {
          that.contentItem = data.content;
          // that.contentItem.phone = that.formatPhoneNumber(that.contentItem.phone);
          that.isContentShow = true;
          that.isContentView = false;
        }
      });
    },
    //关闭编辑弹窗
    handleEditClose() {
      let guid = sessionStorage.getItem('guid');
      if(guid){
        this.handleMoreClick(guid);
      }else{
        this.$parent.getDmsDataList();
        this.isContentShow = false;
        this.isContentView = false;
        this.contentItem = {};
      }
    },
    handleClose() {
      this.tableShow = false;
    },
    creatMap() {
      let that = this;
      mapboxgl.accessToken = webConfig.MAPBOX_ACCESS_TOKEN;
      window.mapboxMap = new mapboxgl.Map({
          container: 'mapContainer',
          //style: 'mapbox://styles/mapbox/standard',
          //stype:'mapbox://styles/mapbox/streets-v11',
          //style: 'mapbox://styles/mapbox/satellite-v9', // 使用卫星图作为基础样式，你也可以选择其他基础样式或者设置为空字符串''来创建空白底图
          style: { 
            "version": 8, 
            "sources": {}, 
            "layers": [],
            "glyphs": "mapbox://fonts/mapbox/{fontstack}/{range}.pbf" // 添加字体服务
          },
          projection: 'equirectangular', // globe 球体投影   mercator 平面墨卡托投影  equirectangular WGS84平面投影
          zoom: 12, // 初始大小
          minZoom:9,
          maxZoom:18,
          center: that.center, // 中心点
          locale: 'zh-CN', // 设置语言为中文
          doubleClickZoom: false // 禁用双击缩放
      
      });
      window.mapboxMap.addControl(new mapboxgl.NavigationControl(), 'bottom-right');
      window.mapboxMap.on('load', function() {
          // 加载单个图标
          // window.mapboxMap.loadImage('./static/image/location3.png', // 可换成你的图片地址
          // function (error, image) {
          //   if (error) throw error;
          //   window.mapboxMap.addImage('location-icon', image);
          // })

        // 定义你要加载的多个图标
        const icons = [
          { name: "location-icon", url: "./static/image/location.png" },
          { name: "location-icon2", url: "./static/image/location2.png" },
          { name:"location-icon3", url: "./static/image/location3.png" },
          { name:"location-center", url: "./static/image/center.png" }
        ];

        //批量加载所有图标（核心代码）
        icons.map(icon => {
          return new Promise((resolve, reject) => {
            window.mapboxMap.loadImage(icon.url, (error, image) => {
              if (error) reject(error);
              window.mapboxMap.addImage(icon.name, image); // 注册图标
              resolve();
            });
          });
        });
        that.initBaseMap();
        // 初始化
        that.mapEditDraw = new MapDraw.init(window.mapboxMap, {
          // 编辑完成 → 自动接收最新图形
          onEditComplete: (data) => {
            // console.log("===mapEditDraw返回数据===：", data);
            if(data.properties.dms_id){// 对dms_id进行判断
              that.editDataList = data;
            }
            // 你可以在这里提交后端接口，将数据保存到数据库
          }
        });
        window.mapEditDraw = that.mapEditDraw;
        // console.log("mapEditDraw:", that.mapEditDraw);

      })
      that.drawAreaFeature();
      this.getVectorData();
    },

    initBaseMap(type){
      let that = this;
      // window.mapboxMap.setStyle('');
      let titleStyle = webConfig.MAPBOX_TILES_NORMAL;
      if(type == "zwb"){
        titleStyle = webConfig.MAPBOX_TILES_NORMAL;
      }else if(type == "asb"){
        titleStyle = webConfig.MAPBOX_TILES_BLUE;
      }else if(type == "yxt"){
        titleStyle = webConfig.MAPBOX_TILES_YXT;
        // window.mapboxMap.setStyle('mapbox://styles/mapbox/satellite-v9');
      }
      // if(type != "yxt"){
        if(window.mapboxMap.getSource('custom-tiles')){
          window.mapboxMap.getSource('custom-tiles').setTiles([titleStyle]);
        }else{
          window.mapboxMap.addSource('custom-tiles', {
            'type': 'raster',
            'tiles': [titleStyle], // 这里使用你的Tile服务URL
            'tileSize': 512 // 瓦片大小，通常为256x256像素
          });
          window.mapboxMap.addLayer({
            'id': 'custom-tiles-layer',
            'type': 'raster',
            'source': 'custom-tiles',
            'source-layer': 'custom-tiles', // 如果需要的话，指定源层名
            'minzoom': 0,
            'maxzoom': 20
          });
        }
      // }
      window.mapboxMap.on('mouseenter', ['data-fill-layer'], function () {
        window.mapboxMap.getCanvas().style.cursor = 'pointer';
      });
      window.mapboxMap.on('mouseleave', ['data-fill-layer'], function (e) {
        window.mapboxMap.getCanvas().style.cursor = '';
        
      });
      window.mapboxMap.on('mouseleave', ['state-fills'], function (e) {
        window.mapboxMap.getCanvas().style.cursor = '';
        if (that.hoveredPolygonId !== null && that.hoveredPolygonId != undefined) {
                window.mapboxMap.setFeatureState(
                    { source: 'states', id: that.hoveredPolygonId },
                    { hover: false }
                );
            }
            that.hoveredPolygonId = null;
      });
      window.mapboxMap.on('mousemove', ['state-fills'], function(e) {
        let that = this;
        if (e.features.length > 0) {
            if (that.hoveredPolygonId !== null && that.hoveredPolygonId != undefined) {
                window.mapboxMap.setFeatureState(
                    { source: 'states', id: that.hoveredPolygonId },
                    { hover: false }
                );
            }
            that.hoveredPolygonId = e.features[0].id;
            window.mapboxMap.setFeatureState(
                { source: 'states', id: that.hoveredPolygonId },
                { hover: true }
            );
        }
      });
       window.mapboxMap.on('move',  () => {
        let that = this;
        if(that.btn_Aim_show == true){
          that.getCenterPoint();
        }
       })
       window.mapboxMap.on('mousemove', (e) => {
          let that = this;
          if(that.btn_Aim_show == false){
            that.mouseCenter = `${e.lngLat.lng.toFixed(6)}, ${e.lngLat.lat.toFixed(6)}`;
          }
       })
      window.mapboxMap.on('zoom', () => {
        let that = this;
        
        const zoom = window.mapboxMap.getZoom();
        // that.areaMarkers.forEach(marker => {
        //   marker.style.display = zoom >= 14 ? 'none' : 'block';
        // });
        // const markers = document.querySelectorAll('.mapboxgl-marker');
        // markers.forEach(marker => {
        //   marker.style.display = zoom >= 14 ? 'none' : 'block';
        // });
      });
      // window.mapboxMap.on('click', function(e) {
      //   // that.editDataList = fet;
      //   console.log("仅获取 click 的要素：", e);
      //   if (that.editFlag) return;
      //   // 关键：只查询 data-fill-layer，过滤掉所有其他图层
      //   const features = window.mapboxMap.queryRenderedFeatures(e.point, {
      //     layers: ['data-fill-layer'] // 只取这个图层
      //   });
      //   // console.log("仅获取e的要素：", e);
      //   if (!features.length) return;
      //   //  现在最多只有 1 个要素 → 绝对不会乱
      //   const feature = features[0];
      //   console.log("仅获取 feature 的要素：", feature);
      //   //  深拷贝 Geometry：绝对避免引用错乱
      //   const fet = {
      //     type: "Feature",
      //     geometry: JSON.parse(JSON.stringify(feature.geometry)),
      //     properties: { ...feature.properties }
      //   };
        
      //   // console.log("仅获取 data-fill-layer 的要素：", fet);
      //   // 以下弹窗（注意要使用 fet.properties）
      //   let str = "";
      //   for (let item in fet.properties) {
      //     if (UTIL.isChinese(item)) {
      //       str += `<p style="margin:2px 0;">${item}：${fet.properties[item]}</p>`;
      //     }
      //   }

      //   const popupContent = `
      //   <div style="font-size:14px;line-height:1.6;padding:10px;">
      //     <h4 style="margin:0 0 6px 0;color:#222;">详细信息</h4>
      //     ${str}
      //   </div>
      //   `;

      //   if (window.popup) window.popup.remove();
      //   window.popup = new mapboxgl.Popup({
      //     closeButton: true,
      //     className: 'custom-popup',
      //     maxWidth: '500px'
      //   })
      //   .setLngLat(e.lngLat)
      //   .setHTML(popupContent)
      //   .addTo(window.mapboxMap);
      // });
      window.mapboxMap.on('click', that.mapClickValue);
    },
    mapClickValue(e){
        let that = this;
      // that.editDataList = fet;
        // console.log("仅获取 click 的要素：", e);
        // 关键：只查询 data-fill-layer，过滤掉所有其他图层
        const features = window.mapboxMap.queryRenderedFeatures(e.point, {
          layers: ['data-fill-layer'] // 只取这个图层
        });
        that.tableShow = false;
        if (that.editFlag){
          if (features.length){
            that.editWinFlag = true;
          }else{
            // that.editWinFlag = false;
          }
          return;
        };
        // console.log("仅获取e的要素：", e);
        if (!features.length) return;
        //  现在最多只有 1 个要素 → 绝对不会乱
        const feature = features[0];
        // console.log("仅获取 feature 的要素：", feature);
        //  深拷贝 Geometry：绝对避免引用错乱
        const fet = {
          type: "Feature",
          geometry: JSON.parse(JSON.stringify(feature.geometry)),
          properties: { ...feature.properties }
        };
        
        // console.log("仅获取 data-fill-layer 的要素：", fet);
        // 以下弹窗（注意要使用 fet.properties）
        
        let str = "";
        for (let item in fet.properties) {
          // console.log(item);
          if (UTIL.isChinese(item) && !that.arrParam.includes(item)) {
            str += `<p style="margin:2px 0;">${item}：${fet.properties[item]}</p>`;
          }
        }

        const popupContent = `
        <div style="font-size:14px;line-height:1.6;padding:10px;">
          <h4 style="margin:0 0 6px 0;color:#222;"><span>内容信息</span><span class="more" id="popup-more-btn">员工信息>></span></h4>
          ${str}
        </div>
        `;

        if (window.popup) window.popup.remove();
        window.popup = new mapboxgl.Popup({
          closeButton: true,
          className: 'custom-popup',
          maxWidth: '500px'
        })
        .setLngLat(e.lngLat)
        .setHTML(popupContent)
        .addTo(window.mapboxMap);

        setTimeout(() => {
          const moreBtn = document.getElementById('popup-more-btn');
          if (moreBtn) {
            moreBtn.addEventListener('click', () => {
              // that.tableShow = false;
              that.handleMoreClick(fet.properties.GUID);
              sessionStorage.setItem('guid', fet.properties.GUID);
            });
          }
        }, 0);
      
    },
    // 处理弹窗中"更多"按钮点击
    handleMoreClick(guid) {
      const that = this;
      //1743 项目数据  1742 申勤员工
      // 排序条件orderByType  1 升序 2 降序
      let requestParams = {
        columnId: webConfig.columnArr[0].id,
        states: "0,1,2,3",
        orderBy: JSON.stringify([{ field: "update_time", orderByType: 2 }]),
        pageSize: 9999,
        page: 0,
      };
      console.log("guid:", guid);
      requestParams.search = JSON.stringify([
        ...(requestParams.search ? JSON.parse(requestParams.search) : []),
        {
          field: "c_xmguid",  // 申勤员工 c_xmguid   项目数据 c_guid
          searchType: 2,
          content: { value: guid },
        },
      ]);
      commonAPI.getDmsDataList(requestParams).then((res) => {
        if (res.code == 200){
          let data = res.content.data;
          data = data.map(item => {
            // 给每个属性名称添加 c_ 前缀
            const newItem = {};
            for (const key in item) {
              // 如果已经有c_
              if (key.includes("c_")) {
                let itemkey = key.replace(/c_/g, "");
                newItem['c_' + itemkey] = item[key];
              }else{ 
                newItem[key] = item[key];
              }
            }
            return newItem;
          })
          // console.log("data:", data);
          that.tableData = data;
          that.tableData.sort((a, b) => a.c_xm.localeCompare(b.c_xm, 'zh-CN'))
          that.tableSearchText = "";
          if(!that.tableShow){
            that.tableShow = true;
          }

          that.contentItem = data;
          that.isContentShow = false;
          that.isContentView = false;

        }else{
          this.$message({ message: '无员工数据', type: 'info' })
        }
      });
    },
    upTableData(data){
      // console.log("data:", data);
      const that = this;
      that.tableData = data;
      that.tableData.sort((a, b) => a.c_xm.localeCompare(b.c_xm, 'zh-CN'))
    },
    setTableShow(data,text){
      // console.log("data:", data);
      const that = this;
      that.tableShow = false;
      // 使用 $nextTick 确保组件先销毁再重建
      that.$nextTick(() => {
        that.tableShow = true;
        that.tableSearchText = text;
        that.tableData = data;
        that.tableData.sort((a, b) => a.c_xm.localeCompare(b.c_xm, 'zh-CN'))
      });
      // console.log("that.tableSearchText:", that.tableSearchText);
    },
    // 复制指定元素内的文本
    copyDivText(selector) {
      const el = document.querySelector(selector);
      if (!el) return ElMessage({
                  message: "未找到内容",
                  type: "error",
                  duration: 1500
                });;

      // 创建临时文本域
      const text = el.innerText.trim();
      this.$copyText(text);
      // navigator.clipboard.writeText(text).then(() => {
      //   ElMessage({
      //     message: "复制成功",
      //     type: "success",
      //     duration: 1500
      //   });
      // }).catch(err => {
      //   ElMessage({
      //     message: "复制失败",
      //     type: "error",
      //     duration: 1500
      //   });
      // });
    },
    toggleEditMode(isEdit){
      let that = this;
      that.editFlag = isEdit;
      // console.log("isEdit:", isEdit);
      // if(isEdit){
      //    this.editWinFlag = true;
      //    window.mapboxMap.off('click', that.mapClickValue)
      //    this.mapEditDraw.setEditLayerIds(['data-fill-layer']);
      // }else{
      //   window.mapboxMap.on('click', that.mapClickValue);
      //   this.mapEditDraw.setEditLayerIds([]);
      // }
      window.mapboxMap.off('click', that.mapClickValue)
      window.mapboxMap.on('click', that.mapClickValue);
      this.mapEditDraw.setEditLayerIds(['data-fill-layer']);
      that.mapEditDraw.isEdit(isEdit);

    },
    getCenterPoint(){
      let that = this;
      let center = window.mapboxMap.getCenter();
      that.mouseCenter = `${center.lng.toFixed(6)}, ${center.lat.toFixed(6)}`;
      // that.drawCenterPoint(center);
    },
    drawCenterPoint(center){
      let jsondata = {
          type: 'FeatureCollection',
          features: [
            {
              type: 'Feature',
              properties: {
                icon: 'location-center'
              },
              geometry: {
                type: 'Point',
                coordinates: [center.lng, center.lat]
              }
            }
          ]
        };

      if(window.mapboxMap.getSource('center-point-source')){
        window.mapboxMap.getSource('center-point-source').setData(jsondata);
      }else{
          window.mapboxMap.addSource('center-point-source', {
            type: 'geojson',
            data: jsondata
          });
          window.mapboxMap.addLayer({
            id: 'location-layer',
            type: 'symbol', // symbol = 图标/文字图层
            source: 'center-point-source',
            layout: {
              'icon-image': 'location-center', // 使用自定义图标
              'icon-size': 0.5, // 图标大小
              'icon-allow-overlap': true, // 允许图标重叠
              'icon-rotate': 0, // 旋转角度
              'icon-offset': [0, -20] // 图标偏移（上下左右）
            },
            paint: {
              'icon-opacity': 1 // 透明度
            }
          },null);
      }
      window.mapboxMap.moveLayer('location-layer');
    },
    drawAreaFeature(){
      let that = this;
    // 初始化底图
      fetch("./static/data/area.geojson").then((response)=>{ return response.json();})
        .then((data)=>{
            let dataJson = data;
            dataJson.features.map((item, index) => {
                item['id'] = index
                // item.properties['color'] = '#9b46e1'
                // item.properties['height'] = Math.floor(Math.random() * (1000 - 9500 + 1)) + 9500

                let name = item.properties.name;
                let center = turf.center(item).geometry.coordinates; // 自动计算面中心点
                // 创建 HTML 元素
                let el = document.createElement('div');
                el.className = 'area-name';
                el.innerText = name;
                // 添加到地图
                let marker = new mapboxgl.Marker(el, { anchor: 'center' })
                      .setLngLat(center)
                      .addTo(window.mapboxMap);
                that.areaMarkers.push(marker);

            });
            that.areaDataList = dataJson;
            window.mapboxMap.addSource('states', {
                'type': 'geojson',
                'data': dataJson,
                'lineMetrics': true
            });
            window.mapboxMap.addLayer({
                'id': 'state-fills',
                'type': 'fill-extrusion', 
                'source': 'states',
                'maxzoom': 14,
                'layout': {},
                'paint': {
                    'fill-extrusion-color': [
                        'case',
                        ['boolean', ['feature-state', 'hover'], false],
                        // 'rgba(155,70,225,0.80)',// 鼠标移入颜色
                        // 'rgba(250,121,3,0.80)', // 默认颜色
                        'rgba(0, 150, 255, 0.8)', // 默认颜色
                        'rgba(25,172,230,0.8)' // 默认颜色
                    ],
                    "fill-extrusion-opacity":0.2,
                    // 从source 'height'属性获取填充-挤出-高度。
                    'fill-extrusion-height': ['get', 'height'],
                    // 开启垂直渐变（自动上下明暗过渡）
                    'fill-extrusion-vertical-gradient': true,
                    
                }
            });

            window.mapboxMap.addLayer({
              id: 'state-borders-layer-1',
              type: 'line',
              source: 'states',
              paint: {
                'line-color': 'rgba(0, 150, 255, 0.15)',
                'line-width': 20,  // 最宽
                'line-blur': 10,   // 最虚
              }
            });

            // //第2层：中间层，中等宽度、中等模糊、中等透明度
            window.mapboxMap.addLayer({
              id: 'state-borders-layer-2',
              type: 'line',
              source: 'states',
              paint: {
                'line-color': 'rgba(0, 150, 255, 0.3)',
                'line-width': 10,
                'line-blur': 5,
              }
            });

            // // 4. 第3层：内层，较窄、较低模糊、较高透明度
            window.mapboxMap.addLayer({
              id: 'state-borders-layer-3',
              type: 'line',
              source: 'states',
              paint: {
                'line-color': 'rgba(0, 150, 255, 0.8)',
                'line-width': 5,
                'line-blur': 3,
              }
            });

            window.mapboxMap.addLayer({
                'id': 'state-borders',
                'type': 'line',
                'source': 'states',
                'layout': {},
                'paint': {
                    'line-color': '#05f1fc',
                    'line-width': 1
                }
            });

           


        }).catch((error)=>{})
      
    },

    getVectorData() {
      let that = this;
       let param = {
        "columnId": 1744,
        "token": localStorage.getItem("token")
      }
       axios.post(webConfig.DMS_URL + '/content/getVectorData', qs.stringify(param), 
       {
          headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'token': localStorage.getItem("token")
          }
        })
        .then(function (response) {
            if(response.data.message == '无效token'){
              that.$message.success('token过期，请重新登录');
              that.$router.push({ path: '/' });
            }else{
              that.createVectorLayer(response.data);
            }
        })
        .catch(function (error) {
            console.log(error);
        });

    },
    createVectorLayer(vectorData) {
      let that = this;
      // console.log(vectorData);
      that.options = [];
      for (let o in vectorData.features[0].properties) {
          that.options.push({
            value: o,
            label: o,
          })
        }
      that.dataList = vectorData;
      if(window.mapboxMap.getSource('vector-data')){
        window.mapboxMap.getSource('vector-data').setData(vectorData);
      }else{
        window.mapboxMap.addSource('vector-data', {
          type: 'geojson',
          data: vectorData
        });
        window.mapboxMap.addLayer({
          'id': 'data-fill-layer',
          'type': 'fill',
          'source': 'vector-data',
          'layout': {},
          'paint': {
              'fill-color': 'rgba(244,104,41,1)', // 面填充颜色
              'fill-opacity': 0.3 // 面填充透明度
          }
        });
        window.mapboxMap.addLayer({
          'id': 'data-line-layer',
          'type': 'line',
          'source': 'vector-data',
          'layout': {},
          'paint': {
              'line-color': 'rgba(244,104,41,1)', // 线颜色
              'line-width': 2 // 线宽度
          }
        });
       
        window.mapboxMap.addLayer({
          'id': 'data-symbol-layer',
          'type': 'symbol',
          'source': 'vector-data',
          "layout": {
            "text-field": this.fontText, // 正确使用 text-field 属性
            // "text-font": ["Open Sans Bold", "Arial Unicode MS Bold"], // 设置字体
            "text-size": 10, // 设置字体大小（可选）
            "text-anchor": "top", // 设置文本锚点（可选）
            "text-offset": [0, 0.6], // 设置文本偏移量（可选）
            "text-allow-overlap": false, // 是否允许文本重叠（可选）
          },
          "paint": {
            "icon-color":"#fff",
            "text-color":"#000"
          }
        });
      }
    },
    handleSelChange(){
      // 在每个字段后面添加换行符
      const withNewlines = this.selectText.reduce((acc, item, index, array) => {
        acc.push(["get", item]);
        if (index < array.length - 1) {
          acc.push("\n");
        }
        return acc;
      }, []);
      this.fontText = ["concat", ...withNewlines];
      this.changeTextField(this.fontText);
    },
    // 动态改变文本字段内容（例如，改为显示名称）
    changeTextField(newField) {
        window.mapboxMap.setLayoutProperty('data-symbol-layer', 'text-field', newField);
    }
  }
};
</script>

<style>
/*节点标签样式 */
.custom-popup {
  z-index: 9;
}
.more{
  float:right;
  cursor: pointer;
  transition: color 0.2s;
}
.more:hover {
  color: #00A8FF;
}
</style>

<style lang="less" scoped>
/deep/ .el-select__wrapper{
  min-height: 30px !important;
}
// 隐藏地图控件（mapboxgl-ctrl-bottom-left）
/deep/.mapboxgl-ctrl-bottom-left div{
  display:none !important;
}
/deep/.mapboxgl-ctrl{
    margin: 0 10px 50px 0 !important;
}
/deep/.el-divider--horizontal{
  margin: 0 !important;
  height: initial !important;
}
/* 新增：辖区名称样式 */
/deep/.area-name {
  position: absolute;
  background: rgba(0,0,0,0.6);
  color: white;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 14px;
  pointer-events: none; /* 不影响鼠标悬浮 */
  transform: translate(-50%, -50%);
  white-space: nowrap;
}

#mapContainer {
  width: 100%;
  height: 100%;
}

.tips {
    position: absolute;
    z-index: 1000;
    color: #fff;
    bottom: 0;
    // left: 45%;
    width: 100%;
    text-align: center;
    padding: 10px 20px;
    background: #063f798a;
    // border-radius: 40px 40px 0px 0;
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px);
}
.right-btn{
  position: absolute;
  z-index: 1000;
  bottom: 156px;
  right: 10px;
  text-align: center;
  // padding: 6px;
  background: #ffffff;
  box-shadow: 0 0 0 2px #0000001a;
  border-radius: 4px;
  display: grid;
  // gap: 8px;
  .icon {
    cursor: pointer;
    padding: 6px;
    &:hover{
      background: #e6e6e6;
    }
  }
  .icon:first-child {
    cursor: pointer;
    padding: 6px;
    &:hover{
      background: #e6e6e6;
      border-radius: 4px 4px 0px 0px;
    }
  }
  .icon:last-child {
    cursor: pointer;
    padding: 6px;
    &:hover{
      background: #e6e6e6;
      border-radius: 0px 0px 4px 4px;
    }
  }
  
}

.select-item{
    position: absolute;
    z-index: 1000;
    bottom: 156px;
    right: 50px;
    background: #01346f99;
    border-radius: 6px;
}

/* 十字准线样式 */
.map-center-crosshair {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 40px;
  height: 40px;
  // width: 100%;
  //height: 100%;
  /* 禁止点击，不影响地图交互 */
  pointer-events: none;
  /* 居中偏移 */
  transform: translate(-50%, -50%);
  z-index: 1;
}

/* 横线 + 竖线 */
.map-center-crosshair::before,
.map-center-crosshair::after {
  content: '';
  position: absolute;
  background: rgba(255, 0, 0, 0.7); /* 红色半透明 */
}
/* 竖线 */
.map-center-crosshair::before {
  width: 4px;
  height: 100%;
  left: 50%;
  transform: translateX(-50%);
}
/* 横线 */
.map-center-crosshair::after {
  width: 100%;
  height: 4px;
  top: 50%;
  transform: translateY(-50%);
}

</style>
