<template>
  <div class="box">
    <div class="box-name">物资</div>
    <div class="close-button" @click="close">
      <i class="el-icon el-icon-close"></i>
    </div>
    <div class="box-title flex column">
      <div class="flex-1 flex ai-c">
        <el-input
          type="text"
          size="mini"
          style="width: 300px; margin-right: 12px; margin-left: 60px"
          v-model="listQuery.wuzi"
        ></el-input>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="getWuziList"
          >查询</el-button
        >
      </div>
      <div class="flex flex-1 ai-c">
        <span style="width: 80px; text-align: right; color: #fff">距离：</span>
        <div class="flex ai-c">
          <el-radio-group v-model="distanceradio" @input="radioChange">
            <el-radio :label="1" class="mr-1">1km内</el-radio>
            <el-radio :label="2" class="mr-1">5km内</el-radio>
            <el-radio :label="3" class="mr-1">10km内</el-radio>
            <el-radio :label="4" class="mr-1">20km内</el-radio>
            <el-radio :label="5">全部</el-radio>
          </el-radio-group>
        </div>
      </div>
    </div>
    <div class="box-container">
      <div class="table-body">
        <div class="item" v-for="(item, index) in goodsListData" :key="index">
          <div class="flex column">
            <div class="flex jc-sb">
              <div>
                <span style="color: #35cf8c" class="fz-16 mr-2">{{
                  item.street
                }}</span>
                <span class="fz-14 mr-2" style="font-weight: bold">{{
                  item.name
                }}</span>
                <span class="mr-2">{{ item.distance }}km</span>
                <span style="color: #cee800"
                  >预计到达时间：{{ item.time }}分钟</span
                >
              </div>
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-position"
                @click="flyToPosition(item)"
              >
                路线
              </el-button>
            </div>
            <div class="line" style="margin: 10px 0"></div>
            <div>物资明细：{{ item.info }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { parse } from "../lib/handleGeojson";
import * as turf from "@turf/turf";
import { getMethodCommon } from "../../../api/common";
const areaName = localStorage.getItem("areaName");
export default {
  name: "monitorbox",
  props: ["endLngLat", "firePopup", "visible"],
  data() {
    return {
      startLngLat: null,
      list: [],
      listQuery: {
        wuzi: null,
        areaname: areaName,
      },
      goodsListData: null,
      echartsLayer: null,
      pathPointGraphicLayer: null,
      goodsGraphicLayer: null,
      goodsGraphicLayerArr: [],
      distanceradio: 1,
      allData: [],
    };
  },
  watch: {
    endLngLat: function (e) {
      this.getWuziList();
    },
    firePopup: {
      handler(newVal, oldVal) {
        if (newVal == true) {
          this.close();
        }
      },
    },
    visible: {
      handler(newVal, oldVal) {
        console.log('newVal: ', newVal);
        if (newVal == false) {
          this.close();
        }
      },
    },
  },
  created() {
    this.getWuziList();
  },
  methods: {
    close() {
      this.goodsGraphicLayerArr.forEach((item) => {
        this.goodsGraphicLayer.removeGraphic(item);
      });
      if (this.pathPointGraphicLayer) {
        this.pathPointGraphicLayer.clear();
      }
      this.$emit("close");
    },
    radioChange(e) {
      let arr = this.nestWuziPoints;
      let newArr = [];
      if (this.distanceradio == 1) {
        arr.forEach((item) => {
          if (item.distance < 1) {
            newArr.push(item);
          }
        });
        this.goodsListData = newArr;
      }
      if (this.distanceradio == 2) {
        arr.forEach((item) => {
          if (item.distance < 5) {
            newArr.push(item);
          }
        });
        this.goodsListData = newArr;
      }
      if (this.distanceradio == 3) {
        arr.forEach((item) => {
          if (item.distance < 10) {
            newArr.push(item);
          }
        });
        this.goodsListData = newArr;
      }
      if (this.distanceradio == 4) {
        arr.forEach((item) => {
          if (item.distance < 20) {
            newArr.push(item);
          }
        });
        this.goodsListData = newArr;
      }
      if (this.distanceradio == 5) {
        this.goodsListData = arr;
      }
      this.goodsListData.sort((a, b) => {
        return a.distance - b.distance;
      });
      this.addGoodsLayer();
    },
    getWuziList() {
      getMethodCommon("/FirePrevention/Loadwuzichubei", this.listQuery).then(
        (res) => {
          if (!res.data.length) {
            this.goodsGraphicLayerArr.forEach((item) => {
              this.goodsGraphicLayer.removeGraphic(item);
            });
            if (this.pathPointGraphicLayer) {
              this.pathPointGraphicLayer.clear();
            }
          } else {
            this.goodsListData = res.data;
            this.getNestPoint(this.endLngLat[0], this.endLngLat[1]).then(
              (wz) => {
                this.nestWuziPoints = wz;
                this.radioChange();
              }
            );
          }
        }
      );
    },
    //火情附近所有点
    async getNestPoint(lng, lat) {
      let from = turf.point([lng, lat]);
      let nestWuziPoints = [];
      await this.goodsListData.forEach((item, index) => {
        let geom = parse(item.geom);
        let to = turf.point(geom.coordinates);
        let options = { units: "kilometers" };
        let distance = turf.distance(from, to, options);
        let obj = {
          lngLat: geom.coordinates,
          distance: distance.toFixed(2),
          time: this.getAroundTime(distance.toFixed(2) * 60 + 5 * 60),
          info: item.info,
          name: item.name,
        };
        nestWuziPoints.push(obj);
      });
      nestWuziPoints.sort((a, b) => {
        return a.distance - b.distance;
      });
      return nestWuziPoints;
    },
    //估算时间   平均60km/h
    getAroundTime(a) {
      var h = parseInt(a / 3600);
      var m = parseInt((a % 3600) / 60);
      var s = parseInt((a % 3600) % 60);
      if (h > 0) {
        return h + "小时" + m + "分" + s + "秒";
      } else {
        return m + "分" + s + "秒";
      }
    },
    flyToPosition(item) {
      this.startLngLat = item.lngLat;
      this.getRoutePath();
      window.globalmap.flyToPoint(item.lngLat, { radius: 1200, pitch: -90 });
    },
    getRoutePath() {
      // 获取路线数据
      let startCoor = this.startLngLat;
      let endCoor = this.endLngLat;
      let params = {
        startlng: parseFloat(startCoor[0]),
        startlat: parseFloat(startCoor[1]),
        endlng: parseFloat(endCoor[0]),
        endlat: parseFloat(endCoor[1]),
        areaname: localStorage.getItem("areaName"),
      };
      getMethodCommon("/FirePrevention/LoadRoad", params).then((res) => {
        console.log("res: ", res);
        if (res.data.length > 0) {
          let LineString = res.data[0].route;
          if (LineString == null || LineString == "null") {
            this.$message({
              type: "warning",
              message: "没有找到合适的路线",
            });
            if (this.pathPointGraphicLayer) {
              this.pathPointGraphicLayer.clear();
            }
          } else {
            this.drawRoutePath(parse(LineString));
          }
        } else {
        }
      });
    },
    drawRoutePath(geojson) {
      // 绘制路线
      if (this.pathPointGraphicLayer == null) {
        this.pathPointGraphicLayer = new mars3d.layer.GraphicLayer();
        window.globalmap.addLayer(this.pathPointGraphicLayer);
      } else {
        this.pathPointGraphicLayer.clear();
      }

      if (geojson.type == "LineString") {
        geojson.coordinates = [geojson.coordinates];
      }

      // 虚线部分
      var startCoor = this.startLngLat;
      var endCoor = this.endLngLat;
      // 起始点坐标
      var startCoorArr = [parseFloat(startCoor[0]), parseFloat(startCoor[1])];
      // 终点坐标
      var endCoorArr = [parseFloat(endCoor[0]), parseFloat(endCoor[1])];

      var startTurfPoint = turf.point(startCoorArr);
      var endTurfPoint = turf.point(endCoorArr);

      // 起始路线部分
      var startPath = [];
      geojson.coordinates[0].forEach((item, index) => {
        startPath.push(turf.point([item[0], item[1]]));
      });

      var startTurfPath = turf.featureCollection(startPath);
      var startNearestPoint = turf.nearestPoint(startTurfPoint, startTurfPath);

      var startNearestPointLngLat = null;
      if (startNearestPoint) {
        startNearestPointLngLat = startNearestPoint.geometry.coordinates;
        var graphic = new mars3d.graphic.PolylineEntity({
          positions: [startCoorArr, startNearestPointLngLat],
          style: {
            width: 5,
            clampToGround: true,
            materialType: mars3d.MaterialType.PolylineDash,
            materialOptions: {
              color: Cesium.Color.YELLOW,
              dashLength: 8.0,
            },
          },
        });
        this.pathPointGraphicLayer.addGraphic(graphic);
      }

      // 终点路线部分
      var endPath = [];
      geojson.coordinates[geojson.coordinates.length - 1].forEach(
        (item, index) => {
          endPath.push(turf.point([item[0], item[1]]));
        }
      );
      var endTurfPath = turf.featureCollection(endPath);
      var endNearestPoint = turf.nearestPoint(endTurfPoint, endTurfPath);

      var endNearestPointLngLat = null;
      if (endNearestPoint) {
        endNearestPointLngLat = endNearestPoint.geometry.coordinates;
        var graphic = new mars3d.graphic.PolylineEntity({
          positions: [endCoorArr, endNearestPointLngLat],
          style: {
            width: 5,
            clampToGround: true,
            materialType: mars3d.MaterialType.PolylineDash,
            materialOptions: {
              color: Cesium.Color.YELLOW,
              dashLength: 8.0,
            },
          },
        });
        this.pathPointGraphicLayer.addGraphic(graphic);
      }

      // 漫游数据
      var tripArr = [];
      // 实线路线部分
      geojson.coordinates.forEach((item, index) => {
        tripArr = tripArr.concat(item);
      });

      var graphic = new mars3d.graphic.PolylineEntity({
        positions: tripArr,
        style: {
          width: 5,
          clampToGround: true,
          materialType: mars3d.MaterialType.LineFlow,
          materialOptions: {
            color: Cesium.Color.CYAN,
            image: "/img/line-colour.png",
            speed: 10,
          },
        },
      });
      this.pathPointGraphicLayer.addGraphic(graphic);

      this.pathPointGraphicLayer.flyTo();

      this.tripFlyArray = [];
      tripArr.forEach((item, index) => {
        if (index % 20 == 0) {
          this.tripFlyArray.push(item);
        }
      });
    },
    addGoodsLayer() {
      if (this.goodsGraphicLayer == null) {
        this.goodsGraphicLayer = new mars3d.layer.GraphicLayer();
        window.globalmap.addLayer(this.goodsGraphicLayer);
      }

      this.goodsGraphicLayerArr.forEach((graphic) => {
        this.goodsGraphicLayer.removeGraphic(graphic);
      });
      this.goodsGraphicLayerArr = [];
      this.goodsListData.forEach((item, index) => {
        let graphic = new mars3d.graphic.BillboardEntity({
          position: [item.lngLat[0], item.lngLat[1]],
          style: {
            image: "img/wuzichubei.png",
            scale:0.7,
            horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
              0,
              200000
            ), // 按视距距离显示
            scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 200000, 0.2),
            clampToGround: true,
          },
          pointerEvents: false,
        });
        this.goodsGraphicLayerArr.push(graphic);
        this.goodsGraphicLayer.addGraphic(graphic);
      });
      window.globalmap.addLayer(this.goodsGraphicLayer);
    },
  },
};
</script>

