<template>
  <div class="home">
    <Header></Header>
    <Map ref="childRef"/>
    <DrawMap></DrawMap>

    <div class="search-box">
      <div class="search-input">
        <el-autocomplete
        v-model="searchText"
        popper-class="custom-dropdown"
        :popper-append-to-body="false"
        :fetch-suggestions="querySearchAsync"
        :placeholder="selectType == '0' ? '请输入地址' : '请输入员工'"
        clearable :clear-icon="CloseBold"
        @select="handleSelect"
        >
          <template #append>
          <el-select v-model="selectType" placeholder="请选择搜索类型" style="width: 80px">
            <el-option label="地址" value="0" />
            <el-option label="员工" value="1" />
          </el-select>
        </template>
        </el-autocomplete>

      </div>
  </div>

  <div class="map-box">
    <div class="map-group">
      <div :class="{'map-item':true,'active':baseMap=='zwb'}" @click="selectMap('zwb')">
        <div style="height: 52px;"><img src="../../public/static/image/zwb.png" class="map-img" mode="scaleToFill" /></div>
        <div class="map-img-name">浅色地图</div>
      </div>
      <div :class="{'map-item':true,'active':baseMap=='asb'}" @click="selectMap('asb')">
        <div style="height: 52px;"><img src="../../public/static/image/asb.png" class="map-img" mode="scaleToFill" /></div>
        <div class="map-img-name">深色地图</div>
      </div>
      <div :class="{'map-item':true,'active':baseMap=='yxt'}" @click="selectMap('yxt')">
        <div style="height: 52px;"><img src="../../public/static/image/yxt.png" class="map-img" mode="scaleToFill" /></div>
        <div class="map-img-name">影像地图</div>
      </div>
    </div>
  </div>

  </div>
</template>
<script>
import mapCommonApi from "@/api/mapCommon";
import commonAPI from "@/api/common";
import Map from "@/components/Map.vue";
import Header from "@/components/Header.vue";
import DrawMap from "@/components/DrawMap.vue";
import { showLoading, hideLoading } from "@/utils/loading";

export default {
  name: "IndexView",
  components: {
    Map,
    Header,
    DrawMap
  },
  data() {
    return {
      baseMap:'zwb',
      searchText: '',
      timeout:  null,
      selectType:'0',
      ygDataList:[]
    };
  },
  mounted() {
    this.initData();
  },
  beforeDestroy() {
    // 在组件销毁前移除事件监听器
  },
  methods: {
    initData(){
      this.getDmsDataList();
    },
    getDmsDataList(){
      const that = this;
      let requestParams = {
        columnId: webConfig.columnArr[0].id,
        states: "0,1,2,3",
        orderBy: JSON.stringify([{ field: "c_xm", orderByType: 2 }]),
        pageSize: 99999,
        page: 0,
      };
      commonAPI.getDmsDataList(requestParams).then((res) => {
        if (res.code == 200){
          let data = res.content.data;
          data = data.map(item => {
            // 给每个属性名称添加 c_ 前缀
            const newItem = {};
            for (const key in item) {
              // 如果已经有c_
              if (key.includes("c_")) {
                let itemkey = key.replace(/c_/g, "");
                newItem['c_' + itemkey] = item[key];
              }else{ 
                newItem[key] = item[key];
              }
            }
            return newItem;
          })
          // console.log("data:", data);
          that.ygDataList = data;
        }else{
          // that.$message({ message: '无员工数据', type: 'info' })
        }
      });
    },
    selectMap(map){
      this.baseMap = map;
      if(map == 'zwb'){
        //切换底图后重新绑定
        window.mapboxMap.on('style.load', this.$refs.childRef.initBaseMap("zwb"));
      }else if(map == 'asb'){
        //切换底图后重新绑定
        window.mapboxMap.on('style.load', this.$refs.childRef.initBaseMap("asb"));
      }else if(map == 'yxt'){
        //切换底图后重新绑定
        window.mapboxMap.on('style.load', this.$refs.childRef.initBaseMap("yxt"));
      }
    },
    querySearchAsync(queryString, cb) {
        let that = this;
        if(queryString == ''){
            if(window.mapboxMap.getSource('point-source')){
              let jsondata = {type: "FeatureCollection",features: []};
              window.mapboxMap.getSource('point-source').setData(jsondata);
            }
            clearTimeout(that.timeout);
            that.timeout = setTimeout(() => {
                cb([]);
            }, 0);
        }else{
          if(that.selectType == "0"){
            that.querySearchAddr(queryString,cb);
          }else{
            that.queryTableData(queryString,cb);
          }
        }
    },
    queryTableData(text,cb){
      const that = this;
      let results = [];
      that.ygDataList.filter(item => {
        if(item.c_xm.includes(text)){
          item.value = item.c_xm;
          results.push(item);
        }
      })
      cb(results);
    },
    querySearchAddr(text,cb){
      let that = this;
      mapCommonApi.getSerachAddress3({
        "address": text
      }).then((res) => {
         let results = res.content.data;
         results.forEach(item => {
            item.value = item.address;
         })
        clearTimeout(that.timeout);
        that.timeout = setTimeout(() => {
            cb(results);
        }, 1000 * Math.random());
      }).catch((err) => {
          clearTimeout(that.timeout);
          that.timeout = setTimeout(() => {
              cb([]);
          }, 0);
      });
    },
    handleSelect(item) {
        let that = this;
        if(that.selectType == "0"){
          if(item){
              let Lon = item.location.split(',')[0]
              let Lat = item.location.split(',')[1]
              let center = [parseFloat(Lon), parseFloat(Lat)]
              window.mapboxMap.flyTo({
                  center: center,
                  zoom: 18,
                  pitch: 0,
              });

            let jsondata = {
                type: 'FeatureCollection',
                features: [
                  {
                    type: 'Feature',
                    properties: {
                      title: item.address,
                      icon: 'location-icon'
                    },
                    geometry: {
                      type: 'Point',
                      coordinates: center
                    }
                  }
                ]
              };

            if(window.mapboxMap.getSource('point-source')){
              window.mapboxMap.getSource('point-source').setData(jsondata);
            }else{
                window.mapboxMap.addSource('point-source', {
                  type: 'geojson',
                  data: jsondata
                });
                window.mapboxMap.addLayer({
                  id: 'location-layer',
                  type: 'symbol', // symbol = 图标/文字图层
                  source: 'point-source',
                  layout: {
                    'icon-image': 'location-icon', // 使用自定义图标
                    'icon-size': 1.5, // 图标大小
                    'icon-allow-overlap': true, // 允许图标重叠
                    'icon-rotate': 0, // 旋转角度
                    'icon-offset': [0, -20] // 图标偏移（上下左右）
                  },
                  paint: {
                    'icon-opacity': 1 // 透明度
                  }
                });
            }
          }
        }else{
          // console.log('[ setItem(guid) ] >');
          sessionStorage.setItem('guid', "");
          that.$refs.childRef.setTableShow(that.searchText)
        }
    },

  }
};

