<template>
  <div>
    <div class="detailList">
      <el-descriptions :column="1" border>
        <el-descriptions-item
          label="图斑编号"
          label-class-name="my-label"
          content-class-name="my-content"
          >{{ hcObj.jcbh || "无" }}</el-descriptions-item
        >
        <el-descriptions-item
          label="外业核实情况"
          content-class-name="my-content"
          :span="3"
          >{{ hcObj.wyhsqk || "无" }}</el-descriptions-item
        >
        <el-descriptions-item label="实际地类代码">{{
          hcObj.sjdldm || "无"
        }}</el-descriptions-item>
        <el-descriptions-item label="调查人员">{{
          hcObj.dcry || "无"
        }}</el-descriptions-item>
        <el-descriptions-item label="调查时间">{{
          hcObj.dcsj || "无"
        }}</el-descriptions-item>
        <el-descriptions-item label="外业预判">
          {{ hcObj.wyyp || "无" }}
        </el-descriptions-item>
        <el-descriptions-item label="核查结果">
          {{ hcObj.hcjg || "无" }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="imgCon">
      <div class="echartTitle">
        <div class="block-title">现场照片</div>
      </div>
      <div class="imgList">
        <div
          class="imgDiv"
          :class="{ hiimg: hiindex === i }"
          v-for="(item, i) in monitorList"
          :key="i"
          @click="clickImg(i)"
          @mouseenter="handleMouseEnter(item, i)"
          @mouseleave="handleMouseLeave(item, i)"
        >
          <span>{{ i + 1 }}</span>
          <!-- <img :src="imgUrl" /> -->
          <img :src="item.imagerPath" />
          <!-- <img :src="imgUrl + item.imagerPath" /> -->
          <p>{{ item.imagerSj }}</p>
        </div>
      </div>
    </div>
    <div class="imgCon">
      <div class="echartTitle">
        <div class="block-title">无人机取证</div>
      </div>
      <div class="imgList">
        <div
          class="imgDiv"
          v-for="(item, i) in xsxList"
          :key="i"
          @click="clickxsx(item)"
        >
          <span>{{ i + 1 }}</span>
          <img :src="item.imagerPath" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getJctbhcInfo, getTiffPath } from "@/api/ghss/jctb.js";
