<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">
      <div class="flex" style="margin-top:15px;margin-bottom:5px;">
        <span class="titlebox">人员类型：</span>
        <div class="flex-1">
          <el-checkbox-group v-model="checkList" @change="checkChange">
            <el-checkbox :label="2" value="2" style="margin-right:10px;">护林员</el-checkbox>
            <el-checkbox :label="3" value="3" style="margin-right:10px;">消防员</el-checkbox>
            <el-checkbox :label="4" value="4"  style="margin-right:10px;">巡查员</el-checkbox>
            <el-checkbox :label="5" value="5">管理人员</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <div class="flex" style="margin-bottom:10px;">
        <span class="titlebox">距离：</span>
        <div>
          <el-radio-group v-model="distanceradio" @change="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="5">全部</el-radio>
          </el-radio-group>
        </div>
      </div>
      <div class="flex" style="margin:12px 0px;">
        <span class="titlebox">
          <span>自定义：</span>
        </span>
        <div class="flex">
          <el-input type="number" size="mini" style="width:100px;margin-right:10px;margin-left: 10px;" placeholder="最小距离"
            v-model="startdistance"></el-input>
          <el-input type="number" size="mini" style="width:100px;margin-right: 10px;" v-model="enddistance" placeholder="最大距离"></el-input>
        </div>
      </div>

      <div class="flex">
        <span class="titlebox">
          <span>人员姓名：</span>
        </span>
        <div class="flex">
          <div class="flex">
            <el-input placeholder="人员姓名" v-model="searchUserName" size="mini" style="margin-right:20px;"></el-input>
          </div>
    
          <el-button type="primary" size="mini" icon="el-icon-search" @click="getListData">查询</el-button>
        </div>
      </div>




    </div>
    <div class="box-container">
      <div class="table-body">
        <div class="table-li" v-for="(item, index) in listData" :key="index">
          <div class="flex jc-sb max-h">
            <div class="flex-1 max-h flex column jc-sb fc-w max-w cursor" @click="flyToPosition(item)">
              <div class="flex fz-16 ai-c">
                <div class="phonecheckbox" :class="checkPhoneArr.includes(item.phone) ? 'active' : ''"
                  @click.stop="phoneCheckClick(item)"></div>
                <div class="color1 mr-2">{{ item.username }}</div>
                <div>{{ item.phone }}</div>
              </div>
              <div class="line"></div>
              <div class="flex fz-10">
                <div class="li-desc" :style="{'color':item.isonline?'#67C23A':'#E6A23C'}">{{item.isonline == 1 ? '在线':'离线' }}</div>
                <div class="li-desc">{{ userIdentity[item.type] }}</div>
                <div class="li-desc">距离：<span class="color2">{{ item.distance ? item.distance : ' - - '}}公里</span></div>
                <div class="li-desc">预计到达时间：<span class="color2">{{ item.duration ? item.duration : ' - - ' }}分钟</span></div>
              </div>
            </div>
            <div class="flex ai-c jc-e" style="width:75px">
              &nbsp;
              <img class="img-box" v-if="false" src="/img/phone.png" @click="callPhone(item.phone)" />
            </div>
          </div>
        </div>
      </div>
      <div class="flex ai-c jc-e callbox" v-if="false">
        <el-input placeholder="请输入呼叫内容" v-model="callText"></el-input>
        <el-button type="primary" size="large" @click="callPhoneAll">一键呼叫</el-button>
      </div>
    </div>


  </div>
</template>
  
