<template>
  <div class="wrapper lh-map" >
    <div class="wrapper-left wrapper-item">
      <el-input placeholder="请输入内容" clearable class="input-search" v-model="searchValue">
        <el-button
          slot="append"
          class="update-elui-style"
          icon="el-icon-search"
          type="primary"
          @click="searchBuilding"
        ></el-button>
      </el-input>
      <div class="left-box" v-if="showSearchRes">
        <div
          v-for="item in houseList"
          class="left-box-item"
          @click="moveToBuilding(item)"
        >
          <div style="font-size: 16px">{{ item.ower }}</div>
          <div>房屋编号：{{ item.buildingno }}</div>
          <div>身份证号：{{ item.oweridcar }}</div>
          <!-- <div class=""></div> -->
          <i class="el-icon-arrow-right more-icon"></i>
        </div>
      </div>
    </div>
    <div
      class="wrapper-right wrapper-item"
      v-if="Object.keys(modelPropertys).length"
    >
      <div class="right-box">
        <div class="right-title">仙湖开发区26号路工程项目</div>
        <el-tabs
          v-model="activeName"
          type="card"
          @tab-click="handleClick"
          class="right-tabs"
        >
          <el-tab-pane label="人口信息" name="first">人口信息</el-tab-pane>
          <el-tab-pane label="房屋信息" name="house">
            <el-button class="add-house" icon="el-icon-plus" type="primary"
              >添加房屋信息</el-button
            >
            <div class="floor">
              <div class="floor-value">一楼</div>
              <div>所在楼层</div>
              <div class="floor-more-btn">
                更多

                <i class="el-icon-arrow-down"></i>
              </div>
            </div>
            <div class="floor-info">
              <div class="info-top">
                <el-row>
                  <el-col :span="6">
                    <div class="area-box">
                      <div class="area-value">{{ modelPropertys.length }}</div>
                      <div>长（米）</div>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="area-box">
                      <div class="area-value">{{ modelPropertys.width }}</div>
                      <div>宽（米）</div>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="area-box">
                      <div class="area-value">
                        {{ modelPropertys.minheight }}
                      </div>
                      <div>高（米）</div>
                    </div>
                  </el-col>
                  <el-col :span="6">
                    <div class="area-box">
                      <div class="area-value">{{ modelPropertys.barea }}</div>
                      <div>面积（米）</div>
                    </div>
                  </el-col>
                </el-row>
              </div>
              <div class="info-bottom">
                <p>
                  <span>房屋结构</span>
                  <span class="info-bottom-value">{{
                    modelPropertys.struct
                  }}</span>
                </p>
                <p>
                  <span>等级</span>
                  <span class="info-bottom-value">{{
                    modelPropertys.level
                  }}</span>
                </p>
                <p>
                  <span>补偿标准</span>
                  <span class="info-bottom-value">{{
                    modelPropertys.paylevel
                  }}</span>
                </p>
                <p>
                  <span>总楼层</span>
                  <span class="info-bottom-value">{{
                    modelPropertys.level
                  }}</span>
                </p>
                <p>
                  <span>单位</span>
                  <span class="info-bottom-value">{{
                    modelPropertys.level
                  }}</span>
                </p>
                <p>
                  <span>单价</span>
                  <span class="info-bottom-value">{{
                    modelPropertys.level
                  }}</span>
                </p>
                <p>
                  <span>金额</span>
                  <span class="info-bottom-value">{{
                    modelPropertys.price
                  }}</span>
                </p>
                <p>
                  <span>备注</span>
                  <span class="info-bottom-value">{{
                    modelPropertys.remark
                  }}</span>
                </p>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="附属物信息" name="second"> </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div id="cesiumContainer" ref="cesiumContainer">
      <!-- <c-pointer></c-pointer> -->
      <!-- 信息框 -->
      <div class="map_infodialog-box" ref="title_box" :style="titlePosition">
        <!-- <div>户主姓名：</div> -->
        <div>
        {{ modelPropertys.ower }}（{{ modelPropertys.oweridcar }}）
        </div>
        <el-button 
        class="update-elui-style infodialog-btn" 
        @click="onStartChart" 
        size="small">发起聊天</el-button>
      </div>
      <slot v-if="map"></slot>
    </div>
  </div>