import { loadGeoJSON } from "@/utils/MapHelper/help.js";
export default {
  props: {
    detailObj: {
      type: Object,
    },
    jcbh: {
      type: String,
    },
  },
  components: {},
  data() {
    return {
      imgUrl: "",
      monitorList: [],
      primitive: null,
      selectId: null,
      primitivesArray: [],
      hcObj: {},
      // jtArr:[],//箭头id数组
      // dwArr:[],//
      idArr: [], //id数组
      handler: {},
      hiindex: "",
      hiid: "",
      xsxList: [],
    };
  },
  computed: {},
  mounted() {
    this.$nextTick(() => {
      this.inputAction();
    });
  },
  methods: {
    inputAction() {
      // 为viewer添加鼠标移动的监听事件
      // viewer.screenSpaceEventHandler.setInputAction(function (movement) {
      //   // movement.endPosition是一个Cesium.Cartesian2对象，表示鼠标在屏幕上的位置

      // }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      this.handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      // this.handler.setInputAction(function (movement) {
      //   let pickedFeature = scene.pick(movement.position);
      //   console.log(movement,pickedFeature,'////');
      //   // that[queryName](movement);
      // },  Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      // 鼠标移动事件
      this.handler.setInputAction((event) => {
        if (this.hiid) {
          this.handleMouseLeave({ id: this.hiid });
        }

        let pickObj = viewer.scene.pick(event.endPosition);
        if (Cesium.defined(pickObj)) {
          if (pickObj.id && pickObj.id.id.includes("jt")) {
            this.hiid = pickObj.id.id.replace("jt", "");
            this.handleMouseEnter({ id: this.hiid });
            this.hiindex = this.idArr.indexOf(this.hiid);
            this.clickImg(this.hiindex);
          }
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    },
    handleMouseEnter(a, b) {
      this.ceshi(a.id, "yr");
    },
    handleMouseLeave(a, b) {
      this.ceshi(a.id, "yc");
    },
    changeData(name, updata) {
      this[name] = updata;
    },
    clickImg(val) {
      this.$emit("updateParent", "emitImgList", this.monitorList);
      this.$emit("updateParent", "emitImgIndex", val);
    },
    //getEntities(id, url, position, type) {
    clickxsx(item) {
      let posArr = item.pngenvelope;

      // 创建Cesium的ImageMaterialProperty
      const imageMaterial = new Cesium.ImageMaterialProperty({
        image: item.imagerPath,
        repeat: new Cesium.Cartesian2(1.0, 1.0), // 控制图像重复，这里设置为不重复
        transparent: true, // 如果图像有透明通道，设置为true
      });
      loadGeoJSON(this.detailObj.geom, "#ff0000", { isfly: true }, (data) => {
        data.entities.add({
          name: "Image Overlay",
          id: "wrj",
          rectangle: {
            coordinates: Cesium.Rectangle.fromDegrees(
              posArr[0],
              posArr[1],
              posArr[2],
              posArr[3]
            ), // 设置矩形的经纬度范围
            material: imageMaterial,
          },
        });
        layerSources["wrj"] = data;
      });
    },
    // aaa() {
    //   var redLine = viewer.entities.add({
    //     // 贴在地面上 两点之间的直线距离
    //     name: "line",
    //     polyline: {
    //     positions: Cesium.Cartesian3.fromDegreesArray([
    //       // o.inx,
    //       // o.iny,
    //       // o.outx,
    //       // o.outy,
    //       109.5077, 18.309, 109.5111, 18.3093,
    //     ]),
    //       width: 20,
    //       // 不带箭头的线
    //       // material: Cesium.Color.RED,
    //       // 是否紧贴地面
    //       clampToGround: true,
    //       // 带箭头的线
    //       material: new Cesium.PolylineArrowMaterialProperty(Cesium.Color.RED),
    //     },
    //   });
    // },

    //加载图片
    ddd(obj) {
      // 将经纬度转换为 Cartesian3 坐标,起始点
      //起始点
      var startPosition = Cesium.Cartesian3.fromDegrees(
        Number(obj.imagerLzb),
        Number(obj.imagerBzb)
      );
      let poi = this.getLonAndLat(
        Number(obj.imagerLzb),
        Number(obj.imagerBzb),
        Number(obj.imagerAngle),
        20
      );
      //结束点
      var targetPosition = Cesium.Cartesian3.fromDegrees(poi.lng, poi.lat);
      // 创建一个实体来表示点
      var pointEntity = viewer.entities.add({
        id: "dw" + obj.id,
        position: startPosition, // 点的位置
        point: {
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // 设置为贴地
          pixelSize: 10, // 点的大小
          color: Cesium.Color.RED, // 点的颜色
          outlineColor: Cesium.Color.BLACK, // 点的轮廓颜色
          outlineWidth: 2, // 点的轮廓宽度
        },
      });
      // 创建一个实体来放置箭头
      var arrowEntity = viewer.entities.add({
        id: "jt" + obj.id,
        position: startPosition, // 设置箭头位置
        billboard: {
          // image: "http://192.168.176.1:8001/长箭头.png", // 设置箭头图标
          image: "/static/images/路径@3x-2.png", // 设置箭头图标
          width: 37, // 设置图标宽度
          height: 69, // 设置图标高度
          scale: 0.7, // 设置图标缩放
          rotation: Cesium.Math.toRadians(360 - Number(obj.imagerAngle)), // 可选，默认为0
          // rotation: Number(obj.imagerAngle), // 可选，默认为0
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // 设置贴地
        },
      });

      // // 计算箭头的方向并更新
      // function updateArrowOrientation() {
      //   // 计算起点到目标点的方向向量
      //   var direction = Cesium.Cartesian3.subtract(
      //     targetPosition,
      //     startPosition,
      //     new Cesium.Cartesian3()
      //   );

      //   // 确保方向向量有效
      //   if (Cesium.Cartesian3.magnitude(direction) > 0) {
      //     // 计算箭头朝向目标的方向角（使用 JavaScript 原生 Math.atan2）
      //     var heading = Cesium.Math.toDegrees(
      //       Math.atan2(direction.y, direction.x)
      //     );

      //     // 固定方向，使用 rotation 设置固定旋转
      //     arrowEntity.billboard.rotation = Cesium.Math.toRadians(heading); // 固定旋转角度，不随地图旋转
      //   }
      // }

      // // 每次视图更新时，重新计算箭头方向
      // viewer.scene.preRender.addEventListener(function () {
      //   updateArrowOrientation();
      // });

      // 聚焦视角到箭头位置
      // viewer.zoomTo(arrowEntity);
    },
    ceshi(id, evtName) {
      let aaa = viewer.entities.getById("jt" + id);
      if (evtName == "yr") {
        aaa.billboard.image = "/static/images/路径@3x.png";
      } else {
        aaa.billboard.image = "/static/images/路径@3x-2.png";
      }
    },

    /**
     * 根据一个经纬度及距离角度，算出另外一个经纬度
     * @param {*} lng 经度 113.3960698
     * @param {*} lat 纬度 22.941386
     * @param {*} brng 方位角 45 ---- 正北方：000°或360° 正东方：090° 正南方：180° 正西方：270°
     * @param {*} dist 90000距离(米)
     * 1、角度转换为弧度公式：弧度=角度×(π ÷度180 )
     * 2、弧度转换为角度公式： 角度=弧度×（180÷π）
     */
    getLonAndLat(lng, lat, brng, dist) {
      //大地坐标系资料WGS-84 长半径a=6378137 短半径b=6356752.3142 扁率f=1/298.2572236
      var a = 6378137;
      var b = 6356752.3142;
      var f = 1 / 298.257223563;

      var lon1 = lng * 1;
      var lat1 = lat * 1;
      var s = dist;
      var alpha1 = brng * (Math.PI / 180); //mapNumberUtil.rad(brng);
      var sinAlpha1 = Math.sin(alpha1);
      var cosAlpha1 = Math.cos(alpha1);

      //var tanU1 = (1 - f) * Math.tan(mapNumberUtil.rad(lat1));
      var tanU1 = (1 - f) * Math.tan(lat1 * (Math.PI / 180));
      var cosU1 = 1 / Math.sqrt(1 + tanU1 * tanU1),
        sinU1 = tanU1 * cosU1;
      var sigma1 = Math.atan2(tanU1, cosAlpha1);
      var sinAlpha = cosU1 * sinAlpha1;
      var cosSqAlpha = 1 - sinAlpha * sinAlpha;
      var uSq = (cosSqAlpha * (a * a - b * b)) / (b * b);
      var A =
        1 + (uSq / 16384) * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
      var B = (uSq / 1024) * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));

      var sigma = s / (b * A),
        sigmaP = 2 * Math.PI;
      while (Math.abs(sigma - sigmaP) > 1e-12) {
        var cos2SigmaM = Math.cos(2 * sigma1 + sigma);
        var sinSigma = Math.sin(sigma);
        var cosSigma = Math.cos(sigma);
        var deltaSigma =
          B *
          sinSigma *
          (cos2SigmaM +
            (B / 4) *
              (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) -
                (B / 6) *
                  cos2SigmaM *
                  (-3 + 4 * sinSigma * sinSigma) *
                  (-3 + 4 * cos2SigmaM * cos2SigmaM)));
        sigmaP = sigma;
        sigma = s / (b * A) + deltaSigma;
      }

      var tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1;
      var lat2 = Math.atan2(
        sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1,
        (1 - f) * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp)
      );
      var lambda = Math.atan2(
        sinSigma * sinAlpha1,
        cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1
      );
      var C = (f / 16) * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
      var L =
        lambda -
        (1 - C) *
          f *
          sinAlpha *
          (sigma +
            C *
              sinSigma *
              (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));

      var revAz = Math.atan2(sinAlpha, -tmp); // final bearing

      var lngLatObj = {
        lng: lon1 + L * (180 / Math.PI),
        lat: lat2 * (180 / Math.PI),
      };
      return lngLatObj;
    },

    delatePoi(type) {
      if (this.idArr.length != 0) {
        this.idArr.forEach((item) => {
          viewer.entities.removeById(type + item);
        });
        // this.idArr = [];
      }
    },
  },
  watch: {
    jcbh: {
      handler(newVal, oldVal) {
        getJctbhcInfo(newVal).then((res) => {
          this.idArr = [];
          if (res.code == 200) {
            this.monitorList = res.data.images;
            this.hcObj = res.data;
            this.monitorList.forEach((item, i) => {
              item.name = res.data.dcry;
              item.imagerPath =
                window.axiosURI + "/file/upload/attachment" + item.imagerPath;
              this.ddd(item);
              this.idArr.push(item.id);
            });
          }
        });
      },
      deep: true,
      immediate: true,
    },
    detailObj: {
      handler(newVal, oldVal) {
        if (newVal.xsxtif) {
          this.xsxList = [];
          getTiffPath(this.detailObj.xsxtif).then((res) => {
            if (res.data.pngenvelope) {
              this.xsxList = [
                {
                  imagerPath:
                    window.axiosURI +
                    "/file/upload/attachment" +
                    res.data.pngpath,
                  pngenvelope: res.data.pngenvelope,
                },
              ];
            }
          });
        }
      },
      deep: true,
      immediate: true,
    },
  },
  beforeDestroy() {
    this.delatePoi("jt");
    this.delatePoi("dw");
    this.handler.destroy();
    this.handler = null;
    viewer.dataSources.remove(layerSources["wrj"]);
  },
};
</script>

