<template>
  <div :style="{ height: '750px' }">
    <a-tabs v-model:activeKey="activeKey" type="card">
      <a-tab-pane key="1" tab="更新的周数影像">
        <div :style="{ margin: '16px', marginLeft: '16px', marginBottom: '16px' }">
          <BasicTable
            @register="chooseUpdateRegisterTable_yearweeks"
            :loading="loading_yearweeks"
          />
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" tab="更新的影像图层">
        <BasicTable
          @register="chooseUpdateRegisterTable_layernames"
          :loading="loading_layernames"
        />
      </a-tab-pane>
      <template #leftExtra>
        <div :style="{ width: '10px' }" />
      </template>
      <template #rightExtra>
        <a-select
          v-if="activeKey == '1'"
          v-model:value="numValue"
          :options="NumOptions"
          style="width: 80px; margin-right: 10px"
          allowClear
          placeholder="份数"
        />
        <a-popover title="提示">
          <template #content>
            <p>是否只展示当前无缩略图的影像图层</p>
          </template>
          <a-switch
            v-if="activeKey == '2'"
            v-model:checked="switchYingxiang"
            style="margin-right: 15px; margin-bottom: 4px"
            checked-children="是"
            un-checked-children="否"
          />
        </a-popover>
        <a-select
          v-model:value="widthAndHeightValue"
          :options="widthAndHeightOptions"
          style="width: 80px; margin-right: 10px"
          allowClear
          placeholder="长宽"
        />
        <a-button type="success" @click="updateGeoTiff" :style="{ marginRight: '10px' }">
          更新缩略图
        </a-button>
      </template>
    </a-tabs>
  </div>
