<template>
  <div>
    <a-row ::gutter="0">
      <a-col :span="12">
        <BasicTable @register="registerTable" @row-click="handRowClick">
          <template #toolbar>
            <a-button type="primary" @click="updateGeoTiff">更新最新影像</a-button>
          </template>
        </BasicTable>
      </a-col>
      <a-col :span="12">
        <div>
          <MapComponent
            ref="mapboxComponentRef"
            style="
              position: absolute;
              top: 16px;
              left: 0px;
              height: calc(100vh - 112px);
              width: calc(85vh);
              z-index: 0;
            "
          />
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch, onMounted } from 'vue';
  // vben
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicTable, useTable } from '@/components/Table';
  import { columns, searchFormSchema } from './util';
  import MapComponent from '@/views/demo/system/geoservermanagement/clound/mapComponent.vue';
  // api
  import {
    GeoTiffManagerUpdateGeoTiff,
    GeoTiffManagerLoadPage,
    GeoTiffManagerGet,
  } from '@/api/demo/system';
  import proj4 from 'proj4';

  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 { createMessage } = useMessage();

  // 影像管理
  const [registerTable, { reload, getSelectRows }] = useTable({
    title: '影像管理',
    api: GeoTiffManagerLoadPage,
    columns: columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    showIndexColumn: true,
    useSearchForm: true,
    ellipsis: false,
    bordered: true,
    showTableSetting: true,
    handleSearchInfoFn(info) {
      return info;
    },
    immediate: false,
  });

  // 更新tiff影像
  const updateGeoTiff = () => {
    GeoTiffManagerUpdateGeoTiff()
      .then((res) => {
        if (res) {
          reload();
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  // 行选中
  const mapboxComponentRef = ref();
  function handRowClick(record) {
    allDataForClearMap.forEach((data) => {
      mapboxComponentRef.value.clearTaskLayer(data.layerName);
    });
    let bbox = getBboxFromUrl(record.accessUrl);
    let lngLat = getCenterPoint(bbox);
    console.log(lngLat);
    // 检测坐标系
    const result = isProjectedCoordinates(parseFloat(lngLat[0]), parseFloat(lngLat[1]));
    if (result) {
      lngLat[0] = result[0];
      lngLat[1] = result[1];
    }
    let chooseRows: any = [];
    chooseRows.push(record);
    mapboxComponentRef.value.GeoTiffManagerRaster(chooseRows, lngLat, 11, true);
  }

  function isProjectedCoordinates(x, y) {
    // 检查是否在地理坐标系的范围内
    const isGeoXInRange = -180 <= x && x <= 180;
    const isGeoYInRange = -90 <= y && y <= 90;
    // 定义坐标系
    const fromCrs1 = 'EPSG:3857'; // 假设输入坐标是 Web Mercator
    const fromCrs2 = 'EPSG:4548';
    const toCrs = 'EPSG:4326'; // 目标坐标系是地理坐标系
    // 如果不在地理坐标系范围内，则认为是投影坐标系
    if (!isGeoXInRange || !isGeoYInRange) {
      // 转换坐标
      // 根据输入坐标的范围来判断是哪个坐标系
      const fromCrs = isProjectedCoordinate(x, y) ? fromCrs2 : fromCrs1;
      return proj4(fromCrs, toCrs, [x, y]);
    } else {
      return false;
    }
  }

  const isProjectedCoordinate = (x, y) => {
    // 检查坐标是否符合 EPSG:4548 的大致范围
    const is4548XInRange = 0 <= x && x <= 1000000;
    const is4548YInRange = 0 <= y && y <= 6000000;
    return is4548XInRange && is4548YInRange;
  };

  // 从参数中获取 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];
  }

  // 用于去除分页后地图还有前一页的图层
  let allDataForClearMap: any = [];
  function forClearMap() {
    GeoTiffManagerLoadPage({
      page: 1,
      limit: 10000,
    }).then((res) => {
      allDataForClearMap = res.items;
    });
  }

  onMounted(() => {
    reload();
    // 用于去除分页后地图还有前一页的图层
    forClearMap();
  });
</script>
