<template>
  <div class="BoxCommonVector" v-if="title">
    <div class="innerContainerVector leftPaneVector" v-drag>
      <h2 class="PangetitleVector darg-div">
        <span class="pange_textVector">{{ title }}</span>
      </h2>
      <i class="el-icon-close" @click="close"></i>
      <el-input
        v-if="word"
        clearable
        v-model="state"
        @input="change_witch"
        class="search"
        placeholder="请输入内容"
      ></el-input>
      <div class="searchDiv" v-else>
        <div class="sidiv" v-for="sitem in searchs" :key="sitem.key">
          <el-input
            v-if="sitem.type == 'input'"
            clearable
            v-model="searchform[sitem.key]"
            @input="change_witch"
            class="search"
            :placeholder="sitem.label"
          ></el-input>
          <el-select
            v-else-if="sitem.type == 'select'"
            clearable
            v-model="searchform[sitem.key]"
            :placeholder="sitem.label"
            @change="change_witch"
          >
            <el-option
              v-for="item in sitem.options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <!-- clearable -->
          <el-cascader
            v-else-if="sitem.type == 'cascader'"
            v-model="searchform[sitem.key]"
            :show-all-levels="false"
            :options="sitem.options"
            :placeholder="sitem.label"
            :props="{
              checkStrictly: true,
              expandTrigger: 'hover',
              emitPath: false,
            }"
            @change="change_witch"
          ></el-cascader>
        </div>
      </div>
      <el-table
        :row-class-name="tableRowClassName"
        ref="singleTable"
        :data="active_dableData"
        style="width: 100%"
        height="650"
        :header-cell-style="{
          background: 'rgba(10, 25, 38, 0.6)',
          color: '#66b1ff',
          fontSize: '14px',
          fontFamily: 'Microsoft YaHei',
          fontWeight: '400',
        }"
      >
        <el-table-column
          show-overflow-tooltip="true"
          v-for="(item, index) in store.state.cockpit_vector.columns"
          :key="index"
          :width="index ? 100 : 150"
          :prop="item"
          :label="item"
        >
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="50">
          <template slot-scope="scope">
            <!-- <el-button @click="info(scope.row)" type="text" size="small">详情</el-button> -->
            <el-button @click="go(scope.row)" type="text" size="small"
              >定位</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
  
<script>
import { QueryOne, QueryList } from "@/api/cockpitNew";
import * as tdsy from "@/views/cockpit/js/tdsy";

import * as wellknown from "wellknown";
import * as turf from "@turf/turf";

