<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="mapboxComponent"
            style="
              position: absolute;
              top: 16px;
              left: 0px;
              height: calc(100vh - 116px);
              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';

  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 mapboxComponent = ref();
  function handRowClick(record) {
    let bbox = getBboxFromUrl(record.accessUrl);
    let lngLat = getCenterPoint(bbox);
    mapboxComponent.value.GeoTiffManagerRaster(record, lngLat, 11);
  }

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

  onMounted(() => {
    reload();
  });
</script>
