<template>
  <div class="current1">
    <div class="upload-div w-1/2 xl:w-1/2 m-4 mr-0" v-if="!isEdit">
      <a-upload-dragger
        v-model:fileList="uploadFrom.shpFileList"
        name="uploadFrom.shpFileName"
        style="height: 274px; width: 300px"
        class="upload-dragger"
        :multiple="false"
        :maxCount="1"
        :before-upload="shpBeforeUpload"
        :customRequest="shpCustomRequest"
        accept=".zip,.xls,.xlsx"
      >
        <p class="ant-upload-drag-icon">
          <PlusOutlined />
        </p>
        <div style="opacity: 0.7"> 文件上传 </div>
        <div class="upload-span">
          <div class="upload-span-content">
            <div style="opacity: 0.7">将文件拖拽到这里或点击上传按钮</div>
            <div style="color: #1e5eff">支持扩展名：zip、xls、xlsx</div>
            <div style="opacity: 0.7"> zip中需要包含 .shp .shx .dbf 文件 </div>
            <div style="opacity: 0.7"> 且.shp文件大小小于3GB </div>
          </div>
        </div>
      </a-upload-dragger>
    </div>
    <div class="upload-form w-1/2 xl:w-1/2 m-4 mr-0">
      <a-form
        ref="formRef"
        :model="uploadFrom"
        :labelCol="{ width: '75px' }"
        labelAlign="right"
        :rules="uploadFormRules"
      >
        <a-form-item label="服务名称" name="serverName">
          <a-input v-model:value="uploadFrom.serverName" placeholder="请输入服务名称" />
        </a-form-item>
        <a-form-item label="所属区县" name="countyname">
          <a-select
            v-model:value="uploadFrom.countyname"
            placeholder="请选择所属区县"
            :options="countynameOptions"
          />
        </a-form-item>
        <a-form-item label="空间参考" name="spatialRef">
          <a-select
            v-model:value="uploadFrom.spatialRef"
            placeholder="请选择空间参考"
            :disabled="isEdit"
          >
            <a-select-option value="EPSG:4326">EPSG:4326</a-select-option>
            <a-select-option value="EPSG:3857">EPSG:3857</a-select-option>
            <a-select-option value="EPSG:4548">EPSG:4548</a-select-option>
            <a-select-option value="EPSG:900913">EPSG:900913</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="数据表名" name="dataTable">
          <a-input
            v-model:value="uploadFrom.dataTable"
            placeholder="请输入表名"
            :disabled="isEdit"
          />
        </a-form-item>
        <a-form-item label="图层样式" name="styleName" :style="{ marginLeft: '10px' }">
          <span :style="{ display: 'flex', alignItems: 'center', gap: '10px' }">
            <a-select
              v-model:value="uploadFrom.styleName"
              placeholder="请选择图层样式"
              :options="layerStyleOptions"
              :field-names="{ label: 'title', value: 'styleName' }"
              @change="uploadFromSetStyle"
            />
            <PlusSquareOutlined
              :style="{ fontSize: '30px', color: hover ? '#2a7dc9' : '#393939' }"
              @mouseenter="hover = true"
              @mouseleave="hover = false"
              @click="addLayerShow"
            />
          </span>
          <a-modal
            title="上传图层样式"
            :open="addLayerOpen"
            @cancel="addLayerClose"
            @ok="addLayerOnOk"
          >
            <AddLayer
              ref="addLayerRef"
              :layerStyleOptions="layerStyleOptions"
              @addLayerSubmitAfter="addLayerSubmitAfter"
            />
          </a-modal>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, watch, onMounted } from 'vue';
  // vben
  import { PermissionBtn } from '@/components/PermissionBtn/index';
  import { useMessage } from '@/hooks/web/useMessage';
  import type { UploadProps } from 'ant-design-vue';
  import { message, Upload } from 'ant-design-vue';
  import { PlusOutlined, DeleteOutlined, PlusSquareOutlined } from '@ant-design/icons-vue';
  // 组件
  import AddLayer from '@/views/demo/system/achievement/LayerStyleManager/addLayer.vue';
  // api
  import { ShpGeoLayerParseShpInfo, getChildrenTree, GeoStylePage } from '@/api/demo/system';
  import { CheckTableExist } from '@/api/database/index';
  import axios from 'axios';
  import { cloneDeep } from 'lodash-es';
  import { getAppEnvConfig } from '@/utils/env';

  const { VITE_GLOB_API_URL } = getAppEnvConfig();
  const { createMessage } = useMessage();
  const formRef = ref();

  const props = defineProps(['uploadForm', 'isEdit']);
  const uploadFrom = ref({
    serverName: '',
    countyname: null,
    spatialRef: null,
    dataSourceType: '',
    dataType: '',
    dataTable: '',
    shpPath: '',
    shpFileName: '',
    shpFileList: [],
    appendPath: '',
    headers: [] as any,
    style: '',
    styleName: null,
  });
  const isEdit = ref(props.isEdit);
  const emit = defineEmits([
    'uploadFormSubmit',
    'setDataSourceType',
    'setShpUploadType',
    'setSldUploadType',
  ]);

  watch(
    () => props.uploadForm,
    () => {
      uploadFrom.value = cloneDeep(props.uploadForm);
    },
    {
      deep: true,
      immediate: true,
    },
  );

  // 验证
  const uploadFormRules = reactive({
    serverName: [{ required: true, message: '请输入服务名称', trigger: 'blur' }],
    countyname: [{ required: true, message: '请输入所属区县', trigger: 'blur' }],
    spatialRef: [{ required: true, message: '请选择空间参考', trigger: 'blur' }],
    // dataType: [{ required: true, message: '请选择数据类型', trigger: 'blur' }],
    // styleName: [{ required: true, message: '请选择图层样式', trigger: 'blur' }],
    dataTable: [
      { required: true, message: '请输入数据表名', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          let reg = /^[a-z]\w{0,28}$/;
          if (value !== '' && !reg.test(value)) {
            callback(
              new Error('小写字母开头，可包含下划线，但不能有汉字和大写字母，不能超过30字符'),
            );
          }
          callback();
        },
        trigger: 'blur',
      },
      {
        validator: (rule, value, callback) => {
          let query: any = { tableName: value };
          CheckTableExist(query)
            .then((res) => {
              if (res) {
                callback(new Error('数据库已有此数据表名，请更换表名'));
              } else {
                callback();
              }
            })
            .catch(() => {
              callback(new Error('检查数据表名时发生错误'));
            });
        },
        trigger: 'blur',
      },
    ],
  });

  // 清除验证
  const clearValidation = () => {
    formRef.value.clearValidate();
    uploadFrom.value.shpFileName = '';
  };

  // 步骤1-提交
  const submit1 = () => {
    formRef.value
      .validate()
      .then(() => {
        let params = {
          zipFilePath: uploadFrom.value.shpPath,
          tableName: uploadFrom.value.dataTable,
          srid: uploadFrom.value.spatialRef,
        };
        ShpGeoLayerParseShpInfo(params).then((res) => {
          uploadFrom.value.dataType = res.dataType;
          uploadFrom.value.headers = res.headers;
          emit('uploadFormSubmit', uploadFrom.value);
        });
      })
      .catch((error) => {
        console.log(error);
      });
  };

  // 步骤1-shp上传
  let isShpUpload = false;
  // 步骤1-shp上传之前
  const shpBeforeUpload: UploadProps['beforeUpload'] = (file) => {
    let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
    let size = file.size / 1024 / 1024;
    const isZipOrXls = extension === 'zip' || extension === 'xls' || extension === 'xlsx';
    const suitableSize = size < 1024 * 3;
    if (!isZipOrXls) {
      createMessage.error('只能上传后缀是.zip .xls或者.xlsx的文件');
    }
    if (extension == 'zip') {
      emit('setDataSourceType', 'shp');
    } else if (['xls', 'xlsx'].includes(extension)) {
      emit('setDataSourceType', 'excel');
    }
    if (!suitableSize) {
      createMessage.error('文件大小不得超过3GB');
    }
    isShpUpload = isZipOrXls && suitableSize;
    if (isShpUpload) {
      emit('setShpUploadType', true);
      uploadFrom.value.serverName = uploadFrom.value.serverName
        ? uploadFrom.value.serverName
        : file.name.substring(0, file.name.lastIndexOf('.'));
    }
    return isShpUpload;
  };
  // 步骤1-shp上传文件接口
  const shpCustomRequest = (options) => {
    if (isShpUpload) {
      const formData = new FormData();
      formData.append('files', options.file);
      // 假设 Token 存储在 localStorage 中
      const token = localStorage.getItem('X-Token');
      // 设置请求头部，带上 Token
      const headers = {
        'X-Token': token,
      };
      axios
        .post(VITE_GLOB_API_URL + '/api/Files/Upload', formData, { headers, timeout: 0 })
        .then((response) => {
          options.onSuccess(response.data, options.file);
          uploadFrom.value.shpFileName = response.data.result[0].fileName;
          uploadFrom.value.shpPath = response.data.result[0].filePath;
          emit('setShpUploadType', false);
        })
        .catch((error) => {
          options.onError(error);
        });
    }
  };

  defineExpose({
    submit1,
    clearValidation,
  });

  // 临沂区县的行政区划---------------------------------------------------------
  const countynameOptions: any = ref([{ label: '临沂市', value: '临沂市' }]);
  function getChildrenTreeByParentId() {
    getChildrenTree({ parentId: 371300 }).then((res) => {
      res.map((item) =>
        countynameOptions.value.push({
          label: item.name,
          value: item.name,
        }),
      );
    });
  }

  // 图层样式按钮颜色---------------------------------------------------------
  const hover = ref(false);
  // 图层样式弹窗
  const addLayerOpen = ref(false);
  // 图层样式Ref
  const addLayerRef = ref();
  // 图层样式弹窗开启
  function addLayerShow() {
    addLayerOpen.value = true;
  }
  // 图层样式弹窗关闭
  function addLayerClose() {
    addLayerRef.value.addLayerCancel();
    addLayerOpen.value = false;
  }
  // 图层样式弹窗提交
  function addLayerOnOk() {
    addLayerRef.value.addLayerSubmit();
  }

  // 图层样式
  const layerStyleOptions: any = ref();
  // 图层样式提交按钮
  function getGeoStylePage() {
    GeoStylePage({ limit: 10000, page: 1 }).then((res) => {
      layerStyleOptions.value = res.items;
    });
  }
  // 图层样式提交成功后
  function addLayerSubmitAfter(addlayer) {
    // 图层样式
    getGeoStylePage();
    uploadFrom.value.styleName = addlayer.styleName;
    uploadFrom.value.style = addlayer.style;
    addLayerOpen.value = false;
  }
  // 图层样式选择改变
  function uploadFromSetStyle() {
    uploadFrom.value.style = layerStyleOptions.value.find(
      (item) => item.styleName == uploadFrom.value.styleName,
    ).style;
  }

  onMounted(() => {
    // 临沂区县的行政区划
    getChildrenTreeByParentId();
    // 图层样式
    getGeoStylePage();
  });
</script>
<style lang="less" scoped>
  .current1 {
    display: flex;
  }
  .upload-div {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    top: -30px;
  }
  .upload-span {
    margin: 30px;
  }
  .upload-form {
    margin-left: 100px;
  }
</style>