let BoxCommonVector_entity = null;
let layerSources = {};
export default {
  data() {
    return {
      state: "",
      timeout: null,
      title: "",
      active_dableData: null,
      tableData: null,
      layersData: {},
      scrollTop_index: null,
      tempdataLayerId: null,
      searchs: [],
      searchform: {},
      xzqTreeData: [],
    };
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === this.scrollTop_index) {
        return "warning-row";
      }
      return "";
    },
    async draw_vector_server(jscType, goitrem) {
      let res = await QueryOne({ jscType, id: "4602" });
      this.layersData = { ...res.data, title: this.title };
      if (goitrem) this.go(goitrem);
      else tdsy.addLayer(this.layersData);
      // this.Getlayers(res.data.url);
    },
    async Getlayers(mapurl) {
      let url = `${mapurl}/layers.json`;
      let res = await axios.get(url);
      let layers = res.data[0].subLayers.layers;
      if (layers.length > 0) this.layersData.layerName = layers[0].name;
    },
    async setLayerStatus(item) {
      let did_v = Number(item.did) - 1;
      this.tempdataLayerId = did_v;
      if (tdsy.layersObj[did_v]) {
        tdsy.layersObj[did_v].show = true;
        viewer.flyTo(layerSources[did_v], {
          offset: new Cesium.HeadingPitchRange(0, -45),
        });
      } else {
        if (tdsy.layer) tdsy.layer.show = false;
        let layer = viewer.imageryLayers.addImageryProvider(
          new Cesium.SuperMapImageryProvider({
            url: this.layersData.url,
            layersID: `[${did_v}]`,
          })
        );
        tdsy.layersObj[did_v] = layer;
        this.loadGeoJSON(item.geom, did_v);
      }
      // } else if (this.layersData.layerName) {
      //   var params_gh = {
      //     layerName: this.layersData.layerName,
      //     isVisible: true,
      //     displayFilter: `xmmc = '${item["项目名称"]}'`,
      //   };
      //   tdsy.superProvider.setLayerStatusParameters([params_gh]);
      //   tdsy.layer.show = false;
      //   let layer = viewer.imageryLayers.addImageryProvider(tdsy.superProvider);
      //   tdsy.layersObj[item.did] = layer;
    },
    loadGeoJSON(geojson, id) {
      let polygon = Cesium.GeoJsonDataSource.load(geojson, {
        clampToGround: true,
        stroke: Cesium.Color.RED.withAlpha(0),
        fill: Cesium.Color.WHITE.withAlpha(0),
      });
      polygon.then(function (dataSource) {
        viewer.dataSources.add(dataSource);
        layerSources[id] = dataSource;
        viewer.flyTo(dataSource, {
          offset: new Cesium.HeadingPitchRange(0, -45),
        });
      });
    },
    multiPolygonToPolygons(multiPolygon) {
      const polygons = [];
      multiPolygon.coordinates.forEach((polygonCoordinates) => {
        polygons.push({
          type: "Polygon",
          coordinates: polygonCoordinates,
        });
      });
      return polygons;
    },
    // draw_vector_tdgy_gy_jd(data) {
    //     const that = this;
    //     data.forEach((res) => {
    //         res.type = this.title
    //         if (res.geom) {
    //             res.geom.coordinates.forEach((res_coordinates) => {
    //                 // let arrayt = [];
    //                 // if (res_coordinates.length == 1) {
    //                 //     arrayt = res_coordinates[0]
    //                 //     const twoDArray = arrayt;
    //                 //     const oneDArray = twoDArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
    //                 //     tdsy.add(res, oneDArray);
    //                 // } else {
    //                 //     // arrayt = res_coordinates
    //                 // }

    //                 // 多面转单面
    //                 // if (res.geom.type == 'MultiPolygon') {
    //                 //     let polygons = that.multiPolygonToPolygons(geojson);

    //                 //     // 在
    //                 //     polygons.forEach((res) => {
    //                 //         that.add_viewer_for_vector(res, data);
    //                 //         tdsy.add(res, oneDArray);

    //                 //     })
    //                 // } else {

    //                 // }

    //             })
    //         }
    //     })
    // },
    draw_vector_tdgy_gy_jd(data) {
      // tdsy.remove();
      data.forEach((res, index) => {
        res.type = "图斑上图";
        res.index = index;
        if (res.geom) {
          let geojson = res.geom;
          if (geojson.type == "MultiPolygon") {
            geojson.coordinates.forEach((res) => {
              const twoDArray = res[0];
              const oneDArray = twoDArray.reduce(
                (accumulator, currentValue) => accumulator.concat(currentValue),
                []
              );

              tdsy.add(res, oneDArray);
            });
          } else {
            const twoDArray = geojson.coordinates[0];
            const oneDArray = twoDArray.reduce(
              (accumulator, currentValue) => accumulator.concat(currentValue),
              []
            );
            tdsy.add(res, oneDArray);
          }
        }
      });
    },
    close() {
      store.setViewerFlagb(true);
      tdsy.remove();
      store.state.vectorData = [];
      store.hideToolBar();
    },
    info() {},
    switch_show(flag) {
      BoxCommonVector_entity.entities.values.forEach((res) => {
        res.show = flag;
      });
    },
    build_data(geojson) {
      geojson.coordinates.forEach((res) => {
        const twoDArray = res[0];
        const oneDArray = twoDArray.reduce(
          (accumulator, currentValue) => accumulator.concat(currentValue),
          []
        );

        BoxCommonVector_entity.entities.add({
          polygon: {
            // 获取指定属性（positions，holes（图形内需要挖空的区域））
            hierarchy: {
              positions: Cesium.Cartesian3.fromDegreesArrayHeights(
                oneDArray.slice(0, -3)
              ),
            },
            // 边框
            outline: true,
            // 边框颜色
            outlineColor: Cesium.Color.RED,
            // 边框尺寸
            outlineWidth: 10,
            // 填充的颜色，withAlpha透明度
            material: Cesium.Color.GREEN.withAlpha(0),
            // 是否被提供的材质填充
            fill: false,
            // 恒定高度
            height: 1.1,
            // 显示在距相机的距离处的属性，多少区间内是可以显示的
            // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(1000, 10000000),
            // 是否显示
            show: true,
            // 顺序,仅当`clampToGround`为true并且支持地形上的折线时才有效。
            zIndex: 10,
          },
        });

        // 注意：polygon首尾坐标要一致
        var polygon = turf.polygon([twoDArray]);

        var centroid = turf.centroid(polygon).geometry.coordinates;

        viewer.camera.flyTo({
          duration: 1,

          destination: Cesium.Cartesian3.fromDegrees(
            centroid[0],
            centroid[1],
            3000
          ),
          // destination: {
          //     x: -6283267.004204832,
          //     y: 28123682.896774407,
          //     z: 23709669.98539126
          // },
          orientation: {
            heading: 6.149339593573709,
            pitch: -1.539825618847483,
            roll: 0,
          },
        });
      });
    },
    go(item) {
      if (!item.geom) {
        this.$message.warning("缺少定位图斑");
      } else {
        if (this.cockpit_vector.mapType) {
          this.setLayerStatus(item);
        } else this.addpolygon(item);
      }
      store.setVectordataid(item.dataid);
      let arr = [];
      // BoxCommonVector_entity = new Cesium.CustomDataSource("BoxCommonVector_entity");
      // viewer.dataSources.add(BoxCommonVector_entity);

      Object.keys(item).forEach((key) => {
        arr.push({
          name: key,
          value: item[key],
        });
      });
      store.state.vectorData = arr;
      store.setActiveToolBar(9);
    },
    addpolygon(item) {
      const that = this;
      let geojson = item.geom;

      if (geojson.type == "MultiPolygon") {
        this.build_data(geojson);
      } else {
        const twoDArray = geojson.coordinates[0];
        const oneDArray = twoDArray.reduce(
          (accumulator, currentValue) => accumulator.concat(currentValue),
          []
        );
        BoxCommonVector_entity.entities.add({
          polygon: {
            // 获取指定属性（positions，holes（图形内需要挖空的区域））
            hierarchy: {
              positions: Cesium.Cartesian3.fromDegreesArrayHeights(
                oneDArray.slice(0, -3)
              ),
            },
            // 边框
            outline: true,
            // 边框颜色
            outlineColor: Cesium.Color.RED,
            // 边框尺寸
            outlineWidth: 10,
            // 填充的颜色，withAlpha透明度
            material: Cesium.Color.GREEN.withAlpha(0),
            // 是否被提供的材质填充
            fill: false,
            // 恒定高度
            height: 1.1,
            // 显示在距相机的距离处的属性，多少区间内是可以显示的
            // distanceDisplayCondition: new Cesium.DistanceDisplayCondition(1000, 10000000),
            // 是否显示
            show: true,
            // 顺序,仅当`clampToGround`为true并且支持地形上的折线时才有效。
            zIndex: 10,
          },
        });

        // 注意：polygon首尾坐标要一致
        var polygon = turf.polygon([geojson.coordinates[0]]);

        var centroid = turf.centroid(polygon).geometry.coordinates;

        viewer.camera.flyTo({
          duration: 1,

          destination: Cesium.Cartesian3.fromDegrees(
            centroid[0],
            centroid[1],
            3000
          ),
          // destination: {
          //     x: -6283267.004204832,
          //     y: 28123682.896774407,
          //     z: 23709669.98539126
          // },
          orientation: {
            heading: 6.149339593573709,
            pitch: -1.539825618847483,
            roll: 0,
          },
        });
      }

      let flag = true;
      let time = setInterval(() => {
        flag = !flag;
        that.switch_show(flag);
      }, 500);
      setTimeout(() => {
        clearInterval(time);
        for (var i = 0; i < 10; i++) {
          BoxCommonVector_entity.entities.values.forEach((res) => {
            BoxCommonVector_entity.entities.remove(res);
          });
        }
      }, 6000);
    },
    change_witch() {
      if (this.word) this.get_searchWord(this.state);
      else this.init_vector(this.searchform);
    },
    // get_search(word) {
    //     if (word.length == 0) {
    //         this.active_dableData = this.tableData;
    //     } else {
    //         let gy_ju = {
    //             beginTime: store.state.cockpit_date[0],
    //             endTime: store.state.cockpit_date[1],
    //             jscType: store.state.cockpit_vector.tablejscType + '_cx',
    //             id: '4602',
    //             val0: word,

    //         }
    //         if (this.title == '土地供应完成项目' || this.title == '山水工程项目') {
    //             gy_ju.beginTime = undefined
    //             gy_ju.endTime = undefined
    //         }

    //         Promise.all([QueryList(gy_ju)]).then((values) => {
    //             values[0].data.map((res) => {
    //                 if (res.geom) {
    //                     res.geom = wellknown.parse(res.geom.split(";")[1]);
    //                 }
    //             })
    //             this.active_dableData = values[0].data

    //         }).catch((error) => {
    //             console.error(error); // 如果有任何一个 promise 失败，则捕获这个错误
    //         });
    //     }

    // },

    get_searchWord() {
      if (this.state.length == 0) {
        this.active_dableData = this.tableData;
        console.log("this.active_dableData: ", this.active_dableData);
      } else {
        // console.log('this.tableData: ', this.tableData);
        // this.active_dableData = this.tableData.filter((item) => {
        //     item.项目名称.indexOf(word) >= 0
        // })
        console.log("this.tableData: ", this.word);

        this.active_dableData = this.tableData.filter((item) => {
          console.log("item: ", item);
          if (item[this.word] && this.state) {
            return item[this.word].indexOf(this.state) >= 0;
          }
          return false;
        });
      }
    },
    async init_vector(params) {
      const that = this;

      let obj = {
        jscType: store.state.cockpit_vector.tablejscType,
        beginTime: store.state.cockpit_date[0],
        endTime: store.state.cockpit_date[1],
        id: store.state.cockpit_region.id,
        ...params,
      };
      if (this.title == "土地供应完成项目" || this.title == "山水工程项目") {
        obj.beginTime = undefined;
        obj.endTime = undefined;
      }
      if (this.title == "进出平衡") {
        (obj.jscType = "jsc_gdbh_jcph_zbmc"),
          (obj.val2 = 0),
          (obj.val1 = 50000),
          (obj.beginTime = store.state.cockpit_date[1].slice(0, 4)),
          (obj.endTime = undefined);
      }
      if (this.title == "土地收储计划项目") {
        obj.beginTime = undefined;
        obj.endTime = undefined;
      }
      let data = await QueryList(obj);
      data.data.map((res) => {
        if (res.geom) {
          res.geom = wellknown.parse(res.geom.split(";")[1]);
        }
      });
      this.active_dableData = data.data;
      this.tableData = data.data;
    },
  },
  computed: {
    cockpit_vector() {
      return store.state.cockpit_vector;
    },
    computed_vectorData() {
      return store.state.vectorData;
    },
  },
  watch: {
    cockpit_vector(newVal, oldVal) {
      this.title = newVal.title;
      console.log("---", newVal);
      this.word = newVal.word;
      this.searchs = newVal.searchs;
      this.searchform = newVal.searchform;
      this.state = "";
      if (newVal.goitem) {
        this.draw_vector_server(newVal.mapType, newVal.goitem);
      } else if (newVal.tableData && newVal.tableData.length > 0) {
        this.active_dableData = []; //防止重复点击tableData不刷新
        this.active_dableData = newVal.tableData;
        this.tableData = newVal.tableData;
        // this.init_vector()
      } else if (this.title) {
        this.init_vector();
      }
    },
    active_dableData(newVal, oldVal) {
      if (this.cockpit_vector.mapType)
        this.draw_vector_server(this.cockpit_vector.mapType);
      else this.draw_vector_tdgy_gy_jd(newVal);
    },
    tempdataLayerId(newVal, oldVal) {
      if (oldVal && tdsy.layersObj[oldVal]) {
        tdsy.layersObj[oldVal].show = false;
      } else if (tdsy.layersObj[newVal]) {
        // tdsy.layersObj[newVal].show = true;
      }
      console.log(newVal, oldVal, "----");
    },
    computed_vectorData(newVal, oldVal) {
      newVal.forEach((res) => {
        if (res.name == "index") {
          const TableRows = this.$refs.singleTable.bodyWrapper.querySelectorAll(
            ".el-table__body tbody .el-table__row"
          );
          let scrollTop = 0;
          for (let i = 0; i < TableRows.length; i++) {
            if (i === res.value) {
              break;
            }
            scrollTop += TableRows[i].offsetHeight;
          }
          this.$refs.singleTable.bodyWrapper.scrollTop = scrollTop;
          this.scrollTop_index = res.value;
        }
      });
    },
  },
  mounted() {
    const that = this;
    this.$nextTick(() => {
      BoxCommonVector_entity = new Cesium.CustomDataSource(
        "BoxCommonVector_entity"
      );
      viewer.dataSources.add(BoxCommonVector_entity);
    });
  },
};
</script>
  