</template>

<script>
import * as Cesium from "cesium";
import "cesium/Build/Cesium/Widgets/widgets.css";
window.Cesium = Cesium;
window.CESIUM_BASE_URL = "/";
import { CesiumZh } from "utils/cesium/CesiumZh.js";
import $ from "jquery";
export default {
  name: "LhMap3D",
  props: {
    // 初始化缩放层级
    /* zoom: {
        type: Number,
        default: 10,
      }, */
    // 初始化中心经纬度
    /* center: {
        type: Array,
        default () {
          return [110.2313, 22.6639, 500];
        },
      } */
  },
  data() {
    return {
      showSearchRes:false,
      map: null,
      isMap: true,
      isOlMap: false,
      // 选中的模型 颜色
      silhouetteGreen: null,
      activeName: "house",
      modelPropertys: {
      },
      searchValue:null,
      // 弹框位置
      titlePosition: {},
      houseList: [],
      allBuildingModels: [],
      old3DTile: null,
    };
  },
  provide() {
    return {
      coordType: null,
      bounds: null,
    };
  },

  beforeDestroy() {},
  methods: {
    init() {
      let script = document.createElement("script");
      script.type = "text/javascript";
      script.src = "./static/CesiumRenderPatch.js";
      document.getElementsByTagName("head")[0].appendChild(script);

      // this.$store.commit("setIsOlMap", false);

      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxZmY4NjlmZS1iM2IwLTRlNWUtOWU5Yy0yMDM2MGRlZjZkZGMiLCJpZCI6Mzc2MzEsImlhdCI6MTYwNjY1MzcyMX0.cNGtGAI3APmDMaFsudpOwkBGXZcpoXgf8mgA9Fdq4jE";
      // Cesium.Ion.defaultAccessToken =
      //   "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJiY2RhMDMyYi1mODVkLTRkODAtYmI4MS0zZTY0OTM3OGExZWEiLCJpZCI6MjU5LCJpYXQiOjE2MTQ1OTIwNDZ9.0jO0HJaY0N1DrvfxPuuoDPWN_ebN2o2Ku2DrRC_P8qs";
      this.map = new Cesium.Viewer(this.$refs.cesiumContainer, {
        terrainProvider: Cesium.createWorldTerrain(),
        proxy: new Cesium.DefaultProxy("/proxy/"), //cesium的跨域
        // ...this.viewerOptions,
        CreditsDisplay: false, //展示数据版权属性
        animation: false, //左下角仪表
        fullscreenButton: false, //全屏按钮
        timeline: false,
        baseLayerPicker: true,
        infoBox: true,
        //  imageryProvider: imgMap,
        animation: false, //左下角仪表
        fullscreenButton: false, //全屏按钮
        geocoder: false, //右上角查询搜索
        sceneMode: 3, //初始场景模式 1 2D模式 2 2D循环模式 3 3D模式  Cesium.SceneMode
        homeButton: false, //home按钮
        sceneModePicker: false, //3d 2d选择器
        selectionIndicator: false, //
        timeline: false, //时间轴
        navigationHelpButton: false, //右上角帮助按钮
      });
    },
    /**显示搜索框 */
    searchBuilding(){
      this.showSearchRes=true;
    },
    addBuildingLayers() {
      var buildingTilesetModel = new Cesium.Cesium3DTileset({
        url: "cesium/building/tileset.json",
      });
      buildingTilesetModel.style = new Cesium.Cesium3DTileStyle({
        color: "color('rgba(255,255,255,0.05)')",
      });
      let buildingTileset = this.map.scene.primitives.add(buildingTilesetModel);
      buildingTileset.readyPromise
        .then((currentModel) => {
          console.log(currentModel, "建筑物模型加载成功");
            var height=20;
           var cartographic = Cesium.Cartographic.fromCartesian(buildingTileset.boundingSphere.center);
           var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, cartographic.height);
           var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, cartographic.height + height);
           var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
           buildingTileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
        })
        .otherwise((error) => {
          console.log(error, "建筑物模型加载错误");
        });
      //监听建筑物的显示得到 模型列表
      buildingTileset.tileVisible.addEventListener((tile) => {
        var features = tile.content._features;
        if (!this.allBuildingModels.length) {
          this.allBuildingModels = features;
          var propertyNames = features[0].getPropertyNames();
          var arr = [];
          if (propertyNames.length > 5) {
            // for (let j = 0; j < features.length; j++) {
            for (let j = 0; j < 10; j++) {
              let item = {};
              for (var i = 0; i < propertyNames.length; ++i) {
                var propertyName = propertyNames[i];
                let value = features[j].getProperty(propertyName);
                item[propertyName] = value;
              }
              arr.push(item);
            }
          }

          this.houseList = arr;
        }
        // console.log(JSON.stringify(this.houseList));
      });
      // 添加信息框
      this.map.container.appendChild(this.$refs.title_box);
    },
    /**设置剪影 */
    addSilhousete() {
      if (
        Cesium.PostProcessStageLibrary.isSilhouetteSupported(this.map.scene)
      ) {
        this.silhouetteGreen = Cesium.PostProcessStageLibrary.createEdgeDetectionStage();
        this.silhouetteGreen.uniforms.color = Cesium.Color.LIME;
        this.silhouetteGreen.uniforms.length = 0.01;
        this.silhouetteGreen.selected = [];

        this.map.scene.postProcessStages.add(
          Cesium.PostProcessStageLibrary.createSilhouetteStage([
            this.silhouetteGreen,
          ])
        );
        console.log(this.silhouetteGreen);
      }
    },
    /**
     * 加载倾斜摄影模型
     */
    addTilesetLayers() {
      console.log("开始加载模型......");
      var tilesetModel = new Cesium.Cesium3DTileset({
        // url: "cesium/csbuilding/tileset.json",
        url: "cesium/3DTiles/tileset.json",
        //maximumScreenSpaceError: 2, //最大的屏幕空间误差
        //maximumNumberOfLoadedTiles: 1000,//最大加载瓦片个数
      });
      // 由于生成3dtiles文件时使用的底图和地形和cesium加载的可能不同，再加上人工调整模型位置具有一定的偏差，所以3dtiles模型加载到数字地球上之后，可能需要再次调整位置，所以最好有前端调整工具去进行模型位置的调整
      let tileset = this.map.scene.primitives.add(tilesetModel);
      tileset.readyPromise
        .then((currentModel) => {
          console.log(currentModel, "加载模型成功");
          var boundingSphere = tileset.boundingSphere;
          // 设置相机，使当前视图包含提供的边界球。
          // this.map.camera.viewBoundingSphere(
          //   boundingSphere,
          //   new Cesium.HeadingPitchRange(0.5, -0.2, boundingSphere.radius * 1.5) //定义航向角，俯仰角和范围
          // );
                var height=20;
           var cartographic = Cesium.Cartographic.fromCartesian(tileset.boundingSphere.center);
           var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, cartographic.height);
           var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, cartographic.height + height);
           var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
           tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
          this.map.zoomTo(currentModel);
          return;
        })
        .otherwise((error) => {
          console.log(error, "模型加载错误");
        });
    },
    addModelClick() {
      this.map.screenSpaceEventHandler.setInputAction((movement) => {
        var pickedFeature = this.map.scene.pick(movement.position);
        // console.log(pickedFeature);
        if (typeof pickedFeature != "undefined") {
          //获取模型的所有数据

          //模型上的所有数据
          var propertyNames = pickedFeature.getPropertyNames();
          if (propertyNames.length > 5) {
            if (this.old3DTile) {
              this.old3DTile.color = new Cesium.Color(255, 255, 255, 0.01);
            }
            for (var i = 0; i < propertyNames.length; ++i) {
              var propertyName = propertyNames[i];
              let value = pickedFeature.getProperty(propertyName);
              this.$set(this.modelPropertys, propertyName, value);
            }
            //设置高亮背景色
            pickedFeature.color = new Cesium.Color(1, 0, 0, 0.4);
            this.old3DTile = pickedFeature;
            // this.silhouetteGreen.selected = [pickedFeature];
            this.titlePosition = {
              bottom: this.map.canvas.clientHeight - movement.position.y + "px",
              left: movement.position.x + "px",
            };
          }
          // this.map.selectedEntity = selectedEntity;
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },
    /**
     * 调整模型参数
     */
    update3dtilesMaxtrix(params) {
      var mx = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(params.rx));
      var my = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(params.ry));
      var mz = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(params.rz));
      var rotationX = Cesium.Matrix4.fromRotationTranslation(mx);
      var rotationY = Cesium.Matrix4.fromRotationTranslation(my);
      var rotationZ = Cesium.Matrix4.fromRotationTranslation(mz);
      //平移 修改经纬度
      var position = Cesium.Cartesian3.fromDegrees(
        params.longitude,
        params.latitude,
        params.height
      );
      var m = Cesium.Transforms.eastNorthUpToFixedFrame(position);
      //旋转、平移矩阵相乘
      Cesium.Matrix4.multiply(m, rotationX, m);
      Cesium.Matrix4.multiply(m, rotationY, m);
      Cesium.Matrix4.multiply(m, rotationZ, m);
      //缩放 修改缩放比例
      var scale = Cesium.Matrix4.fromUniformScale(params.scale);
      Cesium.Matrix4.multiply(m, scale, m);
      //赋值给tileset
      window.tileModel._root.transform = m;
      //调整地下透明度
      viewer.scene.globe.translucency.frontFaceAlphaByDistance.nearValue = Cesium.Math.clamp(
        params.alpha,
        0.0,
        1.0
      );
    },
    /**
     * tabs栏切换
     */
    handleClick() {},
    /**
     * 点击左边栏定位相机飞行
     */
    moveToBuilding(house) {
      this.allBuildingModels.forEach((feature) => {
        if (feature.getProperty("buildingno") == house.buildingno) {
          if (this.old3DTile) {
            this.old3DTile.color = new Cesium.Color(255, 255, 255, 0.01);
          }
          // feature.color = new Cesium.Color(1, 0, 0, 1);
          feature.color = new Cesium.Color(1, 0, 0, 1);
          this.old3DTile = feature;
          var boundingSphere = feature.content.tile.boundingSphere;
          // console.log(boundingSphere);
          //           // 设置相机，使当前视图包含提供的边界球。
          // this.map.camera.viewBoundingSphere(
          //   boundingSphere,
          //   new Cesium.HeadingPitchRange(0.5, -0.2, 0.5) //定义航向角，俯仰角和范围
          // );
        }
      });
    },
    addGerserveJosn() {
      $.ajax({
        url:
          "http://116.63.144.253:8080/geoserver/yyserver/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=yyserver%3Abuilding&maxFeatures=50&outputFormat=application%2Fjson",
        cache: false,
        async: true,
        success: (data) => {
          var dataPromise = Cesium.GeoJsonDataSource.load(data);
          console.log(dataPromise,"dataPromise");
          dataPromise.then((dataSource) => {
            this.map.dataSources.add(dataSource); //加载服务数据
            console.log(dataSource, "dataSource");
            this.map.camera.flyTo(dataSource);
          });
        },
        error: function (data) {
          console.log("error");
        },
      });
    },
    onStartChart(){
      this.$emit("on-start-chart",this.modelPropertys)
    }
  },
  mounted() {
    this.init();
    //添加建筑物倾斜摄影
    this.addBuildingLayers();
    //加载geoserve 数据
    // this.addGerserveJosn();
    // //加载倾斜摄影模型
    this.addTilesetLayers();
 
    //监听点击事件
    this.addModelClick();
    //汉化
    CesiumZh.load();
  },
};
</script>

