<template>
  <div id="CustomService-panel" class="sm-panel" v-drag :style="panelStyle">
    <div class="sm-function-module-sub-section" style="margin:0" v-stopdrag>
      <div class="sm-half-L">
        <label style="width:40%">打开图层</label>
        <select class="sm-select" style="width:58%" v-model="layersType">
          <option value="SCENE">场景</option>
          <option value="S3M">S3M</option>
          <option value="IMG">地图服务</option>
          <option value="TERRAIN">地形服务</option>
          <option value="MVT">矢量要素</option>
          <option value="GEOJSON">GeoJSON</option>
          <option value="SHP">SHP上传</option>
        </select>
      </div>

      <div class="sm-half-L flex-start">
        <input
          type="text"
          class="sm-input sm-margin-M"
          style="width:100%"
          placeholder="URL"
          v-model="layerURL"
          v-show="layersType !== 'SHP'"
        />

        <div v-show="layersType === 'SHP'" class="shp-upload-container">
          <input
            type="file"
            ref="shpFileInput"
            accept=".zip,.shp"
            @change="handleShpFileChange"
            class="sm-input"
            style="width:100%"
          />
          <div class="upload-tip">支持 .zip(包含.shp,.shx,.dbf等) 或单独.shp文件</div>
        </div>

        <input
          type="text"
          class="sm-input sm-margin-M"
          style="width:100%"
          placeholder="自定义名称"
          v-model="layerName"
          v-show="layersType !== 'SHP'"
        />
          <!-- v-show="layersType === 'S3M'" -->

        <label class="label-S">添加token</label>
        <input checked type="checkbox" v-model="isAddToken" v-show="layersType !== 'SHP' && layersType !== 'GEOJSON'" />
        <input
          type="text"
          class="sm-input sm-margin-M"
          style="width:100%"
          placeholder="token"
          v-model="token"
          v-show="isAddToken && layersType !== 'SHP' && layersType !== 'GEOJSON'"
        />
      </div>
      <div class="sm-half-L flex-start" v-show="layersType === 'TERRAIN'">
        <label class="label-S">isSct</label>
        <input checked type="checkbox" v-model="isSct" />
      </div>

      <div class="boxchild">
        <button class="tbtn tbtn-margin-left" type="button" v-on:click="addLayer">添加</button>
        <button @click="clear" class="tbtn tbtn-margin-left" type="button">取消</button>
      </div>
    </div>
  </div>
</template>

