<template>
  <div>
    <div class="search-box">
      <BasicForm
        @register="registerForm"
        :labelWidth="100"
        :schemas="searchFormSchema"
        :actionColOptions="{ span: 24 }"
      />
    </div>
    <a-row ::gutter="0">
      <a-col :span="tableSpan">
        <BasicTable @register="registerTable" @row-click="handRowClick">
          <!-- <template #expandedRowRender="{ record }">
            <span>{{ record.id }} </span>
          </template> -->
          <template #toolbar>
            <PermissionBtn @btn-event="onBtnClicked" />
          </template>
        </BasicTable>
      </a-col>
      <a-col :span="mapSpan">
        <div>
          <MapComponent
            ref="mapboxComponentRef"
            :style="{
              position: 'absolute',
              height: `calc(100vh - 185px)`,
              width: isFullScreen ? `100%` : `calc(83vh)`,
              marginLeft: isFullScreen ? '0px' : '16px',
              top: '0px',
              left: '0px',
              zIndex: '0',
            }"
            @handleOpenImage="handleOpenImage"
          />
          <div class="full-screen-button" :style="{ zIndex: 1 }">
            <a-tooltip placement="top">
              <template #title>
                <span>点击切换是否展示航飞任务表格</span>
              </template>
              <img
                v-if="!isFullScreen"
                @click="fullScreen"
                src="/statistical/full-scrren-button.png"
              />
              <img v-else @click="exitScreen" src="/statistical/full-scrren-button.png" />
            </a-tooltip>
          </div>
        </div>
      </a-col>
    </a-row>

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

