<!--
 * @Descripttion: 
 * @version: 
 * @Author: ysh
 * @Date: 2022-10-20 17:27:09
 * @LastEditors: wrh
 * @LastEditTime: 2026-02-03 10:50:07
-->
<template>
  <div class="layer-box">
    <div class="checkList">
      <el-checkbox-group v-model="checkList">
        <el-checkbox label="水系" @change="checkedSx" />
        <el-checkbox label="范围" @change="checkedRange" />
        <el-checkbox label="控制点" @change="checkedCp" />
      </el-checkbox-group>
    </div>
    <div style="margin-top: 10px;">
      <!-- <el-button @click="handleExpand">展开/折叠</el-button> -->
      <el-button @click="handleAllSelect">全选</el-button>
      <el-button @click="handleCancelSelect">全不选</el-button>
    </div>
    <div style="margin-top: 10px;">
      <el-input v-model="filterInput" class="w-50 m-2" placeholder="请输入项目编号" @keyup.enter="handleFilterNode">
        <template #append>
          <el-button icon="el-icon-search" @click="handleFilterNode"></el-button>
        </template>
      </el-input>
    </div>
    <el-scrollbar class="list-tree-div">
      <el-tree class="filter-tree" :data="treeDatas" :props="defaultProps" node-key="id" show-checkbox ref="projectTree"
        :default-checked-keys="selectedNodeKey" @check-change="handleCheckChange" default-expand-all
        @node-click="handleNodeClick" highlight-current :filter-node-method="filterNode" />
    </el-scrollbar>
  </div>
</template>

<script>
import sjx from '@/assets/images/gis/sjd-active.png';
import { listProject, getProjectKml } from "@/api/file/project";
// ------------------------------------------------ol--------------------------------------------------------------------//
import 'ol/ol.css'
import { Map, View } from 'ol';
import KML from 'ol/format/KML';
import Overlay from 'ol/Overlay';
import Feature from 'ol/Feature';
import { toLonLat } from 'ol/proj';
import TileLayer from 'ol/layer/Tile';
import { Select } from "ol/interaction";
import VectorLayer from 'ol/layer/Vector';
import { boundingExtent } from 'ol/extent';
import { Cluster, Vector as VectorSource, XYZ } from 'ol/source';
import { Point, Polygon, MultiPolygon, MultiLineString } from 'ol/geom';
import { toStringXY, createStringXY, toStringHDMS } from 'ol/coordinate';
import { Circle, Fill, Stroke, Style, RegularShape, Icon, Text } from 'ol/style';
import { MousePosition, ScaleLine, defaults as defaultControls } from 'ol/control';
import { linear, easeIn } from 'ol/easing';
// --------------------------------------------------------------------------------------------------------------------//