<script>
import { postMethodCommon } from '@/api/common.js';
import appConfig from '../../../../public/config/app.json'
import axios from "axios";
export default {
  name: 'monitorbox',
  props: ['fireData'],
  data() {
    return {
      checkList: [2,3,4,5],
      listData: [],
      allData: [],
      fireLngLat: '',
      distanceradio: 5,
      personnelGraphicLayer: null,
      graphicLayerArr: [],
      areaName: localStorage.getItem("areaName"),
      checkPhoneArr: [],
      startdistance: null,
      enddistance: null,
      callText: null,
      searchUserName:null,
      userIdentity:["护林员","消防员","护林员","消防员","巡查员","管理人员"]
    }
  },
  watch: {
    fireData: {
      handler(newVal, oldVal) {
        this.fireLngLat = [newVal.lng, newVal.lat]
        this.getListData();
      },
      immediate: true,
      // 开启深度监听 deep
      deep: true
    },
    status: {
      handler(newVal, oldVal) {
        console.log('status', newVal)
      }
    },
  },
  created() {
    // console.log('appConfig',appConfig.gaodeApi)
    // this.getListData();
    window.videoCall = this.videoCall
  },
  methods: {
    videoCall(phone) {
      this.$emit("videoCall", phone);
    },
    close() {
      this.graphicLayerArr.forEach(item => {
        this.personnelGraphicLayer.removeGraphic(item)
      })
      this.$emit('close')
    },
    phoneCheckClick(item) {
      if (!item.phone) {
        return
      }
      if (this.checkPhoneArr.includes(item.phone)) {
        this.checkPhoneArr = this.checkPhoneArr.filter(val => val != item.phone)
      } else {
        this.checkPhoneArr.push(item.phone)
      }
    },
    checkChange() {
      this.getListData();
    },
    flyToPosition(item) {
      console.log('ii', item)
      if (item.lat && item.lng) {
        let lngLat = [item.lng, item.lat]
        window.globalmap.flyToPoint(lngLat, { radius: 1000, "pitch": -90 });
      } else {
        console.log('人员无坐标')
      }

    },
    //
    handlerRadioChange(e){

    },

    // 根据距离筛选
    radioChange() {

      let arr = this.allData
      let newArr = [];

      // 先判断是否有自定义范围
      if(this.startdistance || this.enddistance){
        this.distanceradio = null;
        arr.forEach(item => {
          if(this.startdistance || this.enddistance){
            if(item.distance && Number(item.distance) >= this.startdistance && Number(item.distance) < this.enddistance){
              newArr.push(item)
            }
          }else{
            newArr.push(item)
          }
        })
      }else{
        if (this.distanceradio == 1) {
          arr.forEach(item => {
            if (item.distance && item.distance < 1) {
              newArr.push(item)
            }
          })
          this.listData = newArr
        }

        if (this.distanceradio == 2) {
          arr.forEach(item => {
            if (item.distance && item.distance < 5) {
              newArr.push(item)
            }
          })
          this.listData = newArr
        }

        if (this.distanceradio == 3) {
          arr.forEach(item => {
            if (item.distance && item.distance < 10) {
              newArr.push(item)
            }
          })
          this.listData = newArr
        }

        if (this.distanceradio == 4) {
          arr.forEach(item => {
            if (item.distance && item.distance >= 10) {
              newArr.push(item)
            }
          })

          this.listData = newArr

        }

        if (this.distanceradio == 5) {
          newArr = arr;
          this.listData = arr
        }
      }

      // 根据搜索内容筛选
      if(this.searchUserName){
        this.listData = newArr.filter((item,index)=>{
          return item.username.match(this.searchUserName);
        })
      }

      this.handleGraphic()

    },
    selListData() {
      // 按照人名查询
      let arr = this.allData
      let newArr = [];

      arr.forEach(item => {
        if(this.startdistance || this.enddistance){
          if(item.distance && Number(item.distance) >= this.startdistance && Number(item.distance) < this.enddistance){
            newArr.push(item)
          }
        }else{
          newArr.push(item)
        }
      })

      

      this.listData = newArr;
      this.handleGraphic()

    },
    handleGraphic() {
      let _this = this;
      if (this.personnelGraphicLayer == null) {
        this.personnelGraphicLayer = new mars3d.layer.GraphicLayer();
        window.globalmap.addLayer(this.personnelGraphicLayer);
      }
      this.graphicLayerArr.forEach(item => {
        this.personnelGraphicLayer.removeGraphic(item)
      })
      this.graphicLayerArr = []
      this.listData.forEach((item, index) => {
        let graphic = new mars3d.graphic.BillboardEntity({
          position: [item.lng, item.lat],
          style: {
            image: "img/jiuyuanrenyuan.png",
            horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 200000), // 按视距距离显示
            scaleByDistance: new Cesium.NearFarScalar(1000, 0.4, 8000, 0.2),
            clampToGround: true
          },
          "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">${item.username}</div>
                              <div class="label-content">
                                <div class="data-li">
                                      <div class="data-value">${_this.userIdentity[item.type]}</div>
                                  </div>
                                  <div class="data-li">
                                      <div class="data-label">电话：</div>
                                      <div class="data-value">${item.phone}</div>
                                  </div>
                                  <div class="data-li">
                                      <div class="data-label"></div>
                                      <div class="data-value">
                                          <span class="label-tag data-value-status-2" title="视频通话" onclick="videoCall('${item.phone}')">视频通话</span></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": -50,
            "offsetX": 30,
            "template": "{content}",
            "horizontalOrigin": "Cesium.HorizontalOrigin.LEFT",
            "verticalOrigin": "Cesium.VerticalOrigin.CENTER"
          },
          pointerEvents: true
        })
        this.graphicLayerArr.push(graphic)

        this.personnelGraphicLayer.addGraphic(graphic);
      })
    },
    callPhone(phone) {
      let time1 = this.fireData.reportTime.split(' ')[0]
      let time2 = this.fireData.reportTime.split(' ')[1]
      let date1 = time1.split('-')
      let date2 = time2.split(':')
      let dates = date1[0] + '年' + date1[1] + '月' + date1[2] + '日 ' + date2[0] + '时' + date2[1] + '分' + date2[2] + '秒'
      let param = {
        phoneNumbers: phone,
        time: dates,
        address: this.fireData.address
      }
      let url = '/FireCodePC/EventAssign?phoneNumbers=' + param.phoneNumbers + '&time=' + param.time + '&address=' + param.address
      postMethodCommon('/FireCodePC/EventAssign', param).then(res => {
        console.log('sa', res)
        if (res.code == 200) {
          this.$message({
            message: res.message,
            type: 'success'
          });
        }
      })
    },
    callPhoneAll() {
      console.log("fireData", this.fireData)
      if (!this.fireData.reportTime) {
        return
      }
      let phoneArr = []
      let time1 = this.fireData.reportTime.split(' ')[0]
      let time2 = this.fireData.reportTime.split(' ')[1]
      let date1 = time1.split('-')
      let date2 = time2.split(':')
      let dates = date1[0] + '年' + date1[1] + '月' + date1[2] + '日 ' + date2[0] + '时' + date2[1] + '分' + date2[2] + '秒'


      if (this.checkPhoneArr.length > 0) {
        phoneArr = this.checkPhoneArr
      } else {
        this.listData.forEach(item => {
          phoneArr.push(item.phone)
        })
      }
      
      let param = {
        phoneNumbers: phoneArr.join(','),
        time: dates,
        address: this.fireData.address,
        work: this.callText
      }


      postMethodCommon('/FireCodePC/EventAssign', param).then(res => {
        if (res.code == 200) {
          this.$message({
            message: res.message,
            type: 'success'
          });
        }
      })
    },
    getListData() {
      let arr = []
      let _this = this

      if (this.checkList.length > 1) {
        arr = [1, 2]
      } else if (this.checkList.length < 1) {
        arr = []
      } else {
        if (this.checkList[0] == '护林员') {
          arr = [1]
        } else {
          arr = [2]
        }
      }

      this.personnelGraphicLayer = null

      let query = {
        areaname: this.areaName,
        lng: this.fireData.lng,
        lat: this.fireData.lat
      }
      postMethodCommon("/FireCodePC/GetForestRangers?areaname=" + this.areaName + "&lng=" + this.fireData.lng + "&lat=" + this.fireData.lat, this.checkList).then(res => {
        let rel = res.data
        // let rel = []
        // res.data.forEach((item,index) =>{
        //     if(index == 1){
        //         rel.push(item)
        //     }
        // })

        this.handleData(rel).then(dl => {

          if(dl){
            // _this.listData = dl
            // _this.allData = dl
            dl.forEach((item,index)=>{
              console.log("typeof",typeof dl[index].distance)
              if(typeof dl[index].distance != "undefined"){
                dl[index].distance = Number(dl[index].distance);
              }else{
                dl[index].distance = null;
              }
            })

            // 进行综合排序
            dl.sort((a,b) =>
              {
               
                if (a.distance === null && b.distance === null) return 0; // 两者都是 null，保持原有顺序
                if (a.distance === null) return 1; // a 是 null，排到后面
                if (b.distance === null) return -1; // b 是 null，排到后面

                if (a.isonline !== b.isonline) {
                  return (a.isonline === b.isonline) ? 0 : a.isonline ? -1 : 1; // 在线用户优先
                }

                return a.distance - b.distance; // 对其他元素进行升序排序
              }
            )

            // 获取到全部的排序数据
            _this.listData = dl;
            _this.allData = dl;

            // 根据距离筛选
            setTimeout(() => {
              _this.radioChange()
            }, 1000)
          }
        })

      })
    },
    async handleData(data) {

      return new Promise(async (resolve,reject)=>{
        let hasLngLatItems = [];
        let allRequest = [];
        try{
          data.forEach((item,index) => {
            // 只请求有位置的数据
            if(item.isonline == 1){
                hasLngLatItems.push(index)
                let url = "https://restapi.amap.com/v3/direction/driving?key=" + appConfig.gaodeApi + "&origin=" + this.fireLngLat[0] + "," + this.fireLngLat[1] + "&destination=" + item.lng + "," + item.lat + "&extensions=base";
                let request = axios({method: 'get',url: url})
                allRequest.push(request);
            }
          })
          // 所有请求完成 再执行排序
          let  responses = await  Promise.all(allRequest);

          // 将信息补充道数组中
          responses.forEach((res,idx)=>{
              if (res.data.route && res.data.route.paths && res.data.route.paths[0]) {
                  let obj = res.data.route.paths[0]
                  data[hasLngLatItems[idx]].distance = (obj.distance / 1000).toFixed(2)
                  data[hasLngLatItems[idx]].duration = Math.round(obj.duration / 60)
              }
          })
          resolve(data);
        }catch(e){
          console.log(e);
          reject(null)
        }
      })
      


      /**
       * .then(res => {
                  // 如果有导航路线
                  if (res.data.route.paths[0]) {
                      let obj = res.data.route.paths[0]
                      item.distance = (obj.distance / 1000).toFixed(2)
                      item.duration = Math.round(obj.duration / 60)
                  }
                }).catch(err => {
                  reject(null);
                })
       * 
       * 
       * */ 
    }
    /*
      
    */ 
  }
}
</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: 160px;
  color: #fff;
  text-align: left;
}