<script lang="ts" setup>
  import { ref, watch, onMounted, computed } from 'vue';
  // vben
  import { useMessage } from '@/hooks/web/useMessage';
  import { BasicTable, useTable } from '@/components/Table';
  import { BasicForm, useForm } from '@/components/Form';
  import { columns, columnsRender, searchFormSchema_map, searchFormSchema_table } from './util';
  import MapComponent from '@/views/demo/system/geoservermanagement/clound/mapComponent.vue';
  import ImageModal from '@/views/demo/system/achievement/Display/ImageModal.vue';
  // api
  import {
    AchievementManageAddImageexif,
    AchievementManageIntactById,
    AchievementManageAddTask,
    AchievementManageListTask,
    AchievementManageListDroneShpImageexif,
  } from '@/api/demo/system';
  import proj4 from 'proj4';
  import dayjs from 'dayjs';
  // 图片路径拼接
  import { getAppEnvConfig } from '@/utils/env';
  const { VITE_GLOB_API_URL } = getAppEnvConfig();
  const VITE_GLOB_API_URL_VAR = ref<String>(VITE_GLOB_API_URL + '/');

  const { createMessage } = useMessage();

  // 全屏------------------------------------------------------------
  const isFullScreen = ref<Boolean>(false);
  const searchFormSchema = ref(searchFormSchema_table);
  const tableSpan = ref(12);
  const mapSpan = ref(12);

  // 全屏
  function fullScreen() {
    isFullScreen.value = true;
    tableSpan.value = 0;
    mapSpan.value = 24;
    searchFormSchema.value = searchFormSchema_map;
    setTimeout(() => {
      mapboxComponentRef.value.resize();
    }, 200);
  }
  // 半屏
  function exitScreen() {
    isFullScreen.value = false;
    tableSpan.value = 12;
    mapSpan.value = 12;
    searchFormSchema.value = searchFormSchema_table;
    setTimeout(() => {
      mapboxComponentRef.value.resize();
    }, 200);
  }

  // 左侧表格的搜索、表格和分页数据------------------------------------------------------------
  // 搜索条件
  const searchParams: any = ref({
    page: 1,
    limit: 10,
  });
  // 表格数据
  const tableData = ref([]);
  // 分页
  const tablePagination = ref({
    current: 1,
    pageSize: 10,
    size: 'small',
    defaultPageSize: 10,
    showSizeChanger: true,
    pageSizeOptions: ['10', '50', '80', '100'],
    showQuickJumper: true,
    total: 0,
  });

  // 搜索条件
  const [registerForm, { validate, getFieldsValue }] = useForm({
    labelWidth: 120,
    actionColOptions: { span: 4 },
    autoSubmitOnEnter: true,
    submitFunc: handleSubmit,
    resetFunc: handleReset,
  });

  // 航飞图片
  const [registerTable, { reload, getSelectRows, setTableData, setLoading }] = useTable({
    title: '航飞图片',
    columns: columns,
    showIndexColumn: true,
    useSearchForm: false,
    ellipsis: false,
    bordered: true,
    showTableSetting: false,
    autoCreateKey: true,
    canResize: true,
    expandRowByClick: true,
    accordion: true,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    handleSearchInfoFn(info) {
      return info;
    },
    immediate: false,
    pagination: tablePagination.value,
  });

  // 获取表格数据
  function getTableData(querys) {
    if (querys.tableBeginDate && querys.tableEndDate) {
      querys.beginDate = dayjs(querys.tableBeginDate).startOf('day').format('YYYY-MM-DD');
      querys.endDate = dayjs(querys.tableEndDate).endOf('day').format('YYYY-MM-DD HH:mm:ss');
    }
    querys = {
      ...querys,
      pageSize: querys.limit,
      pageIndex: querys.page,
    };
    // setLoading(true);
    AchievementManageListTask(querys).then((res) => {
      tableData.value = res.items;
      tablePagination.value.total = res.items.length;
      setTableData(tableData.value);
      // setLoading(false);
    });
  }

  // 查询
  function handleSubmit() {
    searchParams.value = getFieldsValue();
    searchParams.value.page = 1;
    searchParams.value.limit = tablePagination.value.pageSize;
    tablePagination.value.current = 1;
    const querys = Object.assign(searchParams.value);
    if (isFullScreen.value) {
      getTableData(querys);
      setTimeout(() => {
        handAll();
      }, 1000);
    } else {
      getTableData(querys);
    }
  }
  // 重置
  function handleReset() {
    searchParams.value = {
      page: 1,
      limit: 10,
    };
    if (isFullScreen.value) {
      getTableData(searchParams.value);
      setTimeout(() => {
        handAll();
      }, 1000);
    } else {
      getTableData(searchParams.value);
    }
  }

  // 行选中后在地图上显示无人机图标------------------------------------------------------------
  // 行选中
  const mapboxComponentRef = ref();
  const tableData3_tupian = ref([]);

  function handRowClick(record) {
    if (record && record.imageCount == 0) {
      createMessage.warn('当前点击的任务无航飞图片');
      return;
    }
    // taskid筛选
    let querys: any = getFieldsValue();
    if (record.id) {
      querys.taskId = record.id;
      querys.pageIndex = 1;
      querys.pageSize = record.imageCount;
    }
    AchievementManageListDroneShpImageexif({
      ...querys,
    })
      .then((res) => {
        // console.log(res);
        handlerUpdateTaskLayerData(res.items);
        tableData3_tupian.value = res.items;
      })
      .catch((error) => {
        console.log(error);
      });
  }

  // 全部
  let imgCountTotal = 0;
  function handAll() {
    if (imgCountTotal == 0) {
      let totalQuerys = {
        pageSize: tablePagination.value.total,
        pageIndex: 1,
      };
      // setLoading(true);
      AchievementManageListTask(totalQuerys).then((res) => {
        for (const item of res.items) {
          imgCountTotal += item.imageCount;
        }
        DroneShpImageexifAll();
        // setLoading(false);
      });
    } else {
      DroneShpImageexifAll();
    }
  }

  function DroneShpImageexifAll() {
    // 航飞图片的筛选时间
    let querys: any = getFieldsValue();
    if (querys.mapBeginDate && querys.mapEndDate) {
      querys.beginDate = dayjs(querys.mapBeginDate).startOf('day').format('YYYY-MM-DD');
      querys.endDate = dayjs(querys.mapEndDate).endOf('day').format('YYYY-MM-DD HH:mm:ss');
    }
    // taskid筛选
    querys.pageIndex = 1;
    querys.pageSize = imgCountTotal;
    AchievementManageListDroneShpImageexif({
      ...querys,
    })
      .then((res) => {
        if (res.items.length > 0) {
          handlerUpdateTaskLayerData(res.items);
        } else {
          createMessage.info('当前查询时间段内并无航飞任务');
        }
      })
      .catch((error) => {
        console.log(error);
      });
  }

  // 无人机图层
  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);
    });

    // 确定中心点和zoom等级
    let result = calculateCenterAndZoom(lngList, latList);
    // console.log(333, result.center);
    // 航飞图片-图层
    mapboxComponentRef.value.AchievementManagerRaster(
      taskLayerGeoJson,
      result.center,
      7.848587811931849,
      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;
    }
  }

  // 获取任务名称
  function getTaskNameBytaskId(taskid) {
    let resultName = '';
    allDataForClearMap.forEach((element) => {
      if (element.id == taskid) {
        resultName = element.taskName + '(' + element.flyer + ')';
      }
    });
    if (resultName) {
      return resultName + '\n';
    } else {
      return resultName;
    }
  }

  // 确定中心点和zoom等级
  function calculateCenterAndZoom(lngList, latList) {
    // 检查输入的有效性
    if (!lngList || !latList || lngList.length !== latList.length) {
      throw new Error('');
    }
    // 计算中心点
    const centerLng = lngList.reduce((acc, lng) => acc + lng, 0) / lngList.length;
    const centerLat = latList.reduce((acc, lat) => acc + lat, 0) / latList.length;
    // 计算经纬度范围
    const minLng = Math.min(...lngList);
    const maxLng = Math.max(...lngList);
    const minLat = Math.min(...latList);
    const maxLat = Math.max(...latList);
    const deltaLng = maxLng - minLng;
    const deltaLat = maxLat - minLat;
    // 估算合适的缩放级别
    let zoom = 14 - Math.log2(Math.max(deltaLng, deltaLat)); // 直接使用最大偏移量
    zoom = Math.max(8, Math.min(15, zoom)); // 确保缩放级别在合理范围内
    return {
      center: [centerLng, centerLat],
      zoomLevel: zoom,
    };
  }

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

  // 打开窗口
  const handleOpenImage = (properties) => {
    modalOpen.value = true;
    // 正则表达式验证函数
    modalImage.value = properties;
  };
  const handleCancelImage = () => {
    modalOpen.value = false;
  };

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

  onMounted(() => {
    handleReset();
    // 用于去除分页后地图还有前一页的图层
    forClearMap();
  });
</script>
<style lang="less" scoped>
  .search-box {
    background: @component-background;
    height: 58px;
    margin: 16px 16px 16px 16px;
    padding: 12px 0px 0px 0px;
  }

  ::v-deep .ant-table-body {
    height: calc(100vh - 100px) !important;
  }

  ::v-deep .ant-table-wrapper {
    margin-left: 16px !important;
  }

  ::v-deep .ant-row .ant-form-item-row {
    margin-left: 30px !important;
  }

  .full-screen-button {
    width: 56px;
    height: 56px;
    position: absolute;
    // bottom: -640px;
    right: 40px;
    cursor: pointer;
    img {
      width: 100%;
      height: 100%;
    }
  }
</style>