</template>
<script lang="ts" setup>
  import { ref, watch, defineProps, defineEmits, defineExpose } from 'vue';
  import { createVNode } from 'vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { Modal } from 'ant-design-vue';
  import { BasicTable, useTable } from '@/components/Table';
  import {
    chooseUpdateColumns_yearweeks,
    chooseUpdateColumns_layernames,
    searchFormSchema_chooseUpdate,
  } from './util';
  import { useMessage } from '@/hooks/web/useMessage';

  const { createMessage } = useMessage();
  const props = defineProps(['chooseUpdateData_yearweeks', 'chooseUpdateData_layernames']);
  const emit = defineEmits(['generateThumbnail']);

  const activeKey = ref('1');
  // 图片长宽
  const widthAndHeightValue = ref(1024);
  const widthAndHeightOptions = ref([
    {
      value: '4096',
      label: '4096',
    },
    {
      value: '2048',
      label: '2048',
    },
    {
      value: '1024',
      label: '1024',
    },
    {
      value: '512',
      label: '512',
    },
    {
      value: '256',
      label: '256',
    },
  ]);
  // 切割的份数
  const numValue = ref(1);
  const NumOptions = ref([
    {
      value: '30',
      label: '900',
    },
    {
      value: '20',
      label: '400',
    },
    {
      value: '5',
      label: '25',
    },
    {
      value: '1',
      label: '1',
    },
  ]);

  // 选择生成缩略图的影像-周数----------------------------------------------------------------------------
  const [
    chooseUpdateRegisterTable_yearweeks,
    {
      getSelectRows: getSelectRows_yearweeks,
      clearSelectedRowKeys: clearSelectedRowKeys_yearweeks,
    },
  ] = useTable({
    columns: chooseUpdateColumns_yearweeks,
    dataSource: props.chooseUpdateData_yearweeks,
    showIndexColumn: true,
    rowSelection: {
      type: 'checkbox',
    },
    canResize: true,
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    immediate: false,
    pagination: false,
    maxHeight: 585,
  });

  // 选择生成缩略图的影像-图层----------------------------------------------------------------------------
  const serachInfoData = ref(props.chooseUpdateData_layernames);
  const [
    chooseUpdateRegisterTable_layernames,
    {
      getSelectRows: getSelectRows_layernames,
      clearSelectedRowKeys: clearSelectedRowKeys_layernames,
    },
  ] = useTable({
    columns: chooseUpdateColumns_layernames,
    dataSource: serachInfoData,
    showIndexColumn: true,
    rowSelection: {
      type: 'checkbox',
    },
    useSearchForm: true,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema_chooseUpdate,
      autoSubmitOnEnter: true,
    },
    handleSearchInfoFn(info) {
      if (info.rowname) {
        serachInfoData.value = props.chooseUpdateData_layernames.filter((item) => {
          return item.rowname.indexOf(info.rowname) != -1;
        });
      } else {
        serachInfoData.value = props.chooseUpdateData_layernames;
      }
      return info;
    },
    canResize: true,
    showTableSetting: false,
    bordered: true,
    immediate: false,
    pagination: true,
    maxHeight: 471,
  });

  // 筛选无缩略图的影像or展示全部----------------------------------------------------------------------------
  const switchYingxiang = ref(false);
  watch(
    () => switchYingxiang.value,
    async () => {
      if (switchYingxiang.value) {
        serachInfoData.value = await filterLayersWithImages(props.chooseUpdateData_layernames);
      } else {
        serachInfoData.value = props.chooseUpdateData_layernames;
      }
    },
  );

  async function filterLayersWithImages(layerNames) {
    // 创建一个包含所有检查图片存在的Promise数组
    const checkPromises = layerNames.map(async (item) => {
      const exists = await checkImageExists(
        `/geoserver/group/1/${item.rowname}/${item.rowname}.png`,
      );
      return { item, exists };
    });
    // 等待所有Promise完成
    const results = await Promise.all(checkPromises);
    // 过滤出存在图片的图层
    return results.filter((result) => !result.exists).map((result) => result.item);
  }

  async function checkImageExists(url) {
    try {
      const response = await fetch(url, { method: 'HEAD' });
      if (response.ok) {
        return true;
      } else {
        return false;
      }
    } catch (error) {
      return false;
    }
  }

  // 选择更新的缩略图----------------------------------------------------------------------------
  const updateGeoTiff = () => {
    if (activeKey.value == '1') {
      // 更新的周数影像
      let rows = getSelectRows_yearweeks();
      if (rows.length == 0) {
        return createMessage.warn('请勾选至少一条数据进行更新');
      }
      let layerNames: any = '';
      rows.forEach((row, index) => {
        if (index == 0) {
          layerNames = row.rowname;
        } else {
          layerNames = layerNames.concat(',' + row.rowname);
        }
        if (index + 1 == rows.length) {
          updateThumbnail_yearweeks(layerNames);
        }
      });
    } else {
      // 更新的影像图层
      let rows = getSelectRows_layernames();
      if (rows.length == 0) {
        return createMessage.warn('请勾选至少一条数据进行更新');
      }
      if (rows.length >= 50) {
        Modal.confirm({
          title: '发现更新数量达到50，是否要更新全部?',
          icon: createVNode(ExclamationCircleOutlined),
          onCancel() {
            rows.forEach((row, index) => {
              updateThumbnail_layernames(row.rowname, row.bbox, rows.length, index + 1);
            });
          },
          onOk() {
            serachInfoData.value.forEach((row, index) => {
              updateThumbnail_layernames(row.rowname, row.bbox, rows.length, index + 1);
            });
          },
        });
      } else {
        rows.forEach((row, index) => {
          updateThumbnail_layernames(row.rowname, row.bbox, rows.length, index + 1);
        });
      }
    }
  };

  // 生成缩略图-------------------------------------------------------------------------------------------
  // 等待
  const loading_yearweeks = ref(false);
  const loading_layernames = ref(false);
  function updateThumbnail_yearweeks(layerNames) {
    loading_yearweeks.value = true;
    emit(
      'generateThumbnail',
      layerNames,
      null,
      null,
      null,
      widthAndHeightValue.value,
      numValue.value,
    );
  }
  // 生成缩略图
  function updateThumbnail_layernames(rowname, bbox, length, index) {
    loading_layernames.value = true;
    emit('generateThumbnail', rowname, bbox, length, index, widthAndHeightValue.value, 1);
  }

  // 清除旧选项
  function clearSelect_yearweeks() {
    clearSelectedRowKeys_yearweeks();
  }
  function clearSelect_layernames() {
    clearSelectedRowKeys_layernames();
  }

  defineExpose({
    loading_yearweeks,
    loading_layernames,
    clearSelect_yearweeks,
    clearSelect_layernames,
  });
</script>
<style lang="less">
  .content-full {
    white-space: pre-wrap;
    word-break: break-all;
    overflow-wrap: break-word;
    max-width: 100%;
    display: block;
  }
</style>