<style lang="scss" scoped>
div::-webkit-scrollbar {
  width: 9px;
  height: 19px;
}
.BoxCommonVector {
  width: 100%;
  height: 100%;
  position: absolute;
  left: -1rem;
  top: 0rem;
}

.innerContainerVector {
  width: 350px;
  height: 760px; //calc(100% - 20px);
  position: absolute;
  top: 28px;
  z-index: 99;
  background-image: url("/static/images/ghzc/内容框.png");
  background-size: 100% 100%;
  border-top-right-radius: 15px;
  .searchDiv {
    width: 100%;
    display: flex;
    justify-content: space-between;
    margin-right: 10px;
    .sidiv {
      //   min-width: calc(50% - 10px);
      height: 40px;
      margin-bottom: 5px;
      margin-right: 5px;
      display: inline-block;
    }
  }

  .search {
    // margin: 2rem;
  }

  /deep/ .el-input {
    display: inline-block;
  }

  /deep/ .el-input__inner {
    // background: transparent !important;
    color: white !important;
    background: rgba(10, 25, 38, 0.5);
    border-color: #5ecef09a;
    // color: #64daff;
    // font-size: 12px;
  }
}

.leftPaneVector {
  left: 20px;

  .el-icon-close {
    width: 22px;
    height: 22px;
    color: #fff !important;
    background-color: #335f87;
    line-height: 23px;
    padding: 0 5px;
    border-radius: 4px;
    top: -1.9rem !important;
    position: relative;
    right: -19.5rem;
  }

  .PangetitleVector {
    box-sizing: border-box;
    width: 100%;
    height: 35px;
    background: url("/static/images/overview/titlebox.gif") no-repeat !important;
    background-size: 100% 100% !important;
    line-height: 35px;
    font-size: 14px;
    padding-left: 15px;
    display: flex;
    position: relative;
    overflow: hidden;
  }

  .pange_textVector {
    font-size: 14px !important;
    font-family: "HarmonyOS Sans, HarmonyOS Sans";
    font-weight: bold;
    font-size: 18px;
    color: #ffffff;
    margin-left: 30px;
  }
}

