<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="getWaterList">查询</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">1~5km</el-radio>
              <el-radio :label="3" class="mr-1">5~10km</el-radio>
              <el-radio :label="4" class="mr-1">大于10km</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">类型：{{item.name}}</span>
                            <span class="mr-2">距离：{{item.distance}}km</span>
                            <span style="color:#CEE800">预计到达时间：{{item.duration}}分钟</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>
let BASE_URL = process.env.VUE_APP_BASE_API
import appConfig from '../../../../public/config/app.json'
import { parse } from '../lib/handleGeojson'
import * as turf from '@turf/turf'
import axios from "axios";
  export default {
    name: 'monitorbox',
    props:['globalmap','endLngLat'],
    data(){
        return{
            startLngLat:null,
            list:[],
            listQuery:{
                wuzi:null,
                areaname:localStorage.getItem("areaName") == 'feixian' ? '费县' : '平邑县'
            },
            goodsListData:null,
            echartsLayer:null,
            pathPointGraphicLayer:null,
            goodsGraphicLayer:null,
            goodsGraphicLayerArr:[],
            distanceradio: 5,
            allData:[]
        }
    },
    watch:{
      endLngLat:function(e){
        this.getWaterList();
      }
    },
    created(){
        this.getWaterList();
    },
    methods:{
        close(){
            this.goodsGraphicLayerArr.forEach(item =>{
                this.goodsGraphicLayer.removeGraphic(item)
            })
            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.goodsListData = newArr
          }
          if(this.distanceradio == 2){
            arr.forEach(item =>{
              if(item.distance >= 1 && item.distance < 5){
                newArr.push(item)
              }
            })
            this.goodsListData = newArr
          }
          if(this.distanceradio == 3){
            arr.forEach(item =>{
              if(item.distance >= 5 && item.distance < 10){
                newArr.push(item)
              }
            })
            this.goodsListData = newArr
          }
          if(this.distanceradio == 4){
            arr.forEach(item =>{
              if(item.distance >= 10){
                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();
        },
        getWaterList(){
            axios({
                method: 'get',
                url: BASE_URL+"/FirePrevention/Loadwuzichubei",
                params:this.listQuery,
                headers:{
                    "X-Token":localStorage.getItem("X-Token"),
                }
            }).then(res => {
                let rel = res.data.data
                // let rel = []
                // res.data.data.forEach((item,index) =>{
                //     if(index < 2){
                //         rel.push(item)
                //     }
                // })
                this.handleData(rel).then(dl =>{
                    dl.sort((a,b)=>{
                        return a.distance - b.distance
                    })
                    setTimeout(() =>{
                        this.allData = dl
                        this.goodsListData = dl
                        setTimeout(()=>{
                            this.radioChange()
                        },1000)
                    },1000)
                    
                    console.log('goodsListData',this.goodsListData)
                })
                // this.goodsListData = res.data.data;
                // this.addGoodsLayer();
            })
        },
        handleData(data){
            console.log('this.endLngLat',this.endLngLat)
          data.forEach(item =>{
            let lngLat = parse(item.geom).coordinates;
            if(lngLat){
                let url = "https://restapi.amap.com/v3/direction/driving?key="+appConfig.gaodeApi+"&origin=" + parseFloat(this.endLngLat[0]) + "," + 
                    parseFloat(this.endLngLat[1]) + "&destination=" + lngLat[0] + "," + lngLat[1] + "&extensions=base"
                axios({
                    method: 'get',
                    url: url,
                }).then(res => {
                    if(res.data.route){
                        let obj = res.data.route.paths[0]
                        item.distance = (obj.distance/1000).toFixed(2)
                        item.duration = Math.round(obj.duration/60)
                    }
                }).catch(err =>{
                    console.log('ee',err)
                })
            }
          })
          return Promise.resolve(data)
        },
        flyToPosition(item){
            console.log('ii',item)
            let lngLat = parse(item.geom).coordinates;
            this.startLngLat = lngLat;
            this.getRoutePath();
            this.globalmap.flyToPoint(lngLat,{radius:400,"pitch":-90});
        },
        getRoutePath(){ // 获取路线数据
                let startCoor =  this.startLngLat;
                let endCoor = this.endLngLat;

                axios({
                    method: 'get',
                    url: 'http://123.132.248.154:9210/api/FirePrevention/LoadRoad',
                    headers:{
                        "X-Token":localStorage.getItem("X-Token"),
                    },
                    params: {
                        startlng: parseFloat(startCoor[0]),
                        startlat: parseFloat(startCoor[1]),
                        endlng: parseFloat(endCoor[0]),
                        endlat: parseFloat(endCoor[1]),
                    }
                }).then(data => {
                    if (data.data.data.length > 0) {
                        let LineString = data.data.data[0].route;
                        if(LineString == null || LineString == "null"){
                            
                        }else{
                            let _this = this;
                            console.log("LineStringing",LineString);
                            setTimeout(function () {
                               _this.drawRoutePath(parse(LineString));
                                // designPath(parse(LineString));
                            }, 1000)
                        }
        
                    }else{
                        
                    }
                })
        },
        drawRoutePath(geojson) { // 绘制路线
            if(this.pathPointGraphicLayer == null){
                this.pathPointGraphicLayer = new mars3d.layer.GraphicLayer();
                this.globalmap.addLayer(this.pathPointGraphicLayer);
            }
            console.log("geojson",geojson);
            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
                    }
                },
                attr: { remark: "虚线" }
                })
                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
                    }
                },
                attr: { remark: "虚线" }
                })
                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
                }
                },
                attr: { remark: "示例13" }
            })
            this.pathPointGraphicLayer.addGraphic(graphic)

            this.pathPointGraphicLayer.flyTo();

            this.tripFlyArray = [];
            tripArr.forEach((item, index) => {
                if (index % 20 == 0) {
                    this.tripFlyArray.push(item);
                }
            })
        
        },
        addGoodsLayer(){
            this.goodsGraphicLayerArr.forEach(item =>{
                this.goodsGraphicLayer.removeGraphic(item)
            })
            this.goodsGraphicLayerArr = []

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

            
            this.goodsListData.forEach((item,index)=>{
                let graphic = new mars3d.graphic.DivGraphic({
                    position: parse(item.geom).coordinates,
                    style: {
                        html: `<div class="marsTiltPanel marsTiltPanel-theme-blue" style="width:300px;">
                            <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">${item.name}</div>
                                        <div class="label-content">
                                            <div class="data-li">
                                                <div class="data-label">归属信息：</div>
                                                <div class="data-value"><span class="label-num">${item.street}
                                                </div>
                                            </div>
                                            <div class="data-li">
                                                <div class="data-label">物资信息：</div>
                                                <div class="data-value"><span class="label-num">
                                                ${item.info}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="b-t-l"></div>
                                <div class="b-b-r"></div>
                            </div>
                            <div class="arrow" ></div>
                        </div>`,
                        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
                    },
                    attr: { remark: "示例11" },
                    pointerEvents: true
                })

                this.goodsGraphicLayer.addGraphic(graphic);
                this.goodsGraphicLayerArr.push(graphic);

            })
        }
    }
  }
</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, .1), inset -1px -1px 0 rgba(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, .25);
  background-color: rgba(0, 0, 0, .4)
}

::-webkit-scrollbar-thumb:active {
  -webkit-box-shadow: inset 1px 1px 3px rgba(0, 0, 0, .35);
  background-color: rgba(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>
