<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 - 200px);
                    width: calc(85vh);
                    z-index: 0;
                  "
                />
              </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"
      :maskClosable="false"
      :afterClose="handleClose"
      title="添加GeoServer服务"
      width="1000px"
      style="top: 20px"
      size="small"
    >
      <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"
          />
        </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="current = 0"
          v-if="uploadFrom.dataSourceType == 'shp' && current == 1"
        >
          上一步
        </a-button>
        <a-button
          type="primary"
          @click="nextStep"
          v-if="
            !(
              (uploadFrom.dataSourceType == 'shp' && current == 2) ||
              (uploadFrom.dataSourceType == 'excel' && current == 1)
            )
          "
        >
          下一步
        </a-button>
      </template>
    </a-modal>

    <a-modal
      v-model:open="editModalShow"
      :maskClosable="false"
      :afterClose="handleAddClose"
      title="编辑GeoServer服务"
      width="600px"
      style="top: 20px"
      size="small"
    >
      <UploadFrom
        ref="uploadFormRef"
        :uploadForm="uploadFrom"
        :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>
</template>
<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  // vben
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { useMessage } from '@/hooks/web/useMessage';
  // 组件
  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 {
    indexColumns,
    indexSearchFormSchema,
    items_shp,
    items_excel,
  } from './clound/clound.data';
  import {
    getGeomData,
    getStatisticalList,
    ShpGeoLayerAdd,
    ShpGeoLayerLoadPage,
    ShpGeoLayerGet,
    ShpGeoLayerUpdateLayer,
    ShpGeoLayerDelete,
    ShpGeoLayerParseShpInfo,
  } from '@/api/demo/system';
  import axios from 'axios';
  import { cloneDeep } from 'lodash-es';

  const { createConfirm, createMessage } = useMessage();

  const activeKey = ref('1');
  let nowChooseRow: any = {};
  const chooseRow = ref();
  const mapboxComponentRef = ref();
  const serviceTableRef = ref();
  // 表格行选中
  function handRowClick(record) {
    if (activeKey.value == '1') {
      nowChooseRow = record;
      let lngLat = handlerOnMapLoad(record);
      mapboxComponentRef.value.GeoserverManagementRaster(record, lngLat, 11);
    } else {
      nowChooseRow = record;
      chooseRow.value = nowChooseRow;
      setTimeout(() => {
        serviceTableRef.value.setServerUrl(chooseRow.value);
      }, 300);
    }
  }
  // 标签切换
  function handRowChange() {
    if (activeKey.value == '1') {
      let lngLat = handlerOnMapLoad(nowChooseRow);
      mapboxComponentRef.value.GeoserverManagementRaster(nowChooseRow, lngLat, 11);
    } 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 {
          let st: any = res.slice(6, -1);
          st = st.split(' ');
          return [st[0], st[1]];
        }
      })
      .catch((error) => {
        console.log(error);
      });
  }

  // 图层管理
  const searchParams = ref();
  const [registerTable, { reload, getSelectRows, getDataSource, 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: '',
    spatialRef: '',
    dataSourceType: '',
    dataType: '',
    dataTable: '',
    shpPath: '',
    // shpFileName: '',
    appendPath: '',
    // appendFileName: '',
    headers: [] as any,
  };
  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;
    }
  }

  // 步骤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();
      });
    }
    current.value = 1;
  }

  // 步骤2提交
  const headersTableRef = ref();
  function headersTableSubmit(value) {
    uploadFrom.value.headers = value;
    // 新增
    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();
        }
      })
      .catch((error) => {
        console.log(error);
      });
  }

  // 下一步
  function nextStep() {
    // 新增状态下的;
    if (uploadFrom.value.dataSourceType == '') {
      createMessage.warn('请先上传shp文件或者excel文件');
      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() {
    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 = 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() {
    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();
  }

  onMounted(() => {
    reload();
  });
</script>
<style lang="less" scoped>
  .content {
    padding: 20px;
  }

  .current1 {
    margin-top: 30px;
    display: flex;
    width: 800px;
  }
</style>