/deep/.el-input__inner:focus {
  border: 1px solid #1fb1ef;
}

/deep/.el-input__inner {
  border: 1px solid rgba(10, 25, 38, 0.5);
  background: rgba(10, 25, 38, 0.5);
  border-radius: 18px;
  height: 30px;
  color: white;
  line-height: 30px;
  // background: #ffffff3b;
}

/deep/.el-input__icon {
  line-height: 30px;
  border-radius: 0 18px 18px 0;
  cursor: pointer;
}

/deep/.el-input__suffix {
  background: #1fb1ef;
  right: 1px;
  padding: 0 5px;
  border-radius: 0 18px 18px 0;
  opacity: 0.8;
  color: #fff;
}

/deep/ .el-autocomplete-suggestion {
  margin-top: 8px;
  border-radius: 6px;
  border: 1px solid #198ec0;
  background: rgba(10, 25, 38, 0.9);
  color: rgba(25, 142, 192, 1);

  .popper__arrow {
    top: -8px;
    border-bottom-color: rgba(31, 177, 239, 1);
  }

  .popper__arrow::after {
    border-bottom-color: rgba(0, 80, 111, 0.9);
  }

  .el-autocomplete-suggestion__wrap {
    padding: 2px;
  }
}

/deep/ .el-autocomplete-suggestion li {
  color: #ffffff;
}

/deep/ .el-autocomplete-suggestion li:hover {
  background-color: rgba(8, 162, 223, 0.8);
  border-radius: 6px;
}

/deep/ .el-table tr {
  background: rgba(10, 25, 38, 0.5) !important;
}

/deep/ .el-table td.el-table__cell,
.el-table th.el-table__cell.is-leaf {
  background: rgba(10, 25, 38, 0.5) !important;

  border-bottom: 0px solid #ebeef5;
}

.el-table {
  color: #fff;
  background: rgba(10, 25, 38, 0.5) !important;
}

/deep/ .el-table__fixed-right::before,
.el-table__fixed::before {
  background: rgba(10, 25, 38, 0.9) !important;
}

/deep/ .el-table__fixed-right-patch {
  background: rgba(10, 25, 38, 0.9) !important;
}

/deep/ .el-table--border::after,
.el-table--group::after,
.el-table::before {
  background: rgba(10, 25, 38, 0) !important;
}

/deep/ .el-table .warning-row {
  background: rgb(102, 177, 255) !important;
}
</style>
  
