<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-container"> -->
    <div style="height:calc(100% - 10px)">  
      <div class="flex" style="margin: 10px 0">
        <span style="width: 80px; text-align: right; color: #fff">半径：</span>
        <div>
          <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 class="table-body">
        <div class="item" v-for="(item, index) in nestWaterPoints" :key="index">
          <div>{{ "水源地" + (index + 1) }}</div>
          <div>路程 {{ item.distance }} km</div>
          <div>{{ "预计" + item.time }}</div>
          <div class="float:right;text-align:right;">
            <i
              class="el-icon el-icon-position"
              @click="flyToPosition([item.lngLat[0], item.lngLat[1]],'one')"
            ></i>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import appConfig from "../../../../public/config/app.json";
import * as turf from "@turf/turf";
import axios from "axios";
import { getRouterFunc, drawRouterFunc, drawOneRouterFunc,drawRoutersFunc,clearRouterFunc,drawRoutersFuncGrid,drawRoutersFuncWaterGrid } from '../lib/routePath'

let BASE_URL = process.env.VUE_APP_BASE_API;
export default {
  name: "monitorbox",
  props: ["waterCenter", "firePopup","visible","gridMap"],
  data() {
    return {
      startLngLat: null,
      list: [],
      waterPoints: null,
      nestWaterPoints: [],
      echartsLayer: null,
      waterGraphicLayer: null,
      waterGraphicLayerArr: [],
      pathPointGraphicLayer: null,
      allData: [],
      distanceradio:1,
      gridIsShow: true,
    };
  },
  watch: {
    visible: {
      handler(newVal, oldVal) {
        if (newVal == false) {
          this.close();
        }
      },
    },
 
    waterCenter: {
      handler(newVal, oldVal) {
        this.getWaterList();
      },
      immediate: true,
      // 开启深度监听 deep
      deep: true,
    },
    firePopup: {
      handler(newVal, oldVal) {
        if (newVal == true) {
          this.close();
        }
      },
    },
  },
  created() {
    this.getWaterList();
    // window.flyToPosition = this.flyToPosition
  },
  methods: {
    close() {
      if(this.echartsLayer){
        this.echartsLayer.remove(true);
      }

      this.waterGraphicLayerArr.forEach((item) => {
        this.waterGraphicLayer.removeGraphic(item);
      });
      clearRouterFunc()
      this.$emit("close");
    },
    radioChange(e) {
      let arr = this.allData;
      let newArr = [];
      if (this.distanceradio == 1) {
        arr.forEach((item) => {
          if (item.distance < 1) {
            newArr.push(item);
          }
        });
        this.nestWaterPoints = newArr;
      }
      if (this.distanceradio == 2) {
        arr.forEach((item) => {
          if (item.distance < 5) {
            newArr.push(item);
          }
        });
        this.nestWaterPoints = newArr;
      }
      if (this.distanceradio == 3) {
        arr.forEach((item) => {
          if (item.distance < 10) {
            newArr.push(item);
          }
        });
        this.nestWaterPoints = newArr;
      }
      if (this.distanceradio == 4) {
        arr.forEach((item) => {
          if (item.distance <= 20) {
            newArr.push(item);
          }
        });
        this.nestWaterPoints = newArr;
      }
      if (this.distanceradio == 5) {
        this.nestWaterPoints = arr;
      }
      this.nestWaterPoints.sort((a, b) => {
        return a.distance - b.distance;
      });

      

      if (this.waterGraphicLayer == null) {
        this.waterGraphicLayer = new mars3d.layer.GraphicLayer();
        window.globalmap.addLayer(this.waterGraphicLayer);
      }

      this.waterGraphicLayerArr.forEach((graphic) => {
        this.waterGraphicLayer.removeGraphic(graphic);
      });
      this.waterGraphicLayerArr = [];
      this.nestWaterPoints.forEach((item, index) => {
        let graphic = new mars3d.graphic.BillboardEntity({
          position: [item.lngLat[0], item.lngLat[1]],
          style: {
            image: "img/water.png",
            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,
            label: {
                text:"水源地"+(index+1)+"("+item.distance+")km",
                font_size: 12,
                color: "#ffffff",
                pixelOffsetY: -78,
                pixelOffsetX:20,
                distanceDisplayCondition: true,
                distanceDisplayCondition_far: 6000,
                distanceDisplayCondition_near: 0,
            },
          },
          popup: `<div class="marsTiltPanel marsTiltPanel-theme-green">
                  <div class="marsTiltPanel-wrap">
                      <div class="area">
                          <div class="arrow-lt"></div>
                          <div class="b-t"></div>
                          <div class="b-r"></div>
                          <div class="b-b"></div>
                          <div class="b-l"></div>
                          <div class="arrow-rb"></div>
                          <div class="label-wrap">
                              <div class="title">水源地${index+1}</div>
                              <div class="label-content">
                                  <div class="data-li">
                                      <div class="data-label" >距离：</div>
                                      <div class="data-value">${item.distance}km</div>
                                  </div>
                                  <div class="data-li">
                                      <div class="data-label" >预计用时：</div>
                                      <div class="data-value">${item.time}</div>
                                  </div>
                              </div>
                          </div>
                      </div>
                      <div class="b-t-l"></div>
                      <div class="b-b-r"></div>
                  </div>
                  <div class="arrow" ></div>
              </div>`,
          popupOptions: {
              offsetY: -60,
              offsetX:20,
              template: "{content}",
              horizontalOrigin: "Cesium.HorizontalOrigin.LEFT",
              verticalOrigin: "Cesium.VerticalOrigin.CENTER",
          },
          pointerEvents: true,
        });
        this.waterGraphicLayerArr.push(graphic);
        this.waterGraphicLayer.addGraphic(graphic);
      });

      this.nestWaterPoints.forEach((item,index)=>{
        this.flyToPosition([item.lngLat[0], item.lngLat[1]],'all')
      })
      window.globalmap.addLayer(this.waterGraphicLayer);
    },
    getWaterList() {
      axios({
        method: "get",
        params: {
          lng: this.waterCenter[0],
          lat: this.waterCenter[1],
        },
        url: BASE_URL + "/FireGrideResource/GetGridInfoByLngLat",
      }).then((res) => {
        let rel = res.data.result
        if(rel == null){
          axios({
            method: "get",
            url: appConfig[localStorage.getItem("areaName")].waterUrl,
          }).then((res) => {
            this.waterPoints = res.data;
            this.gridIsShow = true
            this.getNestPoint(this.waterCenter[0], this.waterCenter[1]);
            this.radioChange();
          });
        }else{
          axios({
            method: "get",
            params: {
              id: rel.Id
            },
            url: BASE_URL + "/FireGrideResource/GetWaterResource",
          }).then((res) => {
            this.gridIsShow = false
            this.waterPoints = res.data.result;
            let separators = ["(", " ", ")"]
            this.waterPoints.forEach(item =>{
              let coord = item.geom.split( (new RegExp("[" + separators.join('') + "]")) )
              item.coordinates = [ coord[1] , coord[2] ]
            })
            this.getNestPointGrid(this.waterCenter[0], this.waterCenter[1]);
            this.radioChange();
            this.getGridRoute(rel.Id);
            
          });
        }
      });
    },
    getGridRoute(Id){
      clearRouterFunc()
      axios({
        method: "get",
        params: {
          id: Id
        },
        url: BASE_URL + "/FireGrideResource/GetWgRoad",
      }).then((res) => {
        let rel = res.data.result
        let separators = ["((", ",", "))"]
        rel.forEach(item =>{
          item.pointArr = []
          let coord = item.geom.split( (new RegExp("[" + separators.join('') + "]")) )
          coord.forEach((val,index) =>{
            if(index > 1 && index < (coord.length - 2) ){
              item.pointArr.push([
                val.split(' ')[0],val.split(' ')[1]
              ])
            }
          })
        })
        rel.forEach((item,index) =>{
          if(index !== 35){
            drawRoutersFuncGrid(item)
          }
          
        })
        
      });
      axios({
        method: "get",
        params: {
          id: Id
        },
        url: BASE_URL + "/FireGrideResource/GetWgWaterNetwork",
      }).then((res) => {
        let rel = res.data.result
        
        let separators = ["((", ",", "))"]
        rel.forEach(item =>{
          item.pointArr = []
          let coord = item.geom.split( (new RegExp("[" + separators.join('') + "]")) )
          coord.forEach((val,index) =>{
            if(index > 1 && index < (coord.length - 2) ){
              item.pointArr.push([
                val.split(' ')[0],val.split(' ')[1]
              ])
            }
          })
        })
       
        rel.forEach(item =>{
          drawRoutersFuncWaterGrid(item)
        })
        
      });
    },
    //估算时间   平均60km/h
    getAroundTime(a) {
      var h = parseInt(a / 3600);
      var m = parseInt((a % 3600) / 60);
      var s = parseInt((a % 3600) % 60);
      return h + "小时" + m + "分" + s + "秒";
    },
    getNestPointGrid(lng, lat) {
      let from = turf.point([lng, lat]);
      this.nestWaterPoints = [];
      this.waterPoints.forEach((item, index) => {
        let to = turf.point(item.coordinates);
        let options = { units: "kilometers" };
        let distance = turf.distance(from, to, options);
        let obj = {
          lngLat: item.coordinates,
          distance: distance.toFixed(2),
          time: this.getAroundTime(distance.toFixed(2) * 60 + 5 * 60),
        };
        this.nestWaterPoints.push(obj);
      });
      this.nestWaterPoints.sort((a, b) => {
        return a.distance - b.distance;
      });
      this.allData = this.nestWaterPoints;

       
    },
    //火情附近所有点
    getNestPoint(lng, lat) {
      let from = turf.point([lng, lat]);
      this.nestWaterPoints = [];
      this.waterPoints.features.forEach((item, index) => {
        let to = turf.point(item.geometry.coordinates);
        let options = { units: "kilometers" };
        let distance = turf.distance(from, to, options);
        let obj = {
          lngLat: item.geometry.coordinates,
          distance: distance.toFixed(2),
          time: this.getAroundTime(distance.toFixed(2) * 60 + 5 * 60),
        };
        this.nestWaterPoints.push(obj);
      });
      this.nestWaterPoints.sort((a, b) => {
        return a.distance - b.distance;
      });
      this.allData = this.nestWaterPoints;

       
    },
    flyToPosition(lngLat,type) {
      // if(type=='all'){
      //   this.startLngLat = lngLat;
      //   if(this.gridIsShow){
      //     this.getRoutePath(type);
      //   }else{

      //   }
      // }else if(type == 'one'){
      //   this.startLngLat = lngLat;
      //   this.getRoutePath(type);
      // }

      window.globalmap.flyToPoint(lngLat, { radius: 4000, pitch: -90 });
    },
    getRoutePath(type) {
      // 获取路线数据
      let startCoor = this.startLngLat;
      let endCoor = this.waterCenter;
      let params = {
        startlng: parseFloat(startCoor[0]),
        startlat: parseFloat(startCoor[1]),
        endlng: parseFloat(endCoor[0]),
        endlat: parseFloat(endCoor[1]),
        areaname: localStorage.getItem("areaName"),
      };
      getRouterFunc(params,).then(res => {
        if(type == 'all'){
          drawRoutersFunc(res)
        }else if( type == 'one'){
          drawOneRouterFunc(res)
        }
      }).catch(err => {
        clearRouterFunc()
      })
    },
    getEchartsOption(lng,lat,nestWaterPoints) {
          const beijinCoord = [lng, lat]
          const symbolPoint = "image://img/symbol1.png"
          const linePoint = "image://img/linePoint1.png"

          const pointArr = []
          const pathArr = [];
          for(let i=0;i<15;i++){
            pointArr.push({
              name: nestWaterPoints[i].distance+"km",
              value: nestWaterPoints[i].lngLat,
              symbol: symbolPoint
            })
            pathArr.push({
              name: i,
              toname: "当前位置",
              coords: [nestWaterPoints[i].lngLat, beijinCoord]
            })
          }

          const option = {
            animation: false,
            clampToGround:true,
            series: [
              {
                name: "",
                type: "lines",
                coordinateSystem: "mars3dMap",
                zlevel: 1,
                data: pathArr,
                // 线上面的动态特效
                effect: {
                  show: true,
                  smooth: false,
                  trailLength: 0,
                  symbol: linePoint,
                  symbolSize: [10, 30],
                  period: 4
                },
                lineStyle: {
                  normal: {
                    width: 3,
                    color: "#1c67d6",
                    curveness: 0.2
                  }
                }
              },
              {
                type: "effectScatter",
                coordinateSystem: "mars3dMap",
                zlevel: 3,
                data: [
                  {
                    name: "当前位置",
                    value: beijinCoord.concat(200)
                  }
                ],
                rippleEffect: {
                  period: 10,
                  scale: 5,
                  brushType: "fill"
                }
              },
              {
                type: "effectScatter",
                coordinateSystem: "mars3dMap",
                symbolSize: [20, 20],
                symbolOffset: [0, -10],
                zlevel: 3,
                circular: {
                  rotateLabel: true
                },
                label: {
                  normal: {
                    show: true,
                    position: "bottom",
                    formatter: "{b}",
                    fontSize: 14,
                    color: "#fff",
                    textBorderColor: "#2aa4e8",
                    offset: [0, 10]
                  }
                },
                itemStyle: {
                  normal: {
                    shadowColor: "none"
                  }
                },
                data: pointArr
              }
            ]
          }
          return option
        },
  },
};
</script>
<style scoped>
.box {
  width: 100%;
  height:100%;
  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: 40px;
  line-height: 50px;
  text-indent: 20px;
  color: #00fff0;
}
.box-container {
  width: calc(100% - 0px);
  padding: 10px 12px;
  height: calc(100% - 60px);
}
.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% - 25px);
  overflow-y: auto;
}

.table-body .item {
  width: 100%;
  height: 36px;
  background: #00ffee2f;
  font-size: 12px;
  text-align: center;
  line-height: 36px;
  cursor: pointer;
}

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

.table-body .item div {
  float: left;
  width: 25%;
  color: #eee;
}

::-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;
}

.el-radio {
  margin-right: 10px;
  color: #fff;
  margin-bottom: 0;
}

::-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);
}
</style>