<style scoped>
.box {
  width: 100%;
  height: calc(100% - 20px);
  overflow: hidden;
  text-align: left;
  z-index: 99;
}
.box-name {
  height: 47px;
  line-height: 47px;
  color: #fff;
  font-size: 20px;
  font-weight: bold;
  padding: 0 40px;
}
.box-title {
  width: 100%;
  height: 80px;
  color: #00fff0;
  margin-top: 10px;
}
.box-container {
  width: calc(100% - 0px);
  padding: 0px 12px;
  height: calc(100% - 120px);
}
.table-header {
  width: calc(100% - 10px);
  height: 25px;
  color: #fff;
  text-align: center;
}
.table-header div {
  float: left;
  width: 25%;
  border-bottom: 1px dashed #00fff0;
  padding-bottom: 8px;
}
.table-body {
  width: 100%;
  height: calc(100% - 0px);
  overflow-y: auto;
}

.table-body .item {
  padding: 15px;
  width: 100%;
  min-height: 80px;
  background: #00ffee2f;
  font-size: 12px;
  text-align: left;
  color: #fff;
  line-height: 24px;
  cursor: pointer;
}

.table-body .item:nth-child(2n) {
  background: #00ffee50;
}

/* .table-body .item div{
        float:left;
        width:33%;
        height:36px;
        color:#eee;
        overflow: hidden;
    } */