<script>
import layerManagement from "../../js/common/layerManagement.js";
import tool from "../../js/tool/tool.js";
import { watch, ref, reactive, toRefs, onBeforeUnmount, onMounted, getCurrentInstance } from "vue";
import { uploadShp, getGeoJsonList, getGeoJsonUrl } from "../../api/cesium/geojson.js";
export default {
  name: "Sm3dCustomService",
  props: {
    //点击确定时回调
    addCallback: {
      type: Function
    },
    //点击取消时回调
    clearCallback: {
      type: Function
    },
    getLayerName:{
        type: Function
    }
  },
  setup(props) {
    onMounted(() => {
      setTimeout(() => {
        const panel = document.getElementById('CustomService-panel');
        if (panel) {
          panel.style.left = '35%';
          panel.style.top = '25%';
        }
      }, 50);
    });
    
    const shpFileInput = ref(null);
    const shpFile = ref(null);
    const uploadProgress = ref(0);
    const isUploading = ref(false);

    let state = reactive({
      layersType: "SCENE",
      layerURL: null,
      layerName: null,
      isAddToken: false,
      token: null,
      isSct: false
    });

    async function handleShpFileChange(event) {
      const file = event.target.files[0];
      if (!file) return;
      
      const fileName = file.name.toLowerCase();
      if (!fileName.endsWith('.zip') && !fileName.endsWith('.shp')) {
        tool.Message.warnMsg("请上传 .zip 或 .shp 格式的文件");
        return;
      }
      
      shpFile.value = file;
      tool.Message.infoMsg("已选择文件: " + file.name);
    }

    async function uploadShpFile() {
      if (!shpFile.value) {
        tool.Message.warnMsg("请先选择SHP文件");
        return null;
      }
      
      isUploading.value = true;
      uploadProgress.value = 0;
      
      const formData = new FormData();
      formData.append('file', shpFile.value);
      if (state.layerName) {
        formData.append('layerName', state.layerName);
      }
      
      try {
        const result = await uploadShp(formData);
        isUploading.value = false;
        uploadProgress.value = 100;
        
        if (result.code === 200 && result.data) {
          tool.Message.successMsg("文件上传成功");
          return result.data;
        } else {
          tool.Message.errorMsg(result.msg || "上传失败");
          return null;
        }
      } catch (error) {
        isUploading.value = false;
        tool.Message.errorMsg("上传失败: " + error.message);
        return null;
      }
    }

    async function addGeoJsonLayer() {
      const url = state.layerURL;
      if (!url) {
        tool.Message.warnMsg("请输入GeoJSON URL");
        return;
      }
      
      const serviceInfo = {
        url: url,
        type: 'GEOJSON'
      };
      
      layerManagement.addGeoJsonLayer(url, state.layerName || 'GeoJSON', (geoJsonLayer) => {
        addCallback(geoJsonLayer, "GEOJSON", serviceInfo);
      });
    }

    async function addShpLayer() {
      const geoJsonUrl = await uploadShpFile();
      if (!geoJsonUrl) return;
      
      const serviceInfo = {
        url: geoJsonUrl,
        type: 'GEOJSON'
      };
      
      layerManagement.addGeoJsonLayer(geoJsonUrl, state.layerName || 'SHP_Data', (geoJsonLayer) => {
        addCallback(geoJsonLayer, "GEOJSON", serviceInfo);
      });
    }

    let addCallback = () => {};
    let clearCallback = () => {};
    let getLayerName = () => {};

    if (props && props.clearCallback) {
      clearCallback = props.clearCallback;
    }
    if (props && props.addCallback) {
      addCallback = props.addCallback;
    }
      if (props && props.getLayerName) {
      getLayerName = props.getLayerName;
    }

    function check() {
      if (state.layersType === 'SHP') {
        if (!shpFile.value) {
          tool.Message.warnMsg("请先选择SHP文件");
          return false;
        }
        return true;
      }
      
      if (state.layersType === 'GEOJSON') {
        if (!state.layerURL || state.layerURL === "") {
          tool.Message.warnMsg("请填写GeoJSON URL");
          return false;
        }
        return true;
      }
      
      if (!state.layerURL || state.layerURL === "") {
        tool.Message.warnMsg("请填写正确的URL");
        return false;
      }
      if (
        state.layersType != "SCENE" &&
        (!state.layerName || state.layerName === "")
      ) {
        tool.Message.warnMsg("请补充图层名称");
        return false;
      }
      if (state.isAddToken && !state.token) {
        tool.Message.warnMsg("勾选token后请填写token");
        return false;
      }
      return true;
    }

    function checkLayersType(){
      if (state.layersType === 'SHP' || state.layersType === 'GEOJSON') {
        return true;
      }
      let arr = state.layerURL.split('/');
      let layer_type = arr[arr.length -1];
      if(layer_type === 'realspace' && state.layersType != "SCENE") return false;
      if(layer_type === 'config' && state.layersType != "S3M") return false;
      if(layer_type === 'image' && state.layersType != "IMG") return false;
      return true;
    }

    function addLayer() {
      if (!checkLayersType())  {
        tool.Message.warnMsg("请检查添加类型是否正常？");
        return;
      };
      getLayerName(state.layerName);
      
      const currentURL = state.layerURL;
      const currentToken = state.token;
      const currentTokenRequired = state.isAddToken;
      const currentLayerName = state.layerName;
      const currentLayersType = state.layersType;
      
      const serviceInfo = {
        url: currentURL,
        token: currentToken,
        tokenRequired: currentTokenRequired
      };
      
      console.log('addLayer - serviceInfo:', serviceInfo);
      console.log('addLayer - currentURL:', currentURL);
      
      switch (currentLayersType) {
        case "SCENE":
          if (check()) {
            let options = {};
            if (currentTokenRequired) options.SceneToken = currentToken;
            console.log('SCENE回调前serviceInfo:', serviceInfo);
            layerManagement.addScene(currentURL, options, (layers) => {
              console.log('SCENE回调中serviceInfo:', serviceInfo);
              addCallback(layers, "SCENE", serviceInfo);
            });
          }
          break;
        case "S3M":
          if (check()) {
            let scps = [
              { url: currentURL, options: { name: currentLayerName } }
            ];
            layerManagement.addS3mLayers(scps, (layers) => {
              addCallback(layers, "S3M", serviceInfo);
            });
          }
          break;
        case "IMG":
          if (check()) {
            let layer = layerManagement.addImageLayer(currentURL);
            addCallback(layer, "IMG", serviceInfo);
          }
          break;
        case "TERRAIN":
          if (check()) {
            let terrainProvider = layerManagement.addTerrainLayer(currentURL, state.isSct);
            addCallback(terrainProvider, "TERRAIN", serviceInfo);
          }
          break;
        case "MVT":
          if (check()) {
            layerManagement.addMvtLayer(currentURL, currentLayerName, (mvtlayer) => {
              addCallback(mvtlayer, "MVT", serviceInfo);
            });
          }
          break;
        case "GEOJSON":
          if (check()) {
            addGeoJsonLayer();
          }
          break;
        case "SHP":
          if (check()) {
            addShpLayer();
          }
          break;
      }
      clearState();
    }

    function clearState() {
      state.layerURL = null;
      state.layerName = null;
      state.isAddToken = false;
      state.token = null;
      state.isSct = false;
    }
    function clear() {
      clearState();
      clearCallback();
    }

    return {
      ...toRefs(state),
      panelStyle,
      addLayer,
      clear,
      handleShpFileChange,
      shpFileInput,
      uploadProgress,
      isUploading
    };
  }
};
</script>

<style scoped>
.shp-upload-container {
  width: 100%;
  margin-bottom: 10px;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>



