<template>
  <div>
    <div class="switch-button-open" @click="handlerOpen" v-if="!isOpen">
      <img src="/display/switch-button.png" />
    </div>
    <div class="switch-button-close" @click="handlerOpen" v-if="isOpen">
      <img src="/display/switch-button-active.png" />
    </div>
    <div class="case-tree-container" v-if="!isOpen">
      <div class="title">
        <a-tooltip placement="top">
          <template #title>
            <span>点击图层列表地图移动到初始位置</span>
          </template>
          <span @click="resetLocation">图层列表</span>
        </a-tooltip>
        <a-popover placement="right">
          <template #title>
            <span>图层列表设置</span>
          </template>
          <template #content>
            <PopoverContent
              ref="popoverContentRef"
              @changeFillLayerOpacity_tuceng="changeFillLayerOpacity_tuceng"
              @changeFillLayerOpacity_yingxiang="changeFillLayerOpacity_yingxiang"
              @changeYingxiangTreeMenu="changeYingxiangTreeMenu"
            />
          </template>
          <SettingOutlined style="margin-left: 10px; font-size: 20px" />
        </a-popover>
      </div>
      <div class="case-tree">
        <a-input-search
          v-model:value="searchValue"
          style="margin-bottom: 8px; width: 315px"
          placeholder="搜索"
        />
        <a-directory-tree
          v-model:expandedKeys="expandedKeys"
          v-model:selectedKeys="selectedKeys"
          v-model:checkedKeys="checkedKeys"
          checkable
          :tree-data="treeData"
          @select="onSelect"
          @check="onCheck"
          @expand="onExpand"
          :auto-expand-parent="autoExpandParent"
        >
          <template #title="{ title }">
            <span v-if="title?.indexOf(searchValue) > -1">
              {{ title?.substring(0, title?.indexOf(searchValue)) }}
              <span style="color: #f50">{{ searchValue }}</span>
              {{ title?.substring(title?.indexOf(searchValue) + searchValue?.length) }}
            </span>
            <span v-else>{{ title }}</span>
          </template>
        </a-directory-tree>
      </div>
    </div>
    <!-- 时间轴 -->
    <!-- <div class="timeLineBox">
      <TimeLine @handleNowValueChange="handleNowValueChange" />
    </div> -->
    <div>
      <MapComponent
        ref="mapboxComponentRef"
        :style="{
          position: 'absolute',
          height: `calc(100vh - 90px)`,
          width: `100%`,
          marginLeft: '6px',
          top: '0px',
          left: '0px',
          zIndex: '0',
        }"
        @handleOpenImage="handleOpenImage"
        @getDetailByFeature="getDetailByFeature"
      />
    </div>

    <ImageModal
      v-if="modalOpen"
      :tableData3_tupian="tableData3_tupian"
      :modalImage="modalImage"
      @closeImageModal="closeImageModal"
    />

    <div
      class="attribute"
      :style="{
        height: isMinusAttributeWindow ? '540px' : '30px',
      }"
      v-if="showAttributeWindow"
    >
      <span class="span-title">详细信息</span>
      <a-tooltip placement="top">
        <template #title>
          <span>按下空格快速切换</span>
        </template>
        <a-button class="span-button-minus" type="link" @click="minusAttributeWindow">
          <MinusOutlined v-if="isMinusAttributeWindow" style="color: black" />
          <ExpandAltOutlined
            v-if="!isMinusAttributeWindow"
            :style="{ fontSize: '17px', color: 'black' }"
          />
        </a-button>
      </a-tooltip>
      <a-button class="span-button-close" type="link" @click="closeAttributeWindow">
        <CloseOutlined style="color: black" />
      </a-button>
      <AttributeWindow
        v-if="isMinusAttributeWindow"
        :showAttributeFeature="showAttributeFeature"
        :initNameList="initNameList"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch, onMounted, onBeforeUnmount } from 'vue';
  import { BasicTree, TreeItem, TreeActionType } from '@/components/Tree';
  import {
    CloseOutlined,
    ExpandAltOutlined,
    MinusOutlined,
    LeftOutlined,
    RightOutlined,
    SettingOutlined,
  } from '@ant-design/icons-vue';
  import type { TreeProps } from 'ant-design-vue';
  // vben
  import { useMessage } from '@/hooks/web/useMessage';
  // 组件
  import MapComponent from '@/views/demo/system/geoservermanagement/clound/mapComponent.vue';
  import TimeLine from './TimeLine.vue';
  import AttributeWindow from './AttributeWindow.vue';
  import ImageModal from './ImageModal.vue';
  import PopoverContent from './PopoverContent.vue';
  import {
    AchievementManageListTask,
    AchievementManageListDroneShpImageexif,
    GeoTiffManagerLoadPage,
    getGeomData,
    ShpGeoLayerLoadPage,
    getDataTableRecord,
  } from '@/api/demo/system';
  import { getLoad } from '@/api/sys/sysDataItemDetail';
  import { prepareTreeData, yingxiangdata } from './util';
  import dayjs from 'dayjs';
  import proj4 from 'proj4';
  // 图片路径拼接
  import { getAppEnvConfig } from '@/utils/env';

  proj4.defs(
    'EPSG:4548',
    '+proj=tmerc +lat_0=37.56666666666666 +lon_0=126.93333333333333 +k=1 +x_0=200000 +y_0=500000 +ellps=bessel +towgs84=-119.819,-78.445,-112.283,0,0,0,0 +units=m +no_defs',
  );

  const { VITE_GLOB_API_URL } = getAppEnvConfig();
  const VITE_GLOB_API_URL_VAR = ref<String>(VITE_GLOB_API_URL + '/');

  const { createMessage } = useMessage();

  const selectedKeys = ref<string[]>([]);
  const expandedKeys = ref<string[]>(['1', '2', '3']);
  const checkedKeys = ref<string[]>([]);
  const treeData: any = ref(prepareTreeData);
  let tableData1: any = [];
  let tableData2: any = [];
  let tableData3: any = [];
  let tuceng_uniqueKeysArray: any = [];
  let yingxiang_uniqueKeysArray: any = [];
  let hangfei_uniqueKeysArray: any = [];
  const tableData3_tupian: any = ref([]);

  let tableData1_id_list: any = [];
  let tableData2_id_list: any = [];
  let tableData3_id_list: any = [];

  let startTime = dayjs().startOf('year').format('YYYY-MM-DD HH:mm:ss');
  let endTime = dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss');

  // 右边树的数据-----------------------------------------------------------
  let searchKeyVlaue: any = [];
  function fetch() {
    // 搜索用的键值对
    searchKeyVlaue = [];
    // 矢量图层
    ShpGeoLayerLoadPage({
      page: 1,
      limit: 10000,
    }).then((res) => {
      tableData1 = res.items;
      res.items.forEach((item) => {
        tableData1_id_list.push(item.id);
      });
      treeData.value[0].children = [];
      // 矢量图层-第二层
      tuceng_uniqueKeysArray = ['临沂市', '地方区县'];
      tuceng_uniqueKeysArray.forEach((array) => {
        treeData.value[0].children.push({
          key: array,
          title: array,
          children: [],
        });
        searchKeyVlaue.push({ title: array, key: treeData.value[0].key });
      });

      // 矢量图层-第三层
      res.items.forEach((item1) => {
        if (item1.countyname == '临沂市') {
          treeData.value[0].children[0].children.push({
            key: item1.id,
            title: item1.serverName,
          });
          searchKeyVlaue.push({ title: item1.serverName, key: '临沂市' });
        }
        if (item1.countyname != '临沂市') {
          treeData.value[0].children[1].children.push({
            key: item1.id,
            title: item1.serverName,
          });
          searchKeyVlaue.push({ title: item1.serverName, key: '地方区县' });
        }
      });
    });
    // 历史影像
    GeoTiffManagerLoadPage({
      page: 1,
      limit: 10000,
    }).then((res) => {
      // 初始化
      // res.items = yingxiangdata;
      res.items = res.items.sort((a, b) => dayjs(b.dateDir) - dayjs(a.dateDir));
      tableData2 = res.items;
      res.items.forEach((item) => {
        tableData2_id_list.push(item.id);
      });
      treeData.value[1].children = [];

      // 历史影像-第二层
      // if (
      //   popoverContentRef.value == undefined ||
      //   popoverContentRef.value.yingxiangTreeMenu == '0'
      // ) {
      // 按照时间分类
      let dateDirArray: any = [];
      res.items.forEach((item) => {
        dateDirArray.push({
          key: item.dateDir,
        });
      });
      // 不重复的时间
      yingxiang_uniqueKeysArray = Array.from(new Set(dateDirArray.map((item) => item.key))).sort(
        (a, b) => dayjs(b) - dayjs(a),
      );
      // 转换时间数组(年份-周数)
      yingxiang_uniqueKeysArray = yingxiang_uniqueKeysArray.map(convertToYearWeek);
      yingxiang_uniqueKeysArray = [...new Set(yingxiang_uniqueKeysArray)];

      yingxiang_uniqueKeysArray.forEach((array) => {
        // 分解
        const [year, week] = array.split('-').map(Number);
        // 获取输入年周的起始和最后时间
        const weekRange = getWeekRange(year, week);
        treeData.value[1].children.push({
          key: array,
          title: year + '年 第' + week + '周 ' + weekRange.start + '至' + weekRange.end,
          children: [],
        });
        searchKeyVlaue.push({
          title: year + '年 第' + week + '周 ' + weekRange.start + '至' + weekRange.end,
          key: treeData.value[1].key,
        });
      });
      // 历史影像-第三层
      // res.items.forEach((item1) => {
      //   treeData.value[1].children.forEach((item2) => {
      //     if (convertToYearWeek(item1.dateDir) === item2.key) {
      //       item2.children.push({
      //         key: item1.id,
      //         title: item1.layerName,
      //       });
      //       searchKeyVlaue.push({ title: item1.layerName, key: item2.key });
      //     }
      //   });
      // });
      // } else {
      //   let countrynameArray: any = [];
      //   // 按照区县分类
      //   res.items.forEach((item) => {
      //     // 分割路径
      //     let parts = item.tiffPath.split('\\');
      //     if (parts.length <= 1) {
      //       parts = item.tiffPath.split('/');
      //     }
      //     // 提取区县名称
      //     const countryname = parts[parts.length - 2];
      //     countrynameArray.push({
      //       key: countryname,
      //     });
      //   });
      //   yingxiang_uniqueKeysArray = Array.from(new Set(countrynameArray.map((item) => item.key)));
      //   yingxiang_uniqueKeysArray.forEach((array) => {
      //     treeData.value[1].children.push({
      //       key: array,
      //       title: array,
      //       children: [],
      //     });
      //     searchKeyVlaue.push({ title: array, key: treeData.value[1].key });
      //   });
      //   // 历史影像-第三层
      //   res.items.forEach((item1) => {
      //     treeData.value[1].children.forEach((item2) => {
      //       let parts = item1.tiffPath.split('\\');
      //       if (parts.length <= 1) {
      //         parts = item1.tiffPath.split('/');
      //       }
      //       // 提取区县名称
      //       const countryname = parts[parts.length - 2];
      //       if (countryname === item2.key) {
      //         item2.children.push({
      //           key: item1.id,
      //           title: item1.layerName,
      //         });
      //         searchKeyVlaue.push({ title: item1.layerName, key: item2.key });
      //       }
      //     });
      //   });
      // }
    });

    // 航飞图片
    AchievementManageListTask({
      pageIndex: 1,
      pageSize: 10000,
    }).then((res) => {
      // 初始化
      tableData3_tupian.value = [];
      treeData.value[2].children = [];
      // 航飞图片-第二层
      let taskDateArray: any = [];
      res.items.forEach((item) => {
        taskDateArray.push({
          key: item.taskDate,
        });
      });
      hangfei_uniqueKeysArray = Array.from(new Set(taskDateArray.map((item) => item.key)));
      hangfei_uniqueKeysArray.sort((a, b) => dayjs(b) - dayjs(a));
      hangfei_uniqueKeysArray.forEach((array) => {
        treeData.value[2].children.push({
          key: array,
          title: array,
          children: [],
        });
        searchKeyVlaue.push({ title: array, key: treeData.value[2].key });
      });
      // 航飞图片-第三层
      res.items.forEach((item1) => {
        treeData.value[2].children.forEach((item2) => {
          if (item1.taskDate === item2.key) {
            item2.children.push({
              key: item1.id,
              title: item1.workPosition + '_' + item1.flyer + ' (' + item1.imageCount + ')',
            });
            searchKeyVlaue.push({
              title: item1.workPosition + '_' + item1.flyer + ' (' + item1.imageCount + ')',
              key: item2.key,
            });
          }
        });
      });
      // 航飞图片-任务数据初始化用于左侧树复选时使用
      tableData3 = res.items;
      res.items.forEach((item) => {
        tableData3_id_list.push(item.id);
      });
    });
  }
  // 右边树的数据刷新
  function changeYingxiangTreeMenu() {
    fetch();
  }
  // 搜索右边树的数据
  const searchValue = ref<string>('');
  const autoExpandParent = ref<boolean>(true);
  const dataList: TreeProps['treeData'] = [];

  const onExpand = (keys: string[]) => {
    expandedKeys.value = keys;
    autoExpandParent.value = false;
  };

  watch(searchValue, (value) => {
    if (value) {
      let expanded = searchKeyVlaue.filter((item) => item.title.indexOf(value) > -1);
      expanded = Array.from(new Set(expanded.map((item) => item.key)));
      expandedKeys.value = expanded;
      searchValue.value = value;
      autoExpandParent.value = true;
    } else {
      expandedKeys.value = ['1', '2', '3'];
    }
  });

  // 获取年份-周数
  function convertToYearWeek(dateStr) {
    const date = dayjs(dateStr, 'YYYYMMDD');
    // 返回格式化的字符串
    return `${date.year()}-${getWeekOfYear(date)}`;
  }

  // 每周从周一开始
  function getWeekOfYear(date) {
    const firstDayOfYear = dayjs(date).startOf('year');
    const firstMondayOfYear =
      firstDayOfYear.day() === 1
        ? firstDayOfYear
        : firstDayOfYear.add(1 - firstDayOfYear.day(), 'day');
    const diffInDays = date.diff(firstMondayOfYear, 'days');
    const weekNumber = Math.floor(diffInDays / 7) + 1;
    return weekNumber;
  }

  // 指定年份和周数的起始后终结日期
  function getWeekRange(year, week) {
    const startOfYear = dayjs(`${year}-01-01`);
    const startOfWeek = startOfYear.add((week - 1) * 7, 'day');
    const endOfWeek = startOfWeek.add(6, 'day');
    return {
      start: startOfWeek.format('MM-DD'),
      end: endOfWeek.format('MM-DD'),
    };
  }

  // 地图ref-----------------------------------------------------------
  const mapboxComponentRef = ref();
  let checkedKeys_now: any;
  // 树选中
  const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
    // // 选中-添加到树里
    // if (!checkedKeys_now?.includes(info.node.key)) {
    //   if (!['1', '2', '3'].includes(info.node.key)) {
    //     if (hangfei_uniqueKeysArray.includes(info.node.key)) {
    //       treeData.value[2].children.forEach((item) => {
    //         if (item.key == info.node.key) {
    //           item.children.forEach((child) => {
    //             checkedKeys.value.push(child.key);
    //           });
    //         }
    //       });
    //       onCheck(checkedKeys.value);
    //     } else {
    //       checkedKeys.value.push(info.node.key);
    //       onCheck(checkedKeys.value);
    //     }
    //   }
    // }
    // 点击树选项是否跳转：
    if (
      !['1', '2', '3'].includes(info.node.key) ||
      hangfei_uniqueKeysArray.includes(info.node.key)
    ) {
      if (popoverContentRef.value == undefined || popoverContentRef.value.treeRadio) {
        // 矢量图层跳转
        if (tuceng_uniqueKeysArray.includes(info.node.parent.key)) {
          let move = tableData1.find((data) => {
            return info.node.key == data.id;
          });
          if (move) {
            getGeomData({ dataTable: move.dataTable })
              .then((res) => {
                if (res) {
                  let st: any = res.slice(6, -1);
                  st = st.split(' ');
                  if (move.countyname == '临沂市') {
                    mapboxComponentRef.value.handlerLocation([st[0], st[1]], 7.848587811931849);
                  } else {
                    mapboxComponentRef.value.handlerLocation([st[0], st[1]], 9.5);
                  }
                }
              })
              .catch((error) => {
                console.log(error);
              });
          }
        }
        // 历史影像跳转
        if (yingxiang_uniqueKeysArray.includes(info.node.parent.key)) {
          let move = tableData2.find((data) => {
            return info.node.key == data.id;
          });
          if (move) {
            let bbox = getBboxFromUrl(move.accessUrl);
            let lngLat = getCenterPoint(bbox);
            // 检测坐标系
            const result = isProjectedCoordinates(parseFloat(lngLat[0]), parseFloat(lngLat[1]));
            if (result) {
              lngLat[0] = result[0];
              lngLat[1] = result[1];
            }
            mapboxComponentRef.value.handlerLocation(lngLat, 10);
          }
        }
        // 航飞图片跳转
        if (hangfei_uniqueKeysArray.includes(info.node.parent.key)) {
          let move = tableData3.find((data) => {
            return data.id == info.node.key;
          });
          if (move) {
            let st: any = move.geometry.slice(6, -1);
            st = st.split(' ');
            mapboxComponentRef.value.handlerLocation([st[0], st[1]], 10);
          }
        }
      }
    }
  };

  let filter_tuceng: any = [];
  let filter_yingxiang: any = [];
  let filter_hangfei = [];
  let filter_tuceng_old: any = [];
  let filter_yingxiang_old: any = [];
  let tableData3_choose_new: any = [];
  let tableData3_choose_old: any = [];

  // 树复选框选中
  const onCheck: TreeProps['onCheck'] = (checkedKeys) => {
    // console.log(checkedKeys);
    checkedKeys_now = checkedKeys;
    filter_tuceng = [];
    filter_yingxiang = [];
    tableData3_choose_new = [];

    // 清除全部图层
    if (!checkedKeys_now || checkedKeys_now.length == 0) {
      tableData1?.forEach((data) => {
        mapboxComponentRef.value.clearTaskLayer(data.dataTable);
      });
      tableData2?.forEach((data) => {
        mapboxComponentRef.value.clearTaskLayer(data.layerName);
      });
      yingxiang_uniqueKeysArray?.forEach((data) => {
        mapboxComponentRef.value.clearTaskLayer(data);
      });
      mapboxComponentRef.value.clearTaskLayer('AchievementManagerRaster');
      // 历史记录清零
      filter_tuceng_old = [];
      filter_yingxiang_old = [];
    } else {
      // 遍历筛选
      let checkedKeys_move = checkedKeys_now.filter(
        (item) =>
          !['1', '2', '3']
            .concat(tuceng_uniqueKeysArray)
            .concat(yingxiang_uniqueKeysArray)
            .concat(hangfei_uniqueKeysArray)
            .includes(item),
      );
      // 影像管理-第二层-独立处理
      let checkedKeys_yingxiang = checkedKeys_now.filter((item) =>
        yingxiang_uniqueKeysArray.includes(item),
      );
      filter_yingxiang = checkedKeys_yingxiang.map((key) => ({ layerName: key }));
      checkedKeys_move?.forEach((checkedKey, index) => {
        // 图层管理-图层
        if (tableData1_id_list.includes(checkedKey)) {
          tableData1.forEach((data) => {
            if (checkedKey == data.id) {
              filter_tuceng.push(data);
            }
          });
        }
        // 影像管理-图层
        else if (tableData2_id_list.includes(checkedKey)) {
          tableData2.forEach((data) => {
            if (checkedKey == data.id) {
              // 时间轴筛选数据
              // if (dayjs(startTime).format('YYYY-MM-DD') == dayjs(endTime).format('YYYY-MM-DD')) {
              //   filter_yingxiang.push(data);
              // } else if (
              //   // dayjs(startTime).isBefore(data.createTime) &&
              //   dayjs(endTime).isAfter(dayjs(data.dateDir))
              // ) {
              //   filter_yingxiang.push(data);
              // }
              // 只添加没被单独处理的第二层的子项
              if (!checkedKeys_yingxiang.includes(convertToYearWeek(data.dateDir))) {
                filter_yingxiang.push(data);
              }
            }
          });
        }
        // 航飞图片-图层
        else if (tableData3_id_list.includes(checkedKey)) {
          tableData3_choose_new.push(checkedKey);
        }
      });

      // 图层管理-添加删除图层
      if (filter_tuceng.length > 0) {
        if (!arraysEqual(filter_tuceng_old, filter_tuceng)) {
          let remove = filter_tuceng_old.filter((item) => !filter_tuceng.includes(item));
          remove.forEach((data) => {
            mapboxComponentRef.value.clearTaskLayer(data.dataTable);
          });
          let add = filter_tuceng.filter((item) => !filter_tuceng_old.includes(item));
          mapboxComponentRef.value.GeoserverManagementRaster(
            add,
            null,
            null,
            // 是否移动
            false,
            // 透明度
            fillOpacity_tuceng.value,
          );
        }
      } else {
        tableData1.forEach((data) => {
          mapboxComponentRef.value.clearTaskLayer(data.dataTable);
        });
      }

      // 影像管理-添加删除图层
      if (filter_yingxiang.length > 0) {
        if (!arraysEqual(filter_yingxiang_old, filter_yingxiang)) {
          let remove = filter_yingxiang_old.filter((oldItem) => {
            return !filter_yingxiang.some((newItem) => newItem.layerName === oldItem.layerName);
          });
          remove?.forEach((data) => {
            mapboxComponentRef.value.clearTaskLayer(data.layerName);
          });
          let add = filter_yingxiang.filter((newItem) => {
            return !filter_yingxiang_old.some((oldItem) => oldItem.layerName === newItem.layerName);
          });
          mapboxComponentRef.value.GeoTiffManagerRaster(
            add,
            null,
            null,
            // 是否移动
            false,
            // 透明度
            fillOpacity_yingxiang.value,
          );
        }
      } else {
        tableData2.forEach((data) => {
          mapboxComponentRef.value.clearTaskLayer(data.layerName);
        });
        yingxiang_uniqueKeysArray.forEach((data) => {
          mapboxComponentRef.value.clearTaskLayer(data);
        });
      }

      // 记录成旧数据，用于下次比对
      filter_tuceng_old = filter_tuceng;
      filter_yingxiang_old = filter_yingxiang;

      // 航飞图片-图层、任务-添加删除图层
      // 新选择的图片添加上
      const addResult = tableData3_choose_new?.filter(
        (item) => !tableData3_choose_old.includes(item),
      );
      addResult.forEach((r) => {
        tableData3.forEach((data) => {
          if (r == data.id) {
            getFilter_hangfeiArray(data);
          }
        });
      });
      // 被取消选择的选项的图片过滤掉
      const removeResult = tableData3_choose_old?.filter(
        (item) => !tableData3_choose_new.includes(item),
      );
      removeResult.forEach((r) => {
        filter_hangfei = filter_hangfei.filter((item) => {
          return item.taskId != r;
        });
      });
      // 延迟加载到地图中
      setTimeout(() => {
        if (filter_hangfei.length > 0) {
          handlerUpdateTaskLayerData(filter_hangfei);
        } else {
          mapboxComponentRef.value.clearTaskLayer('AchievementManagerRaster');
        }
        // 记录成旧数据，用于下次比对
        tableData3_choose_old = tableData3_choose_new;
      }, 500);
    }
  };

  // 对比数据
  function arraysEqual(a, b) {
    if (a.length !== b.length) return false;
    for (let i = 0; i < a.length; i++) {
      if (a[i] !== b[i]) return false;
    }
    return true;
  }

  // 航飞图片-任务
  async function getFilter_hangfeiArray(data) {
    let res = await AchievementManageListDroneShpImageexif({
      pageIndex: 1,
      pageSize: data.imageCount,
      taskId: data.id,
    });
    res.items.forEach((item) => {
      filter_hangfei.push(item);
    });
    return filter_hangfei;
  }

  // 航飞图片-无人机图层
  function handlerUpdateTaskLayerData(tasklist) {
    let taskLayerGeoJson = {
      type: 'FeatureCollection',
      features: [],
    };
    let lngList: any = [];
    let latList: any = [];
    tasklist?.forEach((item, index) => {
      let st: any = item.geometry.slice(6, -1);
      st = st.split(' ');
      // 检测坐标系
      const result = isProjectedCoordinates(parseFloat(st[0]), parseFloat(st[1]));
      if (result) {
        st[0] = result[0];
        st[1] = result[1];
      }
      lngList.push(parseFloat(st[0]));
      latList.push(parseFloat(st[1]));
      let feature: any = {
        type: 'Feature',
        geometry: {
          type: 'Point',
          coordinates: [parseFloat(st[0]), parseFloat(st[1])],
        },
        properties: {
          id: item.id,
          path: item.path,
          lng: parseFloat(st[0]),
          lat: parseFloat(st[1]),
          uploadTime: item.uploadTime,
          remark: item.remark,
          intact: item.intact,
          userId: item.userId,
          name: item.name,
          taskId: item.taskId,
          workPosition: item.workPosition,
          flyer: item.flyer,
          flyTime: item.flyTime,
          // taskName: taskName,
          taskName: getTaskNameBytaskId(item.taskId),
          // model: item.model,
        },
      };
      taskLayerGeoJson.features.push(feature);
    });
    // 航飞图片-图层
    mapboxComponentRef.value.AchievementManagerRaster(taskLayerGeoJson, null, null, false);
  }
  // 投影坐标系=>地理坐标系
  function isProjectedCoordinates(x, y) {
    // 检查是否在地理坐标系的范围内
    const isGeoXInRange = -180 <= x && x <= 180;
    const isGeoYInRange = -90 <= y && y <= 90;
    // 定义坐标系
    const fromCrs = 'EPSG:3857'; // 假设输入坐标是 Web Mercator
    const toCrs = 'EPSG:4326'; // 目标坐标系是地理坐标系
    // 如果不在地理坐标系范围内，则认为是投影坐标系
    if (!isGeoXInRange || !isGeoYInRange) {
      // 转换坐标
      const transformer = Transformer.fromCrs(fromCrs, toCrs);
      return transformer.transform([x, y]);
    } else {
      return false;
    }
  }

  // 从参数中获取 bbox 的值
  function getBboxFromUrl(url) {
    const urlObj = new URL(url);
    const params = new URLSearchParams(urlObj.search);
    const bbox = params.get('bbox');
    return bbox;
  }

  // 计算中心点
  function getCenterPoint(bbox) {
    const coords = bbox.split(',').map((coord) => parseFloat(coord));
    const [minLon, minLat, maxLon, maxLat] = coords;
    const centerLon = (minLon + maxLon) / 2;
    const centerLat = (minLat + maxLat) / 2;
    return [centerLon, centerLat];
  }

  // 航飞图片-获取任务名称
  function getTaskNameBytaskId(taskid) {
    let resultName = '';
    tableData3.forEach((element) => {
      if (element.id == taskid) {
        resultName = element.taskName;
      }
    });
    return resultName;
  }

  // 时间轴发生改变返回值
  function handleNowValueChange(value) {
    // console.log(421, value);
    startTime = dayjs(value[0]).startOf('year').format('YYYY-MM-DD HH:mm:ss');
    endTime = dayjs(value[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss');
    // isTimeMove = true;
    onCheck(checkedKeys_now);
  }

  // 设置ref
  const popoverContentRef = ref();
  // 矢量图层-动态调整图层的透明度
  const fillOpacity_tuceng = ref(1);
  function changeFillLayerOpacity_tuceng(value) {
    fillOpacity_tuceng.value = parseFloat(value);
    mapboxComponentRef.value.changeFillLayerOpacity(
      'GeoserverManagementRaster',
      filter_tuceng_old,
      value,
    );
  }
  // 历史影像-动态调整图层的透明度
  const fillOpacity_yingxiang = ref(1);
  function changeFillLayerOpacity_yingxiang(value) {
    fillOpacity_yingxiang.value = parseFloat(value);
    mapboxComponentRef.value.changeFillLayerOpacity(
      'GeoTiffManagerRaster',
      filter_yingxiang_old,
      value,
    );
  }

  // 图层列表收起放出
  const isOpen = ref(false);
  function handlerOpen() {
    isOpen.value = !isOpen.value;
  }
  // 点击图层列表地图恢复位置
  function resetLocation() {
    mapboxComponentRef.value.handlerLocation(
      [118.30207505530701, 35.30123435040745],
      7.848587811931849,
    );
  }

  // 字典-详细信息
  const initNameList: any = ref([]);
  function getSysDataItemDetail() {
    getLoad({ code: 'geoservermanagement' }).then((res) => {
      initNameList.value = res;
    });
  }

  onMounted(() => {
    fetch();
    // 字典-详细信息
    getSysDataItemDetail();
    // 在组件挂载时添加监听器
    addEventListener();
  });

  // 在组件卸载时移除监听器
  onBeforeUnmount(() => {
    removeEventListener();
  });

  // 点击矢量图层展示点击块的属性------------------------------------------------------------
  const showAttributeWindow = ref(false);
  const isMinusAttributeWindow = ref(true);
  const showAttributeFeature: any = ref();

  const getDetailByFeature = (feature) => {
    getDataTableRecord({
      id: feature.properties.id,
      dataTable: feature.source,
    }).then((res) => {
      showAttributeFeature.value = res;
      showAttributeWindow.value = true;
      if (!showAttributeWindow.value) {
        isMinusAttributeWindow.value = true;
      }
    });
  };
  const closeAttributeWindow = () => {
    showAttributeWindow.value = false;
    isMinusAttributeWindow.value = true;
  };
  const minusAttributeWindow = () => {
    isMinusAttributeWindow.value = !isMinusAttributeWindow.value;
  };

  // 添加键盘事件监听器
  const addEventListener = () => {
    window.addEventListener('keydown', handleKeydown);
  };
  // 移除键盘事件监听器
  const removeEventListener = () => {
    window.removeEventListener('keydown', handleKeydown);
  };
  // 处理按键按下事件
  const handleKeydown = (event: KeyboardEvent) => {
    if (event.code == 'Space') {
      minusAttributeWindow();
    }
  };

  // 点击地图上的无人机图标后展示图片------------------------------------------------------------
  // 窗口
  const modalOpen = ref(false);
  const modalImage: any = ref({});
  const closeImageModal = () => {
    modalOpen.value = false;
  };

  // 打开窗口
  const handleOpenImage = (properties) => {
    modalOpen.value = true;
    tableData3_tupian.value = filter_hangfei;
    // 正则表达式验证函数
    modalImage.value = properties;
  };
</script>
<style type="less" scoped>
  ::v-deep .ant-tree-list {
    background: #041b36;
    color: #ffffff;
  }
  .case-tree-container {
    width: 360px;
    height: calc(100vh - 180px);
    position: absolute;
    background: #041b36;
    color: #155dd8;
    z-index: 1;
    bottom: 20px;
    left: 25px;
  }

  .title {
    display: flex;
    justify-content: center;
    width: 100%;
    height: 40px;
    background-image: url('/display/title.png');
    background-size: 100% 100%;
    line-height: 40px;
    text-indent: 18px;
    font-size: 18px;
    font-weight: bold;
    color: #ffffff;
  }

  .case-tree {
    padding: 10px 24px;
    /* overflow: auto; */
    max-height: 670px; /* 设置最大高度 */
    overflow-y: auto; /* 启用垂直滚动 */
  }

  .timeLineBox {
    position: absolute;
    z-index: 1;
    left: 420px;
    bottom: 20px;
    width: 1200px;
    height: 120px;
    border: 2px #155dd8;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 60px / 60px;
  }

  .switch-button-open {
    width: 50px;
    height: 100px;
    position: absolute;
    left: -10px;
    top: 50%;
    transform: translate(0, -50%);
    cursor: pointer;
    z-index: 999;
    img {
      width: 100%;
      height: 100%;
    }
  }

  .switch-button-close {
    width: 50px;
    height: 100px;
    position: absolute;
    left: -10px;
    top: 50%;
    z-index: 999;
    transform: translate(0, -50%);
    cursor: pointer;
    img {
      width: 100%;
      height: 100%;
    }
  }

  .toper {
    position: absolute;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    z-index: 1082;
    width: 100%;
    font-size: 40px;
    top: 0px;
    height: auto; /* 自动高度，适应内容 */
    background: rgba(0, 0, 0, 0.4);
    padding: 10px; /* 内边距，使文本不紧贴边框 */
  }

  .info-item {
    color: #ffffff;
    font-size: 30px; /* 后面三个项的字体大小 */
    margin-right: 30px; /* 每个 span 之间的间距 */
  }

  .info-item.solo {
    font-size: 40px; /* 第一个 span 的字体大小 */
    margin-bottom: 10px; /* 第一个 span 的底部间距 */
  }

  .info-row {
    display: flex; /* 使用 flex 布局使三个 span 排成一行 */
    flex-wrap: nowrap; /* 不允许换行 */
  }

  .info-row .info-item:last-child {
    margin-right: 0; /* 最后一个 span 不需要右边距 */
  }

  .leftOutlined {
    position: absolute;
    top: 40%;
    z-index: 1082;
    left: 0px;
    color: #ffffff;
    background-color: gray; /* 默认灰色背景 */
    border-radius: 50%; /* 圆形 */
    padding: 10px; /* 内边距 */
    margin: 5px; /* 外边距 */
    transition: background-color 0.3s ease; /* 平滑过渡 */
    cursor: pointer; /* 鼠标指针变为手型 */
    overflow: visible;
  }

  .rightOutlined {
    position: absolute;
    z-index: 1082;
    top: 40%;
    right: 0px;
    color: #ffffff;
    background-color: gray; /* 默认灰色背景 */
    border-radius: 50%; /* 圆形 */
    padding: 10px; /* 内边距 */
    margin: 5px; /* 外边距 */
    transition: background-color 0.3s ease; /* 平滑过渡 */
    cursor: pointer; /* 鼠标指针变为手型 */
  }

  .leftOutlined:hover {
    background-color: black; /* 鼠标悬停时背景颜色变为黑色 */
  }
  .rightOutlined:hover {
    background-color: black; /* 鼠标悬停时背景颜色变为黑色 */
  }

  .attribute {
    position: absolute;
    background-color: white;
    right: 10px;
    z-index: 1;
    top: 80px;
    width: 400px;
    height: 540px;
    border-radius: 10px;
  }

  .span-title {
    margin-left: 10px;
    color: rgba(0, 0, 0, 0.88);
    font-weight: 600;
    font-size: 20px;
    line-height: 1.5;
    word-wrap: break-word;
  }

  .span-button-minus {
    position: absolute;
    right: 50px;
  }

  .span-button-close {
    position: absolute;
    right: 10px;
  }
</style>
