<template>
  <div>
    <a-row ::gutter="0">
      <a-col :span="12">
        <BasicTable @register="registerTable" @row-click="handRowClick">
          <template #toolbar>
            <PermissionBtn @btn-event="onBtnClicked" />
          </template>
        </BasicTable>
      </a-col>
      <a-col :span="12">
        <div class="map-outer" style="position: relative; top: 35px">
          <a-tabs v-model:activeKey="activeKey" type="card" @change="handRowChange">
            <a-tab-pane key="1" tab="地图">
              <div>
                <MapComponent
                  ref="mapboxComponentRef"
                  style="
                    position: absolute;
                    top: 0px;
                    left: 0px;
                    height: calc(100vh - 188px);
                    width: calc(85vh);
                    z-index: 0;
                  "
                  @getDetailByFeature="getDetailByFeature"
                />
              </div>
            </a-tab-pane>
            <a-tab-pane key="2" tab="服务">
              <ServiceTable ref="serviceTableRef" :chooseRow="chooseRow" />
            </a-tab-pane>
          </a-tabs>
        </div>
      </a-col>
    </a-row>

    <a-modal
      v-model:open="addModalShow"
      :closable="true"
      :maskClosable="false"
      title="添加GeoServer服务"
      width="1000px"
      style="top: 20px"
      size="small"
    >
      <template #closeIcon>
        <CloseOutlined :style="{ fontSize: '25px' }" @click="closeIcon" />
      </template>
      <div class="content">
        <div>
          <a-steps :current="current" size="small" label-placement="vertical" :items="items" />
        </div>
        <div class="current1" v-if="current == 0">
          <UploadFrom
            ref="uploadFormRef"
            :uploadForm="uploadFrom"
            :isEdit="isEdit"
            @setDataSourceType="setDataSourceType"
            @uploadFormSubmit="uploadFormSubmit"
            @setShpUploadType="setShpUploadType"
          />
        </div>
        <div class="current2" v-if="current == 1 && uploadFrom.dataSourceType == 'shp'">
          <HeadersTable
            ref="headersTableRef"
            :headers="uploadFrom.headers"
            @headersTableSubmit="headersTableSubmit"
          />
        </div>
        <div
          class="current3"
          v-if="current == 2 || (current == 1 && uploadFrom.dataSourceType == 'excel')"
        >
          <a-result
            status="success"
            title="图层创建成功"
            subTitle="图层创建成功，请在云查询图层列表查看"
          >
            <template #extra>
              <a-button type="primary" @click="closeAndCreate">再次创建</a-button>
              <a-button @click="handleAddClose">关闭窗口</a-button>
            </template>
          </a-result>
        </div>
      </div>
      <template #footer>
        <a-button
          type="default"
          @click="handleAddClose"
          v-if="
            !(
              (uploadFrom.dataSourceType == 'shp' && current == 2) ||
              (uploadFrom.dataSourceType == 'excel' && current == 1)
            )
          "
        >
          取消
        </a-button>
        <a-button
          type="primary"
          @click="jiexi_loading ? createMessage.info('文件解析中，不能回到上一步') : (current = 0)"
          v-if="uploadFrom.dataSourceType == 'shp' && current == 1"
        >
          上一步
        </a-button>
        <a-button type="primary" @click="nextStep" v-if="current == 0"> 下一步 </a-button>
        <a-button
          type="primary"
          @click="nextStep"
          :loading="jiexi_loading"
          v-if="uploadFrom.dataSourceType == 'shp' && current == 1"
        >
          解析
        </a-button>
      </template>
    </a-modal>

    <a-modal
      v-model:open="editModalShow"
      :maskClosable="false"
      title="编辑GeoServer服务"
      width="600px"
      style="top: 20px"
      size="small"
    >
      <UploadFrom
        ref="uploadFormRef"
        :uploadForm="uploadFrom"
        :maskClosable="false"
        :isEdit="isEdit"
        @uploadFormSubmit="uploadFormSubmit"
      />
      <template #footer>
        <a-button type="default" @click="handleEditClose"> 取消 </a-button>
        <a-button type="primary" @click="handleEditSubmit"> 提交 </a-button>
      </template>
    </a-modal>

    <div
      class="attribute"
      :style="{
        height: isMinusAttributeWindow ? '540px' : '30px',
      }"
      v-if="showAttributeWindow"
    >
      <span class="span-title">详细信息</span>
      <a-tooltip placement="top">
        <template #title>
          <span>按下空格快速切换</span>
        </template>
        <a-button class="span-button-minus" type="link" @click="minusAttributeWindow">
          <MinusOutlined v-if="isMinusAttributeWindow" style="color: black" />
          <ExpandAltOutlined
            v-if="!isMinusAttributeWindow"
            :style="{ fontSize: '17px', color: 'black' }"
          />
        </a-button>
      </a-tooltip>
      <a-button class="span-button-close" type="link" @click="closeAttributeWindow">
        <CloseOutlined style="color: black" />
      </a-button>
      <AttributeWindow
        v-if="isMinusAttributeWindow"
        :showAttributeFeature="showAttributeFeature"
        :initNameList="initNameList"
      />
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
  // vben
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { useMessage } from '@/hooks/web/useMessage';
  import {
    CloseOutlined,
    ExpandAltOutlined,
    MinusOutlined,
    CheckOutlined,
  } from '@ant-design/icons-vue';
  // 组件
  import UploadFrom from './clound/uploadFrom.vue';
  import HeadersTable from './clound/headersTable.vue';
  import ServiceTable from './clound/serviceTable.vue';
  import MapComponent from './clound/mapComponent.vue';
  import AttributeWindow from '@/views/demo/system/achievement/Display/AttributeWindow.vue';

  import {
    indexColumns,
    indexSearchFormSchema,
    items_shp,
    items_excel,
  } from './clound/clound.data';
  import {
    getGeomData,
    ShpGeoLayerAdd,
    ShpGeoLayerLoadPage,
    ShpGeoLayerUpdateLayer,
    ShpGeoLayerDelete,
    getDataTableRecord,
  } from '@/api/demo/system';
  import { getLoad } from '@/api/sys/sysDataItemDetail';
  import axios from 'axios';
  import { cloneDeep } from 'lodash-es';
  import { getAppEnvConfig } from '@/utils/env';

  const { VITE_GLOB_GEOSERVER_PREFECTURE_CITY_NAME } = getAppEnvConfig();
  const { createConfirm, createMessage } = useMessage();

  const activeKey = ref('1');
  let nowChooseRow: any = {};
  const chooseRow = ref();
  const mapboxComponentRef = ref();
  const serviceTableRef = ref();
  // 上传中和解析中
  const shp_uploadloading = ref(false);
  const jiexi_loading = ref(false);
  // 表格行选中
  function handRowClick(record) {
    if (activeKey.value == '1') {
      nowChooseRow = record;
      handlerOnMapLoad(record);
    } else {
      nowChooseRow = record;
      chooseRow.value = nowChooseRow;
      setTimeout(() => {
        serviceTableRef.value.setServerUrl(chooseRow.value);
      }, 300);
    }
  }
  // 标签切换
  function handRowChange() {
    if (activeKey.value == '1') {
      handlerOnMapLoad(nowChooseRow);
    } else {
      chooseRow.value = nowChooseRow;
      console.log(nowChooseRow);
      setTimeout(() => {
        serviceTableRef.value.setServerUrl(chooseRow.value);
      }, 300);
    }
  }

  // 获取图层中心
  function handlerOnMapLoad(chooseRow) {
    getGeomData({ dataTable: chooseRow.dataTable })
      .then((res) => {
        if (res == undefined) {
          createMessage.error('数据库不存在此图层的数据表');
        } else {
          allDataForClearMap.forEach((data) => {
            mapboxComponentRef.value.clearTaskLayer(data.dataTable);
          });
          let st: any = res.slice(6, -1);
          st = st.split(' ');
          let chooseRows: any = [];
          chooseRows.push(nowChooseRow);
          if (chooseRow.countyname == VITE_GLOB_GEOSERVER_PREFECTURE_CITY_NAME) {
            mapboxComponentRef.value.GeoserverManagementRaster(
              chooseRows,
              [118.30207505530701, 35.30123435040745],
              7.848587811931849,
              true,
            );
          } else {
            mapboxComponentRef.value.GeoserverManagementRaster(chooseRows, [st[0], st[1]], 9, true);
          }
        }
      })
      .catch((error) => {
        console.log(error);
      });
  }

  // 图层管理
  const searchParams = ref();
  const [registerTable, { reload, getSelectRows, clearSelectedRowKeys }] = useTable({
    title: '图层管理',
    api: ShpGeoLayerLoadPage,
    columns: indexColumns,
    formConfig: {
      labelWidth: 120,
      schemas: indexSearchFormSchema,
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: true,
    ellipsis: true,
    rowSelection: {
      type: 'radio',
    },
    handleSearchInfoFn(info) {
      searchParams.value = info;
      return info;
    },
  });

  // 步骤
  const current = ref(0);
  const items = ref(items_shp);

  // 步骤1信息
  const uploadFormRef = ref();
  const uploadFromAdd = {
    serverName: '',
    countyname: undefined,
    spatialRef: undefined,
    dataSourceType: '',
    dataType: '',
    dataTable: '',
    shpPath: '',
    shpFileName: '',
    shpFileList: [],
    appendPath: '',
    headers: [] as any,
    style: '',
    styleName: undefined,
  };
  const uploadFrom = ref(uploadFromAdd);

  // 确认上传的文件类型
  function setDataSourceType(value) {
    uploadFrom.value.dataSourceType = value;
    if (value === 'shp') {
      items.value = items_shp;
    } else if (value === 'excel') {
      items.value = items_excel;
    }
  }
  // shp文件上传完毕
  function setShpUploadType(value) {
    shp_uploadloading.value = value;
  }

  // 步骤1提交
  function uploadFormSubmit(value) {
    uploadFrom.value = value;
    if (uploadFrom.value.dataSourceType === 'excel') {
      uploadFrom.value.dataType = '点';
    }
    if (uploadFrom.value.headers) {
      uploadFrom.value.headers.forEach((item) => {
        item.refName = item.refName != null ? item.refName.toLowerCase() : item.name.toLowerCase();
        item.initName = initNameList.value.find((i) => {
          return item.refName.toLowerCase() === i.itemValue.toLowerCase();
        })?.itemName;
      });
    }
    current.value = 1;
  }

  // 步骤2提交
  const headersTableRef = ref();
  function headersTableSubmit(value) {
    if (jiexi_loading.value) {
      createMessage.info('文件解析中，请勿重复提交！');
      return;
    }
    uploadFrom.value.headers = value;
    jiexi_loading.value = true;
    // 新增
    ShpGeoLayerAdd(uploadFrom.value)
      .then((res) => {
        if (res) {
          if (uploadFrom.value.dataSourceType == 'shp') {
            current.value = 2;
          } else if (uploadFrom.value.dataSourceType == 'excel') {
            current.value = 1;
          }
          handleSuccess();
          jiexi_loading.value = false;
        }
      })
      .catch((error) => {
        console.log(error);
        jiexi_loading.value = false;
      });
  }

  // 下一步
  function nextStep() {
    // 新增状态下的;
    if (uploadFrom.value.dataSourceType == '') {
      createMessage.warn('请先上传shp文件或者excel文件');
      return;
    }
    if (shp_uploadloading.value) {
      createMessage.warn('shp文件上传中，请稍等...');
      return;
    }
    if (current.value == 0 && uploadFrom.value.dataSourceType == 'shp') {
      uploadFormRef.value.submit1();
    } else if (current.value == 0 && uploadFrom.value.dataSourceType == 'excel') {
      uploadFrom.value.dataType = '点';
      headersTableSubmit([]);
    } else if (current.value == 1) {
      headersTableRef.value.submit2();
    }
  }

  // 按键
  const isEdit = ref(false);
  function onBtnClicked(domId) {
    switch (domId) {
      case 'btnAdd':
        isEdit.value = false;
        handleAdd();
        break;
      case 'btnEdit':
        isEdit.value = true;
        handleEdit();
        break;
      case 'btnDelete':
        handleDelete();
        break;
      default:
        break;
    }
  }

  // 新增弹窗开关
  const addModalShow = ref<Boolean>(false);
  // 打开新增弹窗
  function handleAdd() {
    current.value = 0;
    addModalShow.value = true;
    uploadFrom.value = cloneDeep(uploadFromAdd);
    items.value = items_shp;
  }
  // 关闭新增窗口
  function handleAddClose() {
    if (shp_uploadloading.value || jiexi_loading.value) {
      createConfirm({
        iconType: 'info',
        title: '关闭窗口',
        content: shp_uploadloading.value
          ? '文件上传中，关闭窗口后，需要重新上传文件，确认关闭当前窗口吗？'
          : '文件解析中，文件解析需要时间，关闭窗口后，不需要重复新增步骤。',
        onOk: () => {
          shp_uploadloading.value = false;
          jiexi_loading.value = false;
          addModalShow.value = false;
        },
      });
    } else {
      shp_uploadloading.value = false;
      jiexi_loading.value = false;
      addModalShow.value = false;
    }
    if (uploadFormRef.value) {
      uploadFormRef.value.clearValidation();
    }
  }
  // 窗口关闭
  function closeIcon() {
    shp_uploadloading.value = false;
    jiexi_loading.value = false;
    addModalShow.value = false;
    if (uploadFormRef.value) {
      uploadFormRef.value.clearValidation();
    }
  }

  // 再次创建
  function closeAndCreate() {
    current.value = 0;
    addModalShow.value = true;
    uploadFrom.value = cloneDeep(uploadFromAdd);
    items.value = items_shp;
  }

  // 编辑弹窗开关
  const editModalShow = ref<Boolean>(false);
  // 编辑
  function handleEdit() {
    let rows: any = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请勾选一个图层进行编辑');
    }
    uploadFrom.value = cloneDeep(rows[0]);
    current.value = 0;
    editModalShow.value = true;
    setDataSourceType(uploadFrom.value.dataSourceType);
  }
  // 编辑提交
  function handleEditSubmit() {
    ShpGeoLayerUpdateLayer(uploadFrom.value)
      .then((res) => {
        if (res) {
          handleSuccess();
          handleEditClose();
        }
      })
      .catch((error) => {
        console.log(error);
      });
  }
  // 关闭编辑窗口
  function handleEditClose() {
    uploadFormRef.value.clearValidation();
    editModalShow.value = false;
  }

  // 删除
  async function handleDelete() {
    let rows = getSelectRows();
    if (rows.length == 0) {
      return createMessage.warn('请勾选一个图层进行删除');
    }
    const query = { id: rows[0].id };
    createConfirm({
      iconType: 'info',
      title: '删除',
      content: '确定要删除当前图层吗？',
      onOk: async () => {
        const data = await ShpGeoLayerDelete(query);
        if (data) {
          handleSuccess();
          createMessage.success('删除成功');
        } else {
          createMessage.error('删除失败');
        }
      },
    });
  }
  // 刷新表格
  function handleSuccess() {
    clearSelectedRowKeys();
    reload();
  }

  // 字典-详细信息
  const initNameList: any = ref([]);
  function getSysDataItemDetail() {
    getLoad({ code: 'geoservermanagement' }).then((res) => {
      initNameList.value = res;
    });
  }

  // 点击矢量图层展示点击块的属性------------------------------------------------------------
  const showAttributeWindow = ref(false);
  const isMinusAttributeWindow = ref(true);
  const showAttributeFeature: any = ref();

  const getDetailByFeature = (feature) => {
    getDataTableRecord({
      id: feature.properties.id,
      dataTable: feature.source,
    }).then((res) => {
      showAttributeFeature.value = res;
      showAttributeWindow.value = true;
      if (!showAttributeWindow.value) {
        isMinusAttributeWindow.value = true;
      }
    });
  };

  const closeAttributeWindow = () => {
    showAttributeWindow.value = false;
    isMinusAttributeWindow.value = true;
  };
  const minusAttributeWindow = () => {
    isMinusAttributeWindow.value = !isMinusAttributeWindow.value;
  };

  // 添加键盘事件监听器
  const addEventListener = () => {
    window.addEventListener('keydown', handleKeydown);
  };
  // 移除键盘事件监听器
  const removeEventListener = () => {
    window.removeEventListener('keydown', handleKeydown);
  };
  // 处理按键按下事件
  const handleKeydown = (event: KeyboardEvent) => {
    if (event.code == 'Space') {
      minusAttributeWindow();
    }
  };

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

  onMounted(() => {
    reload();
    // 字典-详细信息
    getSysDataItemDetail();
    // 在组件挂载时添加监听器
    addEventListener();
    // 用于去除分也后地图还有前一页的图层
    forClearMap();
  });
</script>
<style lang="less" scoped>
  .content {
    padding: 20px;
  }

  .current1 {
    margin-top: 30px;
    display: flex;
    width: 800px;
  }

  .attribute {
    position: absolute;
    background-color: white;
    right: 10px;
    z-index: 1;
    top: 10px;
    width: 400px;
    height: 540px;
    border-radius: 10px;
  }

  .span-title {
    margin-left: 10px;
    color: rgba(0, 0, 0, 0.88);
    font-weight: 600;
    font-size: 20px;
    line-height: 1.5;
    word-wrap: break-word;
  }

  .span-button-minus {
    position: absolute;
    right: 50px;
  }

  .span-button-close {
    position: absolute;
    right: 10px;
  }
</style>