</script>

<style>
.el-select__wrapper{
  min-height: 40px !important;
  background: transparent  !important;
  /* box-shadow: 0 0 0 1px #01346fe0 inset; */
}
.el-select__placeholder{
  color: #fff !important;
}
.el-tag.el-tag--info{
    --el-tag-text-color: #ffffff !important;
}
.el-tag.el-tag--info {
    --el-tag-bg-color: #f3f3f700;
}

.el-popper.is-light{
  background: #01346fe0 !important;
  border: 1px solid #01346fe0 !important;
  max-width: none !important;
}
.el-select-dropdown__item{
  color: #fff !important;
}
.el-select-dropdown__item.is-hovering{
  background: linear-gradient(to right, #01346fe0, #02a7bd, #01346fe0) !important;
  color: #fff !important;
}
</style>

<style lang="less" scoped>

.home {
  width: 100%;
  height: 100%;
  // position: relative;
  // user-select: none;
  /* Chrome, Opera, Safari */
  // -moz-user-select: none;
  /* Firefox */
  // -ms-user-select: none;
  /* Internet Explorer/Edge */
  // -khtml-user-select: none;
  /* Konqueror/Safari */
  // -webkit-user-select: none;
  /* Webkit */
  // user-select: none;
  /* 标准语法 */
}
.search-box {
  position: absolute;
  top: 60px;
  left: 42%;
  z-index: 999;
  padding: 12px 20px;
  width: 400px;
  .search-input{
    -webkit-backdrop-filter: blur(5px);
    backdrop-filter: blur(5px);
    background: #01346f99;
    border-radius: 4px;
  }
}
.map-box{
    position: fixed;
    right: 50px;
    bottom: 50px;
    display: flex;
    align-items: center;
    z-index: 10;
    .map-group{
      display: flex;
      gap: 5px;
      align-items: center;
      background-color: #01346f3d;
      border: 1px solid #01346f3d;
      padding: 5px;
      border-radius: 5px;
      .map-item{
        display: grid;
        // gap: 0px 10px;
        // align-items: center;
        text-align: center;
        border-radius: 5px;
        // background: white;
        cursor: pointer;
        border: 2px solid #2881f600;
      }
      .map-item:hover{
        color: #2880f6;
        border: 2px solid #2880f6;
      }
      .active{
        color: #2880f6;
        border: 2px solid #2880f6;
      }
      .map-img{
          width: 80px;
          height: 100%;
          border-radius: 3px 3px 0px 0px;
        }
      .map-img-name{
        padding-bottom: 5px;
        background: #fff;
        border-radius: 0px 0px 3px 3px;
      }
    }
}
</style>