<template>
  <a-modal
    class="insert-shp-modal"
    width="1290px"
    :destroyOnClose="true"
    v-model:open="props.openModal"
    @cancel="closeModal"
  >
    <template #closeIcon>
      <CloseCircleOutlined />
    </template>
    <div class="title">服务发布</div>
    <div class="content">
     
      <div class="select-file-div" v-show="current === 0">
        <div class="upload-form">

          <a-form
            ref="formRef"
            :model="uploadFrom"
            :label-col="{ style: { width: '75px' } }"
            labelAlign="right"
            :rules="uploadFormRules"
          >
            <a-form-item label="服务名称" name="name">
              <a-input v-model:value="uploadFrom.name" placeholder="请输入服务名称" />
            </a-form-item>

            <a-form-item label="服务描述" name="description">
              <a-input v-model:value="uploadFrom.description" placeholder="请输入服务名称" />
            </a-form-item>

            

            <!-- 显示条件：文件类型为shp 或者 类型为Excel时有线索数据 -->
            <a-form-item label="空间参考" name="srid" >
              <a-select v-model:value="uploadFrom.srid" placeholder="请选择空间参考">
                <a-select-option value="EPSG:4326">EPSG:4326</a-select-option>
                <a-select-option value="3857">EPSG:3857</a-select-option>
                <a-select-option value="900913">EPSG:900913</a-select-option>
              </a-select>
            </a-form-item>

            <!-- 显示条件：文件类型为Excel有线索时 -->
            <a-form-item label="数据类型" name="vectorType" >
              <a-select v-model:value="uploadFrom.vectorType" placeholder="请选择数据类型">
                <a-select-option value="point">点</a-select-option>
                <a-select-option value="linestring">线</a-select-option>
                <a-select-option value="面">面</a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="数据表名" name="relationTable">
              <a-row :gutter="12">
                <a-col :span="20">
                  <a-input v-model:value="uploadFrom.relationTable" placeholder="请输入表名" />
                </a-col>
                <a-col :span="4">
                  <!-- <a-tooltip title="从现有数据表中选择">
                    <a-button type="primary"  :icon="h(PlusOutlined)"  @click="handlerGetExistsTableList"/>
                  </a-tooltip> -->

                  <a-popover placement="topLeft">
                    <template #content>
                      <a-table :dataSource="dataSource" :columns="columns" :size="'small'" >
                        <template #bodyCell="{ column,record }">
                          <template v-if="column.key === 'operation'">
                            <a-button type=""  :icon="h(PlusOutlined)" @click="handlerGetExistsTableList(record)"  />
                          </template>
                        </template>
                      </a-table>
                    </template>

                    <template #title>
                      <span>从现有数据表中选择</span>
                    </template>
                    <a-button type="primary"  :icon="h(PlusOutlined)"  />
                  </a-popover>
                </a-col>
              </a-row>
            </a-form-item>
          </a-form>

          <div class="upload-span-button">
            <a-button type="primary" :icon="h(CloudUploadOutlined)" @click="submitShp">发布服务</a-button>
          </div>

        </div>
      </div>

      <div class="edit-info-div" v-show="current === 1">
        <a-table
          :columns="tablecolumns"
          :data-source="dataList"
          :pagination="false"
          :bordered="true"
          :scroll="{ y: 260 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'type'">
              <a-select v-model:value="record.type" style="width: 120px">
                <a-select-option value="geometry">geometry</a-select-option>
                <a-select-option value="varchar">varchar</a-select-option>
                <a-select-option value="text">text</a-select-option>
              </a-select>
            </template>
            <template v-if="column.key === 'length'">
              <a-input v-model:value="record.length" />
            </template>
            <template v-if="column.key === 'refName'">
              <a-input v-model:value="record.refName" />
            </template>
            <template v-if="column.key === 'initName'">
              <a-input v-model:value="record.initName" />
            </template>
            <template v-if="column.key === 'operation'">
              <a-button shape="round" :icon="h(DeleteOutlined)" @click="deleteListItem(record)">
                删除
              </a-button>
            </template>
          </template>
        </a-table>
        <div class="insert-list-button" @click="insertListItem">新增一条</div>
        <div class="footer-button">
          <a-button @click="current--">取消</a-button>
          <a-button style="margin-left: 25px" type="primary" @click="submitDataList"
            >下一步</a-button
          >
        </div>
      </div>
      
      <div class="submit-success" v-show="current === 2">
        <div class="success-content">
          <CheckCircleOutlined style="font-size: 100px; color: #1fd286; margin-bottom: 30px" />
          <div style="margin-bottom: 19px; font-size: 26px">导入成功</div>
          <div><a-button type="primary">查看数据</a-button></div>
        </div>
      </div>

      <!-- 已有数据表 -->
      <div class="exist-table-list" v-if="showExistTableList">

      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { defineEmits, defineProps, ref, h, reactive, onUnmounted, toRaw } from 'vue';
  import {
    CloseCircleOutlined,
    PlusOutlined,
    DeleteOutlined,
    CheckCircleOutlined,
  } from '@ant-design/icons-vue';
  import './index.scss';
  import { InboxOutlined,CloudUploadOutlined } from '@ant-design/icons-vue';
  import { message } from 'ant-design-vue';
  import type { UploadChangeParam } from 'ant-design-vue';
  import type { UploadProps } from 'ant-design-vue';
  import { addLayer } from '@/api/sys/layerManagement'
  import axios from 'axios';
  import { v4 as uuidv4 } from 'uuid';
  import { FILETYPE } from '../util' 
  import {ObjectToUrl} from '../src/tool'
  const dataSource = reactive([
    {
      "tablename":"monitor"
    },
    {
      "tablename":"monitor0527"
    },
  ]) 
      
  const columns = reactive([
    {
      title: '数据表名称',
      dataIndex: 'tablename',
      key: 'tablename',
    },{
      title: '选择数据表',
      dataIndex: 'operation',
      key: 'operation',
    }
  ])

  const current = ref(0);
  const fileList = ref<UploadProps['fileList']>([]);
  const props = defineProps(['openModal']);
  const emits = defineEmits(['update:openModal']);
  const uploadFrom = reactive({
    relationTable: null,
    name:null,
    description: null,
    srid:null,
    vectorType: null,
    style:"",
    createTime:new Date(),
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShp = ref<Boolean>(true);
  const showExistTableList = ref<Boolean>(false)

  // todo
  const tablecolumns = [
    { title: 'Shp原始字段', dataIndex: 'name', key: 'name' },
    { title: '数据类型', dataIndex: 'type', key: 'type' },
    { title: '数据长度', dataIndex: 'length', key: 'length' },
    { title: '英文名称', dataIndex: 'refName', key: 'refName' },
    { title: '中文名称', dataIndex: 'initName', key: 'initName' },
    { title: '操作', dataIndex: 'operation', key: 'operation' },
  ];



  const uploadFormRules = reactive({
    name: [{ required: true, message: '请输入服务名称', trigger: 'blur' }],
    description:[{ required: true, message: '请输入服务描述', trigger: 'blur' }],
    hasFeature: [{ required: true, message: '请选择是否有线索数据', trigger: 'blur' }],
    srid: [{ required: true, message: '请选择参考系', trigger: 'blur' }],
    vectorType: [{ required: true, message: '请选数据类型', trigger: 'blur' }],
    relationTable: [{ required: true, message: '请输入表名', trigger: 'blur' }],
  });


const beforeUpload:UploadProps['beforeUpload'] = (file) => {
  file.type === FILETYPE.ZIP ? isShp.value = true: isShp.value = false
  fileList.value = [file];
  return false;
};


const handlerUploadFile = ()=>{
  let url = "http://192.168.10.102:9500/api/Files/Upload"
  
  const [proxyFile] = fileList.value 
  let file = proxyFile.originFileObj 

  let formData = new FormData();
  formData.append('files', file)
  // formData.append('serverName',uploadFrom.serverName)
  // formData.append('spaceType',uploadFrom.spaceType)
  // formData.append('tableName',uploadFrom.tableName)


  axios.post(url,formData,{headers: {'Content-Type': 'multipart/form-data;charset=UTF-8','X-Token':"95a1a7a8"}}).then(res => {
    handlerCreateLayer(res.data.result[0].filePath)
  })
}

const handlerCreateLayer =(filePath)=>{

  // upload 接口返回路径的反斜杠替换  20240528\\2024052814563161320172.zip → 20240528/2024052814563161320172.zip

  filePath = filePath.replace(/\\/,'/');

  let addForm = {
    filePath:filePath,
    tableName:uploadFrom.tableName,
    srid:uploadFrom.spaceType
  }
  let params = ObjectToUrl(addForm);

  axios.post("http://192.168.10.102:9500/api/PolygonalShape/CreateGISLayer"+params,{},{headers:{'Content-Type': 'multipart/form-data;charset=UTF-8','X-Token':"95a1a7a8"}}).then(res=>{
    console.log("helloworld",res);
  })
}

const submitShp = () => {
  formRef.value.validate().then(() => {
    addLayer(uploadFrom).then(res=>{
      console.log("addLyaerAPI",res);
      if(res){
        closeModal()
      }
    })


    // axios.post(url,formData,{headers: {'Content-Type': 'multipart/form-data;charset=UTF-8'}}).then(res => {
    //   let data = res.data.data.heads
    //   let showData = data.map(item => {
    //     return {...item,refName:item.name.toLowerCase(),initName:item.name,key:uuidv4()}
    //   })
    // }).catch(err => {
    //   console.log(err)
    // })

  }).catch(err => {
    console.log(err)
  })
}

const closeModal = () => {
  emits('update:openModal', false)
  formRef.value.resetFields()
  fileList.value = []
  current.value = 0
}

const deleteListItem = (record) => {
  dataList.value = dataList.value.filter(item => item.key !== record.key)
}
const insertListItem = () => {
  dataList.value.push({
    key:uuidv4(),
    name:'',
    type:'',
    length:'',
    refName:'',
    initName:'',
  })
}
const submitDataList = () => {


  // let refRelation = {}

  // dataList.value.forEach((item,index)=>{
  //   refRelation[item.refName] = item.initName;
  // })

  // console.log("refRelation",refRelation);

 
  // let exportForm = {
  //     "newHeads": dataList.value,
  //     "refRelation": JSON.stringify(refRelation),
  // }

  // console.log(dataList.value)
  current.value++
}

// 获取现有数据表
const handlerGetExistsTableList = (record )=>{
  uploadFrom.tableName = record.tablename
}
</script>

<style lang="scss" scoped>
  .insert-shp-modal {
    .title {
      height: 77px;
      border-bottom: 1px solid #d7dbec;
      display: flex;
      align-items: center;
      padding-left: 63px;
      font-size: 28px;
    }
    .content {
      padding: 106px;
    }
    .steps {
      // margin-bottom: 80px;
    }
    .select-file-div {
      padding-left: 52px;
      padding-top: 80px;
      display: flex;
      .upload-div {
        width: 200px;
        height: 200px;
        background: #ffffff;
        box-shadow: 0px 52px 103px 0px rgba(192, 199, 218, 0.35);
        border-radius: 4px;
        display: flex;
        justify-content: center;
        align-items: center;
        .upload-dragger {
          height: 174px;
        }
      }
      .upload-span {
        margin-left: 40px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .upload-span-content {
          font-size: 16px;
          margin-top: 8px;
        }
      }
      .upload-form {
        flex: 1;
        margin-left: 40px;
        .upload-span-button {
          display: flex;
          justify-content: flex-end;
        }
      }
    }
    .edit-info-div {
      padding-top: 26px;
      .footer-button {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
      }
      .insert-list-button {
        background-color: #91b0ff;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
        user-select: none;
        cursor: pointer;
        height: 30px;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
        font-weight: 400;
        transition: 1s;
      }
      .insert-list-button:hover {
        font-weight: 900;
        color: #000;
      }
    }
    .submit-success {
      .success-content {
        width: 200px;
        align-items: center;
        margin: auto;
        display: flex;
        flex-direction: column;
      }
    }
    .exist-table-list{
      width:100%;
      height: calc( 100% - 60px);
      position:absolute;
      top:60px;
      left:0px;
      background:#fff;
      border-radius: 12px;
    }
  }
</style>