<style lang="less" scoped>
/deep/ .el-descriptions-item__label.is-bordered-label {
  color: #fff;
  background-color: transparent;
}
/deep/ .el-descriptions__body {
  color: #fff;
  background-color: transparent;
}
.imgCon {
  .imgList {
    width: 100%;
    // height: 300px;
    max-height: 400px;
    display: flex;
    flex-wrap: wrap;
    // background-color: rgba(255, 192, 203, 0.372);
    .imgDiv {
      width: 126px;
      height: 83px;
      margin-right: 10px;
      // background-color: rgba(0, 255, 255, 0.413);
      position: relative;
      margin: 4px 4px;
      img {
        width: 126px;
        height: 83px;
      }
      span {
        width: 26px;
        height: 26px;
        display: inline-block;
        position: absolute;
        top: 0;
        left: 0;
        background: #dbad70;
        text-align: center;
        line-height: 26px;
      }
      p {
        position: absolute;
        bottom: 0;
        font-size: 10px;
        color: #33ccff;
        text-align: center;
        width: 100%;
        height: 30px;
        line-height: 30px;
      }
    }
    .hiimg {
      border: 1px solid red;
    }
  }
}
.detailList {
  margin-top: 10px;
}
/deep/ .el-descriptions .is-bordered .el-descriptions-item__cell {
  padding: 3px;
}
</style>
