<template>
  <div class="layer-list-panel">
    <div class="layer-list-panel-title">
      <div class="title">
        <img src="@/assets/image/common/layerIcon.png" alt="" />
        <span style="margin-left: 0.08rem">资源列表</span>
      </div>
      <div @click="onExpandChange" style="cursor: pointer">
        <img v-show="isExpanded" src="@/assets/image/common/arrow-up.png" style="width: 14px; height: 12px" />
        <img v-show="!isExpanded" src="@/assets/image/common/arrow-up.png" style="transform: rotate(180deg); width: 14px; height: 12px" />
      </div>
    </div>

    <div class="layer-list-panel-content" v-show="isExpanded">
      <el-tree ref="tree" :data="treeData" show-checkbox node-key="id" :props="defaultProps" @check-change="onCheckChange" :default-expanded-keys="['1']">
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
            <i v-if="data.loading" class="el-icon-loading" style="margin-left: 4px; color: #409eff"></i>
            <i v-if="data.error" class="el-icon-warning" style="margin-left: 4px; color: #f56c6c" :title="data.error"></i>
          </span>
        </template>
      </el-tree>
    </div>
  </div>
</template>

<script>
import * as mars3d from 'mars3d'
let layerCache = {}
export default {
  name: 'LayerListView',
  data() {
    return {
      isExpanded: true,
      defaultProps: { children: 'children', label: 'label' },
      treeData: [
        {
          id: '1',
          label: '综合信息',
          children: [
            {
              id: '1-1',
              label: '生态区',
              children: [
                { id: '1-1-1', label: '提防背河坡脚线', meta: { type: 'polyline', url: '/geojson/difangbeihe.geojson' } },
                { id: '1-1-2', label: '河道管理范围线', meta: { type: 'polyline', url: '/geojson/hedaoguanli.geojson' } },
                { id: '1-1-3', label: '一二级管控区界限', meta: { type: 'polyline', url: '/geojson/yijiguanxian.geojson' } },
                { id: '1-1-4', label: '生态区界限', meta: { type: 'polyline', url: '/geojson/shengtaiqu.geojson' } },
                { id: '1-1-5', label: '城市核心区', meta: { type: 'polyline', url: '/geojson/chengshihx.geojson' } },
                { id: '1-1-6', label: '农村区段', meta: { type: 'polyline', url: '/geojson/nongcunqd.geojson' } },
                { id: '1-1-7', label: '规划区', meta: { type: 'polyline', url: '/geojson/guihuaqu.geojson' } },
                { id: '1-1-8', label: '城市核心区（右岸）', meta: { type: 'polyline', url: '/geojson/chengshihx_r.geojson' } },
                { id: '1-1-9', label: '农村区段（右岸）', meta: { type: 'polyline', url: '/geojson/nongcunqd_r.geojson' } }
              ]
            },
            { id: '1-2', label: '监测设备' },
            { id: '1-3', label: '入河排水（污）口' },
            { id: '1-4', label: '河道管理站' }
          ]
        },
        {
          id: '2',
          label: '水文监测',
          children: [
            { id: '2-1', label: '水文监测点1', meta: { type: 'point', url: '/geojson/sw1.geojson' } },
            { id: '2-2', label: '水文监测点2', meta: { type: 'point', url: '/geojson/sw2.geojson' } }
          ]
        },
        {
          id: '3',
          label: '采砂区',
          children: [
            { id: '3-1', label: '兴平市宜空采砂区', meta: { type: 'polygon', url: '/geojson/yikong.geojson' } },
            { id: '3-2', label: '兴平市团结采砂区', meta: { type: 'polygon', url: '/geojson/tuanjie.geojson' } },
            { id: '3-3', label: '兴平市汤坊龙兴1区采砂区', meta: { type: 'polygon', url: '/geojson/longxing.geojson' } }
          ]
        }
      ]
    }
  },
  methods: {
    onExpandChange() {
      this.isExpanded = !this.isExpanded
    },

    async onCheckChange(node, checked) {
      const id = node.id
      if (!node.meta?.url) {
        return
      }
      if (checked) {
        // 已缓存直接显示
        if (layerCache[id]) {
          layerCache[id].show = true
          return
        }
        // 开始加载
        this.$set(node, 'loading', true)
        this.$set(node, 'error', '')
        try {
          const layer = new mars3d.layer.GeoJsonLayer({
            name: node.label,
            url: node.meta.url,
            crs: 'EPSG:4326',
            clampToGround: true,
            symbol: this.getStyleByName(node.label)
          })
          window.map.addLayer(layer)
          layerCache[id] = layer
          // 父子关联：勾选子节点时，父节点作为 groupId
          const parent = this.$refs.tree.getNode(id).parent
          if (parent && parent.data.id) {
            layer.options.parentId = parent.data.id
          }
        } catch (e) {
          this.$set(node, 'error', e.message || '加载失败')
        } finally {
          this.$set(node, 'loading', false)
        }
      } else {
        // 取消勾选 -> 销毁
        if (layerCache[id]) {
          window.map.removeLayer(layerCache[id])
          delete layerCache[id]
        }
      }
    },
    getStyleByName(name) {
      if (name === '生态区界限') {
        return { type: 'polyline', styleOptions: { color: '#0c5b0f', width: 4 } }
      } else if (name === '河道管理范围线') {
        return {
          type: 'polyline',
          styleOptions: { width: 4, materialType: mars3d.MaterialType.PolylineDash, materialOptions: { color: '#0c5b0f', dashLength: 40 } }
        }
      } else if (name === '一二级管控区界限') {
        return { type: 'polyline', styleOptions: { color: '#db7f06', width: 4 } }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.layer-list-panel {
  position: absolute;
  top: px-to-rem(80);
  left: px-to-rem(480);
  width: px-to-rem(240);
  padding: px-to-rem(10);
  background: #1b2535;
  border-radius: 6px;
  opacity: 0.85;
  z-index: 1000;
  .layer-list-panel-title {
    margin-bottom: px-to-rem(10);
    height: px-to-rem(30);
    line-height: px-to-rem(30);
    display: flex;
    justify-content: space-between;
    align-items: center;
    .title {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: px-to-rem(18);
      color: #eaf3fe;
    }
  }
  .layer-list-panel-content {
    margin: px-to-rem(-10);
    padding: px-to-rem(10);
    max-height: px-to-rem(340);
    overflow: auto;
    :deep(.el-tree) {
      background: transparent;
      color: #fff;
      .el-tree-node__content {
        height: unset;
      }
      .el-tree-node__content:hover,
      .el-upload-list__item:hover,
      .el-tree-node:focus > .el-tree-node__content {
        background-color: transparent;
        height: unset;
      }
      .el-tree-node__label {
        white-space: wrap;
      }
    }
  }
}
</style>
