<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 #toolbar>
            <!-- <PermissionBtn @btn-event="onBtnClicked" /> -->
          </template>
        </BasicTable>
      </a-col>
      <a-col :span="mapSpan">
        <div>
          <MapComponent
            ref="mapboxComponentRef"
            :style="{
              position: 'absolute',
              height: `calc(100vh - 196px)`,
              width: isFullScreen ? `100%` : `calc(83vh)`,
              marginLeft: isFullScreen ? '0px' : '16px',
              top: '0px',
              left: '0px',
              zIndex: '0',
            }"
            @handleOpen="handleOpen"
          />
          <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>

    <a-modal :open="modalOpen" :title="modalTitle" :footer="null" @cancel="handleCancel">
      <a-image style="height: 100%; width: 100%" :src="modalImage" />
    </a-modal>
  </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 { BasicForm, useForm } from '@/components/Form';
  import { columns, searchFormSchema_map, searchFormSchema_table } from './util';
  import MapComponent from '@/views/demo/system/geoservermanagement/clound/mapComponent.vue';
  // api
  import {
    AchievementManageAddImageexif,
    AchievementManageIntactById,
    AchievementManageAddTask,
    AchievementManageListTask,
    AchievementManageListDroneShpImageexif,
  } from '@/api/demo/system';
  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>(true);
  const searchFormSchema = ref(searchFormSchema_map);
  const tableSpan = ref(0);
  const mapSpan = ref(24);

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

  // 左侧表格的搜索、表格和分页数据------------------------------------------------------------
  // 搜索条件
  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, getDataSource, setTableData, setLoading }] =
    useTable({
      title: '航飞图片',
      columns: columns,
      showIndexColumn: true,
      useSearchForm: false,
      ellipsis: false,
      bordered: true,
      showTableSetting: false,
      autoCreateKey: false,
      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();
  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);
      })
      .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) => {
        res.items.forEach((item) => {
          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) => {
        // console.log(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) => {
      // lngList.push(parseFloat(item.gemo.x));
      // latList.push(parseFloat(item.gemo.y));
      let feature: any = {
        type: 'Feature',
        geometry: {
          type: 'Point',
          coordinates: [parseFloat(item.gemo.x), parseFloat(item.gemo.y)],
        },
        properties: {
          taskName: getTaskNameBytaskId(item.taskId) + item.uploadTime,
          path: item.path,
          // model: item.model,
          lng: item.gemo.x,
          lat: item.gemo.y,
        },
      };
      taskLayerGeoJson.features.push(feature);
    });

    // 确定中心点和zoom等级
    // let result = calculateCenterAndZoom(lngList, latList);
    // console.log(result);
    // 航飞图片-图层
    mapboxComponentRef.value.AchievementManageRaster(
      taskLayerGeoJson,
      [118.30207505530701, 35.30123435040745],
      7.848587811931849,
    );
  }

  // 获取任务名称
  function getTaskNameBytaskId(taskid) {
    let resultName = '';
    getDataSource().forEach((element) => {
      if (element.id == taskid) {
        resultName = element.taskName;
      }
    });
    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) * 360) / 360); // 360度为地球一圈
    zoom = Math.max(8, Math.min(15, zoom)); // 确保缩放级别在合理范围内
    return {
      center: [centerLng, centerLat],
      zoomLevel: zoom,
    };
  }

  // 点击地图上的无人机图标后展示图片------------------------------------------------------------
  // 窗口
  const modalOpen = ref(false);
  const modalTitle = ref('');
  const modalImage = ref('');
  // 打开窗口
  const handleOpen = (path) => {
    modalOpen.value = true;
    modalTitle.value = '';
    modalImage.value = VITE_GLOB_API_URL_VAR.value + path;
  };
  // 关闭窗口
  const handleCancel = () => {
    modalOpen.value = false;
    modalTitle.value = '';
    modalImage.value = '';
  };

  onMounted(() => {
    handleReset();
  });
</script>
<style lang="less" scoped>
  .search-box {
    background: @component-background;
    margin: 16px 16px 16px 0px;
    padding: 16px 16px 0px 16px;
  }

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

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