.titlebox {
  width: 100px;
  text-align: right;
}

.box-container {
  width: calc(100% - 0px);
  padding: 0px 12px;
  height: calc(100% - 240px);
}

.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% - 70px);
  overflow-y: auto;
}

.table-body .table-li {
  width: 100%;
  height: 99px;
  background: #0E2320;
  margin-bottom: 10px;
  padding: 10px 15px;
}





::-webkit-scrollbar-track,
::-webkit-scrollbar-thumb {
  border: 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, .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-checkbox {
  color: #fff;
  margin-right: 0;
}

.el-checkbox__label {
  padding-left: 0;
}

.el-checkbox__input {
  display: inline;
}

.el-radio {
  margin-right: 10px;
  color: #fff;
  margin-bottom: 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;
}

.color1 {
  color: #156EF9;
}

.color2 {
  color: #E8A700;
}

.line {
  width: 100%;
  height: 1px;
  border: 1px solid #2D80EE;
}

.li-desc {
  padding: 3px 7px;
  background: #14332F;
  border-radius: 2px;
  margin-right: 8px;
}

.li-desc:last-child {
  margin-right: 0;
}

.img-box {
  width: 44px;
  height: 44px;
  border-radius: 44px;
  cursor: pointer;
}

.callbox {
  width: 95%;
  height: 80px;
}

.phonecheckbox {
  width: 14px;
  height: 14px;
  border: 1px solid #DCDFE6;
  border-radius: 3px;
  background: #fff;
  margin-right: 10px;
}

.phonecheckbox.active {
  background: #409EFF;
  border: 1px solid #409EFF;
  position: relative;
}

.phonecheckbox.active::after {
  box-sizing: content-box;
  content: "";
  border: 1px solid #FFF;
  border-left: 0;
  border-top: 0;
  width: 3px;
  height: 7px;
  left: 4px;
  top: 1px;
  position: absolute;
  transition: transform .15s ease-in .05s;
  transform-origin: center;
  transform: rotate(45deg) scaleY(1);
}</style>