export default {
  props: {
    proTree: {
      type: Array,
      required: true
    },
  },
  data() {
    return {
      kmlPath: process.env.VUE_APP_BASE_API,
      sxLayer: new VectorLayer({
              style: new Style({
                stroke: new Stroke({
                  color: '#0000ff',
                  width: 2
                })
              }),
              source: new VectorSource({
                url: process.env.VUE_APP_BASE_API + "/profile/upload/uploadKmlFiles/shuixi.kml",
                format: new KML({
                  extractStyles: false
                }),
                projection: 'EPSG:4326'
              })
            }),
      treeDatas: [],
      selectedNodeKey: [],
      allNodeKey: [],
      checkList: ['范围', '控制点'],
      filterInput: '',
      defaultProps: { label: 'name', children: 'children' }
    };
  },
  mounted() {
    this.initTree();
  },
  methods: {
    initTree() {
      let param = {
        pageNum: 1,
        pageSize: 99999999
      }
      if (this.$store.getters.roles.includes('projectLeader') && !this.$store.getters.roles.includes('leader')) {
        param.projectLeader = this.$store.getters.userId
      }
      listProject(param).then(res => {
        if (res.code == 200) {
          let alldata = res.rows;
          let tree = [];
          for (let d of alldata) {
            if (d.kmlLat && d.kmlLng) {
              tree.push(d);
            }
          }
          let list = [];
          let selectList = [];
          for (let t of tree) {
            let kmlUrl = this.kmlPath + "/profile/upload" + t.projectKml;
            let cpUrl = this.kmlPath + "/profile/upload" + t.projectCp;
            let obj = {};
            obj.id = t.projectNumber;
            obj.name = t.projectNumber + '-' + t.projectName;
            let color = 'rgba(' + parseInt(Math.random() * 255) + ',' + parseInt(Math.random() * 255) + ',' + parseInt(Math.random() * 255) + ',0.8)';
            obj.range = new VectorLayer({
              title: t.projectNumber,
              style: new Style({
                // fill: new Fill({
                //   color: color,
                // }),
                stroke: new Stroke({
                  color: '#30A9DE',
                  width: 3
                })
              }),
              source: new VectorSource({
                url: kmlUrl,
                format: new KML({
                  extractStyles: false
                }),
                projection: 'EPSG:4326'
              })
            });
            obj.cp = new VectorLayer({
              title: t.projectNumber,
              // style: new Style({
              //   image: new Icon({
              //     src: sjx,
              //     crossOrigin: 'anonymous',
              //   }),
              //   fill: new Fill({
              //     color: '#30A9DE',
              //   })
              // }),
              style: this.cpStyle(obj),
              source: new VectorSource({
                url: cpUrl,
                format: new KML({
                  extractStyles: false,
                  writeStyles: true,
                  showPointNames: true
                }),
                projection: 'EPSG:4326'
              })
            });
            selectList.push(obj.id);
            obj.range.setVisible(false);
            obj.cp.setVisible(false);
            this.$store.getters.map.addLayer(obj.range);
            this.$store.getters.map.addLayer(obj.cp);
            list.push(obj);
            // this.$refs.projectTree.setCheckedKeys(selectList);
          }
          this.treeDatas = list;
          this.allNodeKey = selectList;
        }
      })
      this.sxLayer.setVisible(false);
      this.$store.getters.map.addLayer(this.sxLayer);
    },
    /* 全选 */
    handleAllSelect() {
      this.$refs.projectTree.setCheckedKeys(this.allNodeKey);
    },
    /* 全不选 */
    handleCancelSelect() {
      this.$refs.projectTree.setCheckedKeys([]);
    },
    // 筛选
    filterNode(value, data) {
      if (!value)
        return true
      return data.name.includes(value)
    },
    // 触发筛选
    handleFilterNode() {
      this.$refs.projectTree.filter(this.filterInput)
    },
    handleCheckChange(data, checked, indeterminate) {
      if (this.checkList.indexOf('范围') != -1) {
        data.range.setVisible(checked);
      } else {
        data.range.setVisible(false);
      }
      if (this.checkList.indexOf('控制点') != -1) {
        data.cp.setVisible(checked);
      } else {
        data.cp.setVisible(false);
      }
    },
    handleNodeClick(nodeObj) {
      let checkedKeys = this.$refs.projectTree.getCheckedKeys();
      let currentKey = this.$refs.projectTree.getCurrentKey();
      if (checkedKeys.includes(currentKey)) {
        let view = this.$store.getters.map.getView();
        let source = nodeObj.range.getSource();
        view.fit(source.getExtent());
      } else {
        checkedKeys.push(currentKey);
        this.$refs.projectTree.setCheckedKeys(checkedKeys);
        setTimeout(() => {
          let view = this.$store.getters.map.getView();
          let source = nodeObj.range.getSource();
          view.fit(source.getExtent());
        }, 200);
      }
    },
    checkedSx(val) {
      this.sxLayer.setVisible(val);
    },
    checkedRange(val) {
      let datas = this.$refs.projectTree.getCheckedNodes();
      for (let d of datas) {
        d.range.setVisible(val);
      }
    },
    checkedCp(val) {
      let datas = this.$refs.projectTree.getCheckedNodes();
      for (let d of datas) {
        d.cp.setVisible(val);
      }
    },
    cpStyle(obj) {
      let feature = obj;
      let style = new Style({
        image: new Icon({
          src: sjx,
          crossOrigin: 'anonymous',
        }),
        fill: new Fill({
          color: '#30A9DE',
        }),
        text: new Text({
          text: this.getText(feature),
          font: '14px sans-serif',
          textAlign: 'center',
          textBaseline: 'middle',
          justify: 'center',
          // backgroundFill: new Fill({
          //   color: '#fff',
          // }),
          stroke: new Stroke({
            color: '#F9F871',
            width: 2
          }),
          offsetY: -30,
          padding: [1, 1, 1, 1]
        })
      });
      return style
    },
    /* 根据缩放决定text是否显示 */
    getText(feature, resolution) {
      let reo = resolution * 100;
      let text;
      if (reo > 2) {
        text = '';
      } else {
        text = feature.name;
      }
      return text;
    },
  },
}
</script>

<style lang="scss" scoped>
.checkList {
  display: flex;
  text-align: center;
  justify-content: center;
  border: 1px dashed #bccfec;
}

.list-tree-div {
  width: 280px;
  height: 660px;
  overflow: auto;
  background: none;
  flex-grow: 1;
  display: flex;

  .el-scrollbar {
    display: flex;
    padding: 2.6px 16px 16px 0;
    width: 280px;

    .el-scrollbar__wrap {
      overflow-x: hidden;
      overflow-y: auto;
      min-width: 250px;

      .el-tree.filter-tree {
        .el-tree-node {
          >.el-tree-node__content {
            /* 让纵向滚动条与内容最右边界限之间留有8px的宽度，使效果更好看。 */
            padding: 0 8px 0 0;

            .el-tree-node__expand-icon {
              margin: -2 0 0 3px;
              padding: 0;
            }

            >label.el-checkbox {
              margin-right: 4px;
              margin-bottom: 0px;
              font-size: 12px;
            }

            .el-tree-node__label {
              font-size: 12px;
              line-height: 12px;
            }
          }

          .el-tree-node__children {
            /* 出现横轴滚动条 */
            display: inline-block;
            min-width: 100%;
          }

        }
      }

    }

    .el-scrollbar__bar {
      &.is-horizontal {
        bottom: 0;
      }

      &.is-vertical {
        right: 0;
      }
    }
  }
}

:deep(.el-checkbox__label) {
  color: var(--el-tree-text-color) !important;
}

:deep(.el-tree-node) {
  white-space: normal;
}

:deep(.el-tree-node__content) {
  height: 100%;
  align-items: baseline;
}

:deep(.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content) {
  background-color: #bccfec !important;
}</style>