<style lang='scss' scoped>
#cesiumContainer {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
  position: relative;
  background-color: rgba(125, 124, 129, 1);

  /deep/.cesium-viewer-bottom {
    display: none;
  }
}
.wrapper {
  height: 100%;
  width: 100%;
  background-color: #0b0f34;
  position: relative;
  .wrapper-item {
    width: 320px;
    height: calc(100% - 80px);
    position: absolute;
    z-index: 5;
    top: 50%;
    transform: translateY(-50%);
    color: #fff;
  }
  .wrapper-left {
    margin-left: 10px;
    // pointer-events: none;
    .input-search {
      background: rgba(33, 224, 81, 0.2);
      margin-bottom: 20px;
      input {
        background: transparent;
      }
      /deep/.el-input-group__append {
        background-color: #409eff;
        color: #fff;
      }
    }
    .left-box {
      width: 240px;
      height: calc(100% - 100px);
      padding: 10px;
      color: #fff;
      overflow: auto;
      // background: rgba(11, 15, 12, 0.2) url("../../../sources/images/4.png")
      //   no-repeat 100% 100%;
      background-color: rgba(0, 18, 42, 0.8);
      // background-image: url("../../../sources/images/4.png");
      // background-repeat: no-repeat;
      // background-size: 100% 100%;
      .left-box-item {
        border-bottom: 1px solid #524d4d;
        padding: 10px;
        box-sizing: border-box;
        border-left: 2px solid transparent;
        position: relative;
        &:hover {
          // background:linear-gradient(90deg, rgba(191, 136, 34, 0.8) 0%, rgba(6, 0, 87, 0.8) 100%);
          cursor: pointer;
          border-left-color: #eea110;
          background: linear-gradient(
            to right,
            rgba(191, 136, 34, 0.6),
            rgba(191, 136, 34, 0)
          );
        }
        .more-icon {
          border-radius: 50%;
          border: 1px solid rgba(191, 136, 34, 0.6);
          padding: 5px;
          position: absolute;
          right: 0;
          top: calc(50% - 13px);

          color: rgba(191, 136, 34, 0.6);
        }
      }
    }
  }
  .wrapper-right {
    right: 10px;
    background-color: rgba(0, 18, 42, 0.8);
    .right-box {
      color: #fff;
      .right-title {
        background-color: rgba(255, 138, 0, 0.2);
        font-weight: bolder;
        height: 26px;
        line-height: 26px;
        padding: 10px;
        font-size: 20px;
      }
      .right-tabs {
        margin: 10px;
        /deep/ {
          .el-tabs__nav {
            border: none;
          }
          .el-tabs__item {
            color: #fff;
            padding: 0 10px;
            // border: 1px solid red;
            margin-right: 5px;
            background: linear-gradient(to bottom, #5c4222, rgba(0, 0, 0, 0));
            &.is-active {
              background: linear-gradient(to bottom, #f58705, rgba(0, 0, 0, 0));

              border: none;
            }
          }
          .el-tabs--card > .el-tabs__header .el-tabs__nav {
            border: none;
          }
        }
        .add-house {
          width: 100%;
        }
        .floor {
          margin-top: 10px;
          border-radius: 2px;
          background: linear-gradient(to right, #976e3e, rgba(0, 0, 0, 0));
          padding: 5px 10px;
          position: relative;
          .floor-value {
            font-size: 18px;
          }
          .floor-more-btn {
            position: absolute;
            right: 10px;
            top: 10px;
            border: 1px solid #ff8a0066;
            border-radius: 15px;
            padding: 5px 20px;
            color: #ff8a0066;
          }
        }
        .floor-info {
          margin-top: 10px;
          .info-top {
            padding-bottom: 10px;
            border-bottom: 1px solid #524d4d;
            /deep/ {
              .el-col {
                &:last-child {
                  border: none;
                }
                .area-box {
                  border-right: 1px solid #524d4d;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  flex-direction: column;
                  .area-value {
                    font-weight: bolder;
                    font-size: 14px;
                  }
                }
              }
            }
          }
          .info-bottom {
            padding: 10px;
            .info-bottom-value {
              float: right;
            }
          }
        }
      }
    }
  }
}
.map_infodialog-box {
  background-color: rgba(0, 18, 42, 1);
  color: rgba(255, 138, 0, 1);
  position: absolute;
  padding: 10px;
  border-radius: 3px;
  .infodialog-btn{
    float: right;
    margin: 10px;
  }
}
</style>