::-webkit-scrollbar-track,
::-webkit-scrollbar-thumb {
  border: 0;
}
.close-button {
  position: absolute;
  right: 20px;
  top: 14px;
  cursor: pointer;
  color: #fff;
  font-weight: bold;
  width: 20px;
  height: 20px;
  background: #0abfb5cc;
  line-height: 20px;
  text-align: center;
}

.line {
  width: 406px;
  height: 1px;
  border: 1px solid;
  border-image: linear-gradient(
      90deg,
      rgba(0, 212, 134, 1),
      rgba(86, 254, 254, 0)
    )
    1 1;
}
::-webkit-scrollbar {
  height: 10px;
  width: 10px;
  background: transparent;
  border-radius: 5px;
}

::-webkit-scrollbar-thumb {
  padding-top: 100px;
  -webkit-box-shadow: inset 1px 1px 0 rgba(0, 0, 0, 0.1),
    inset -1px -1px 0 rgba(0, 0, 0, 0.07);
  background-color: #797979;
  min-height: 28px;
  border-radius: 4px;
  background-clip: padding-box;
}

::-webkit-scrollbar-track,
::-webkit-scrollbar-thumb {
  border: 0;
}

::-webkit-scrollbar-thumb:hover {
  -webkit-box-shadow: inset 1px 1px 1px rgba(0, 0, 0, 0.25);
  background-color: rgba(0, 0, 0, 0.4);
}

::-webkit-scrollbar-thumb:active {
  -webkit-box-shadow: inset 1px 1px 3px rgba(0, 0, 0, 0.35);
  background-color: rgba(0, 0, 0, 0.5);
}
.el-radio {
  margin-right: 10px;
  color: #fff;
  margin-bottom: 0;
}
::v-deep .el-input__inner {
  margin-top: 0 !important;
  top: 0 !important;
}

::v-deep .el-input__inner {
  background: none;
  color: #fff;
  margin-top: 4px;
}

::v-deep .el-input__inner {
  background: none;
  color: #fff;
  margin-top: 4px;
}

::v-deep .el-input__inner {
  border-radius: 0px;
  position: relative;
  top: 1px;
}

::v-deep .el-button {
  border-radius: 0px;
}

/* 

*/
</style>
