<template>
  <div class="common-page device-manage">

    <div class="option page-row">
      <!--工具栏-->
      <div class="head-container">
        <!-- 搜索 -->
        <label class="el-form-item-label" style="font-weight: 500;">安全帽</label>
        <el-input v-model="query.safetyhatmac" clearable size="small" placeholder="请输入安全帽MAC" style="width:180px;"/>
<!--        <label class="el-form-item-label" style="font-weight: 500;">摄像头id</label>-->
<!--        <el-input v-model="query.cameraid" clearable size="small" placeholder="请输入id" style="width:180px;"/>-->
        <label class="el-form-item-label" style="font-weight: 500;">人员姓名</label>
        <el-input v-model="query.name" clearable size="small" placeholder="请输入姓名" style="width:180px;"/>
        <label class="el-form-item-label" style="font-weight: 500;">工种</label>
        <el-select v-model="query.type" placeholder="请选择">
          <el-option v-for="item in stuOpts" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <el-button size="mini" type="success" icon="el-icon-search" @click="toSearch">搜索</el-button>
        <el-button size="mini" icon="el-icon-refresh" @click="clearLimit">重置</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <div class="panel-bottom page-row">
      <div class="ctin-box">
        <div class="content-within">
          <div class="content-fix">
            <div class="toolbar">
              <!--              <el-button size="mini" type="primary" icon="el-icon-plus" @click="toAdd">新增</el-button>-->
              <el-button size="mini" icon="el-icon-document" @click="downloadFile">导出</el-button>
            </div>
            <div class="content">
              <el-table :data="tableData" v-loading="loading" border style="width:auto">
                <el-table-column prop="safetyhatmac" label="安全帽MAC" align="center"></el-table-column>
                <!--                <el-table-column prop="cameraid" label="摄像头id" align="center"></el-table-column>-->
                <el-table-column prop="type" label="工种" align="center">
                  <template slot-scope="scope">
                    <span>{{ scope.row.type=='1'?'访客':'员工' }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="人员姓名" align="center"></el-table-column>
                <el-table-column prop="phone" label="电话" align="center"></el-table-column>
                <el-table-column label="操作" align="center" fixed="right">
                  <template slot-scope="scope">
                    <span class="link-cell" @click="openTrailView(scope.row)">轨迹回放</span>
                    <span class="link-cell" @click="openPosView(scope.row)">轨迹数据</span>
                    <span v-show="scope.row.userid" class="link-cell" @click="openvideoView(scope.row)">视频回放</span>
                    <span v-show="scope.row.userid" class="link-cell" @click="openPhotoView(scope.row)">相册</span>
                  </template>
                </el-table-column>
              </el-table>
              <!--分页组件-->
              <el-pagination :total="total" :current-page="page" style="margin-top: 8px;"
                             layout="total, prev, pager, next, sizes" @size-change="sizeChange"
                             @current-change="pageChange"/>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 轨迹回放 -->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="cancelForm" :visible="trailView" title="轨迹回放" width="1200px">
      <div class="head-container">
        <label class="el-form-item-label" style="font-weight: 500;">日期</label>
        <el-date-picker
          v-model="trailDate"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          :default-time="['00:00:00', '23:59:59']">
          start-placeholder="查询开始时间"
          end-placeholder="查询结束时间">
        </el-date-picker>
        <el-button size="mini" type="success" icon="el-icon-search" @click="drawTrail">查询</el-button>
      </div>
      <div id="centerDiv" class="mapcontainer">
        <mars3dViewerMap :url="configUrl" @onload="onMapload" ref="mars3dViewerMapMethod" mapKey="peopleTrailView" :clockAnimate="true"/>
      </div>
    </el-dialog>
    <!-- 轨迹数据 -->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="cancelForm" :visible="posView" title="轨迹数据" width="900px">
      <div class="head-container">
        <label class="el-form-item-label" style="font-weight: 500;">日期范围</label>
        <el-date-picker
          v-model="posDate"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
        <el-button size="mini" type="success" icon="el-icon-search" @click="loadPosList">查询</el-button>
        <el-button size="mini" icon="el-icon-document" @click="downloadFilePos">导出</el-button>
      </div>
      <el-table :data="posList" border style="width:auto;overflow-y:auto;" height="46vh">
        <el-table-column type="index" width="50" :index="indexMethod"></el-table-column>
        <el-table-column prop="safetyhatmac" label="安全帽MAC" align="center"></el-table-column>
        <el-table-column prop="name" label="姓名" align="center"></el-table-column>
        <el-table-column prop="x" label="X坐标" align="center"></el-table-column>
        <el-table-column prop="y" label="Y坐标" align="center"></el-table-column>
        <el-table-column prop="time" label="时间" align="center"></el-table-column>
      </el-table>
      <el-pagination :total="totalPos" :current-page="pagePos" style="margin-top: 8px;"
                     layout="total, prev, pager, next, sizes" @size-change="sizeChangePos" @current-change="pageChangePso"/>
    </el-dialog>
    <!-- 视频 -->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="cancelFormViedoRtc" :visible="videoRtc" title="实况" width="800px">
      <video id="remoteVideo" controls style="width:100%;height:440px;"></video>
    </el-dialog>
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="cancelFormViedo" :visible="videoDia" title="回放" width="800px">
      <div style="width:100%;height:440px;">
        <video id="videoRealtime" class="video-js vjs-default-skin vjs-big-play-centered vjs-fluid" controls data-setup="{}">
          您的浏览器不支持：HTML5 video.
        </video>
      </div>
    </el-dialog>
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="cancelForm" :visible="videoView" :title="title" width="800px">
      <div class="head-container">
        <label class="el-form-item-label" style="font-weight: 500;">日期</label>
        <el-date-picker
          v-model="videoDate"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
        <el-button size="mini" type="success" icon="el-icon-search" @click="loadvideoList">查询</el-button>
        <el-button size="mini" type="primary" icon="el-icon-video-camera" @click="realVideo">实时播放</el-button>
      </div>
      <el-table :data="videoList" border style="width:auto;height:45vh;overflow-y:auto">
        <el-table-column prop="safetyhatmac" label="录像时间" align="center">
          <template slot-scope="scope">
            {{formatDate(scope.row.time)}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160px">
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-video-camera-solid" @click="videoPlay(scope.row.url)">播放</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 相册 -->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="cancelForm" :visible="photoView" :title="title" width="1600px">
      <div class="items">
        <div class="item" v-for="(item,index) in photoList" :key="index">
          <el-image :src="item.image_url" :preview-src-list="[item.image_url]"><div slot="placeholder" class="image-slot">加载中<span class="dot">...</span></div></el-image>
          <div>{{formatDate(item.time)}}</div>
        </div>
        <div class="item" v-for="(item,index) in photoListVoid" :key="index">
          <div style="line-height: 200px;opacity:20%">暂无更多图片...</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-show="pageP>1" type="primary" icon="el-icon-arrow-left" @click="priorP()">上一页</el-button>
        <el-button type="primary" @click="nextP()">下一页<i class="el-icon-arrow-right el-icon--right"></i></el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {Tools, HttpReq, Dates} from '@/assets/js/common.js';
import {JSWebrtc} from '@/assets/js/jswebrtc.js';
import 'video.js/dist/video-js.css'
import videojs from 'video.js'
import 'videojs-contrib-hls'
import mars3dViewerMap from "../../../components/mars3d/Map5.vue";
import * as mars3d from "mars3d";
import * as Cesium from "mars3d-cesium";
import peopleIcon from "../../../assets/images/point.png";

export default {
  name: 'peopleLogData',
  components: {
    mars3dViewerMap,
  },
  data() {
    const basePathUrl = window.basePathUrl || ''
    return {
      configUrl: basePathUrl + 'config/config.json',
      videoPlayer: null,
      videoRtcPlayer: null,
      title: '新增',
      photoView: false,
      videoView: false,
      loading: false,
      videoDia: false,
      videoRtc: false,
      posView: false,
      trailView: false,
      page: 1,
      size: 10,
      total: 0,
      query: {},
      tableData: [],
      map: null,
      graphicLayer: null,
      stuOpts: [
        {label: '全部', value: undefined},
        {label: '访客', value: 1},
        {label: '员工', value: 0},
      ],
      pageP: 1,
      photoList: [],
      photoListVoid: [],
      videoDate: '',
      videoList: [],
      peoItem: null,
      posDate: [],
      posList: [],
      pagePos: 1,
      sizePos: 10,
      totalPos: 0,
      trailDate: [],
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.loadData();
      // const debounce = (func, dalay = 100, immediate = true) => {
      //   let timer, callNow = immediate;
      //   return (...args) => {
      //     if (timer) clearTimeout(timer);
      //     if (callNow) {
      //       func(...args);
      //       callNow = false;
      //     }
      //     timer = setTimeout(() => {
      //       func(...args);
      //     }, dalay)
      //   }
      // };
      // window.addEventListener('mousewheel', debounce((e)=>{
      //   if(this.photoView && e.wheelDelta<0){
      //     console.log("鼠标滚轮后滚",e)
      //   }
      // }), false)
    })
  },
  methods: {
    onMapload(map) {
      map.unbindContextMenu();
      var graphicLayer = new mars3d.layer.GraphicLayer();
      map.addLayer(graphicLayer);
      this.map = map;
      this.graphicLayer = graphicLayer;
    },
    drawTrail() {
      let map = this.map;
      let graphicLayer = this.graphicLayer;
      if (!(this.trailDate && this.trailDate.length)) {
        this.$message({
          message: '请输入查询时间范围'
        });
        return;
      }
      let param = {
        safetyhatmac: this.peoItem.safetyhatmac,
        page: 0,
        size: 43200,
        sort: `date,asc`
      };
      param.daterange = this.trailDate.join(',');
      this.$nextTick(() => {
        HttpReq.truckDispatching.propleGetLocus(param).then((res) => {
          if (res.code == 200) {
            if(res.body){
              let trailList = res.body.list;
              const property = new Cesium.SampledPositionProperty()
              property.forwardExtrapolationType = Cesium.ExtrapolationType.HOLD
              let start,stop,position;
              for (let i = 0, len = trailList.length; i < len; i++) {
                const item = trailList[i];
                position = Cesium.Cartesian3.fromDegrees(Number(item.y), Number(item.x), 200);
                let juliaDate = Cesium.JulianDate.fromDate(new Date(item.time.replace(/-/g,"/")));
                property.addSample(juliaDate, position);
                if (i === 0) {
                  start = juliaDate
                } else if (i === len - 1) {
                  stop = juliaDate
                }
                const graphic = new mars3d.graphic.PointPrimitive({
                  position: position,
                  style: {
                    pixelSize: 4,
                    color: "#cccccc"
                  },
                  popup: "id编号:" + item.id + "<br/>时间:" + item.time
                });
                graphicLayer.addGraphic(graphic);
              }
              // 设置时钟属性
              map.clock.startTime = start.clone()
              map.clock.stopTime = stop.clone()
              map.clock.currentTime = start.clone()
              map.clock.clockRange = Cesium.ClockRange.LOOP_STOP
              map.clock.multiplier = 5
              map.controls.timeline.zoomTo(start, stop)
              // 创建path对象
              let pathEntity = new mars3d.graphic.PathEntity({
                position: property,
                orientation: new Cesium.VelocityOrientationProperty(property),
                style: {
                  resolution: 1,
                  leadTime: 0,
                  trailTime: 3600,
                  color: "#ff0000",
                  width: 3
                },
                label: {
                  text: this.peoItem.name,
                  font_size: 18,
                  font_family: "楷体",
                  color: "#ff0000",
                  outline: true,
                  outlineColor: "#000000",
                  visibleDepth: false,
                  outlineWidth: 5,
                  horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                  verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                  pixelOffset: new Cesium.Cartesian2(0, -25) // 偏移量
                },
                billboard: {
                  image: peopleIcon,
                  scale: 0.5,
                  horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                  verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                  visibleDepth: false
                }
              })
              graphicLayer.addGraphic(pathEntity)
              this.map.setCameraView({ lat: trailList[0].x, lng: trailList[0].y, alt:300 });
            }
          }
        })
      })
    },
    loadData() {
      var param = this.query;
      param.page = this.page - 1;
      param.size = this.size;
      param.vague = {safetyhatmac: param.safetyhatmac || undefined, name: param.name || undefined};
      param.exact = {type: param.type};
      param.sort = `date,desc`;
      this.$nextTick(() => {
        //获取安检信息
        HttpReq.truckDispatching.propleGetPerequipment(param).then((res) => {
          if (res.code == 200) {
            this.loading = false;
            this.tableData = res.body.list;
            this.total = res.body.total;
          }
        })
      })
    },
    loadDataP() {
      var param = {
        userid: this.peoItem.userid,
        page: this.pageP,
      };
      this.$nextTick(() => {
        HttpReq.truckDispatching.propleGetHisphoto(param).then((res) => {
          if (res.code == 200) {
            if(res.body.data){
              this.photoList = res.body.data;
              this.totalP = res.body.total;
              this.photoListVoid=[];
              for(let i=10-this.photoList.length;i>0;i--){
                this.photoListVoid.push({});
              }
            }else{
              this.pageP--;
              this.$message({
                message: res.body.msg
              });
            }
          }
        })
      })
    },
    loadvideoList() {
      let param = {
        userid: this.peoItem.userid,
        year: `${this.videoDate.getFullYear()}`,
        month: `${('0' + (this.videoDate.getMonth() + 1)).substr(-2)}`,
        day: `${('0' + (this.videoDate.getDate())).substr(-2)}`
      };
      this.$nextTick(() => {
        HttpReq.truckDispatching.propleGetHisvideo(param).then((res) => {
          if (res.code == 200) {
            if(res.body.data){
              this.videoList = res.body.data;
            }else{
              this.$message({
                message: res.body.msg
              });
            }
          }
        })
      })
    },
    indexMethod(index) {
      return 1+index+this.pagePos*this.sizePos-this.sizePos;
    },
    loadPosList() {
      let param = {
        safetyhatmac: this.peoItem.safetyhatmac,
        page: this.pagePos - 1,
        size: this.sizePos,
        sort: `date,desc`
      };
      param.daterange = undefined;
      if (this.posDate && this.posDate.length) {
        param.daterange = this.posDate.join(',');
      }
      this.$nextTick(() => {
        HttpReq.truckDispatching.propleGetLocus(param).then((res) => {
          if (res.code == 200) {
            if(res.body){
              this.posList = res.body.list;
              this.totalPos = res.body.total;
            }
          }
        })
      })
    },
    openPhotoView(item) {
      this.title = '相册';
      this.photoView = true;
      this.peoItem = item;
      this.pageP = 1;
      this.photoList = [];
      this.loadDataP();
    },
    realVideo(){
      if(this.videoRtcPlayer){
        this.videoRtcPlayer.destroy();
        this.videoRtcPlayer = null;
      }
      this.videoRtc = true;
      this.$nextTick(() => {
        HttpReq.truckDispatching.propleGetRealvideo({
          mac: this.peoItem.safetyhatmac,
        }).then((res) => {
          if (res.code == 200) {
            if(res.body && res.body.api_url && res.body.play_url){
              this.videoRtcPlayer = new JSWebrtc.Player(res.body.api_url, res.body.play_url, {
                  video: document.getElementById("remoteVideo"),
                  autoplay: true,
                  onPlay: () => {
                    console.log('开始播放');
                  },
                  onFail: () => {
                    console.log('播放失败');
                    this.videoRtcPlayer.destroy();
                  }
                });
            }else{
              this.$message({
                message: '链接失败！'+res.body.msg
              });
            }
          }
        })
      })
    },
    videoPlay(url, tp){
      this.videoDia = true;
      this.$nextTick(() => {
        if(!this.videoPlayer){
          this.videoPlayer = videojs('videoRealtime', {
            fluid: true,
            bigPlayButton: false,
            textTrackDisplay: false,
            sources: [{ src:url, type: tp||"video/mp4" }],
            posterImage: true,
            errorDisplay: false,
            controlBar: true
          },  ()=> {
            console.log('video ready!')
            this.videoPlayer.play();
          })
        }else{
          let data = { src:url, type: tp||"video/mp4" }
          this.videoPlayer.pause();
          this.videoPlayer.src(data);
          this.videoPlayer.load(data);
          this.videoPlayer.play();
        }
      })
    },
    formatDate(time) {
      let d = time ? new Date(time * 1000) : new Date();
      return `${d.getFullYear()}/${('0' + (d.getMonth() + 1)).substr(-2)}/${('0' + (d.getDate())).substr(-2)} ${('0' + (d.getHours())).substr(-2)}:${('0' + (d.getMinutes())).substr(-2)}:${('0' + (d.getSeconds())).substr(-2)}`;
    },
    openTrailView(item) {
      this.trailView = true;
      this.peoItem = item;
      this.trailDate = [];
    },
    openPosView(item) {
      this.posView = true;
      this.peoItem = item;
      this.posList = [];
      this.posDate = [];
      this.pagePos = 1;
      this.sizePos = 10;
      this.totalPos = 0;
      this.loadPosList();
    },
    openvideoView(item) {
      this.title = '视频回放';
      this.videoView = true;
      this.peoItem = item;
      this.videoList = [];
      this.videoDate = new Date();
      this.loadvideoList();
    },
    download(text, name, suffix) {
      var link = document.createElement('a');
      link.style.display = 'none';
      link.href = URL.createObjectURL(new Blob([text], { type: "application/vnd.ms-excel" }));
      link.setAttribute('download', name + '.' + suffix);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    downloadFile() {
      var loading = this.$loading({
        lock: true,
        text: '请稍后.....',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      var param = this.query;
      param.page = this.page - 1;
      param.size = this.size;
      param.vague = {safetyhatmac:param.safetyhatmac||undefined,name:param.name||undefined};
      param.exact = {type:param.type};
      param.sort = `date,desc`;

      HttpReq.truckDispatching.propleGetHisout(param).then((res) => {
        loading.close();
        let d = new Date();
        this.download(res, `人员设备历史记录${d.getFullYear()}${('0'+(d.getMonth()+1)).substr(-2)}${('0'+(d.getDate())).substr(-2)}`, 'xlsx')
      })
    },
    downloadFilePos() {
      var loading = this.$loading({
        lock: true,
        text: '请稍后.....',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      let param = {
        safetyhatmac: this.peoItem.safetyhatmac,
        page: this.pagePos - 1,
        size: this.sizePos,
      };
      param.daterange = undefined;
      if (this.posDate && this.posDate.length) {
        param.daterange = this.posDate.join(',');
      }
      HttpReq.truckDispatching.propleGetLocusout(param).then((res) => {
        loading.close();
        let d = new Date();
        this.download(res, `轨迹数据${d.getFullYear()}${('0'+(d.getMonth()+1)).substr(-2)}${('0'+(d.getDate())).substr(-2)}`, 'xlsx')
      })
    },
    cancelFormViedoRtc(){
      this.videoRtc = false;
      if(this.videoRtcPlayer){
        this.videoRtcPlayer.destroy();
        this.videoRtcPlayer = null;
      }
    },
    cancelFormViedo(){
      this.videoDia = false;
    },
    cancelForm() {
      this.photoView = false;
      this.videoView = false;
      this.videoDia = false;
      this.posView = false;
      if (this.trailView) {
        this.graphicLayer.clear();
      }
      this.trailView = false;
    },
    // 点击搜索
    toSearch() {
      this.page = 1;
      this.loadData();
    },
    // 重置搜索
    clearLimit() {
      this.query = {};
      this.loadData()
    },
    pageChange(e) {
      this.page = e
      this.loadData()
    },
    pageChangePso(e) {
      this.pagePos = e
      this.loadPosList()
    },
    sizeChange(e) {
      this.page = 1
      this.size = e
      this.loadData()
    },
    sizeChangePos(e) {
      this.pagePos = 1
      this.sizePos = e
      this.loadPosList()
    },
    priorP(){
      this.pageP -= 1;
      this.loadDataP()
    },
    nextP(){
      this.pageP += 1;
      this.loadDataP()
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
div::-webkit-scrollbar{
  display:none
}
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.cell-input {
  //min-width: 220px;
}

.form-cell {
  margin: 0 !important;
  width: 100%;
}

.grid-content {
  //border: 1px solid rgba(100, 100, 100, 0.1);
  padding: 5px 30px;
}
.cell-box {
  min-width: 120px;
}
.cell-box .el-input__inner {
  border: 1px solid rgba(100, 100, 100, 0.1);
}

.cell-box .el-input.is-disabled .el-input__inner {
  border: 1px solid rgba(100, 100, 100, 0.1);
  background: white;
  cursor: text;
}

.cell-box .el-input.is-disabled .el-input__icon {
  cursor: text;
}

.cell-box .el-icon-arrow-up:before {
  content: '';
}

.mapcontainer {
  height: 30vh;
  width: 680px;
  overflow: hidden;
}
.link-cell {
  color: dodgerblue;
  cursor: pointer;
}

.items {
  width: 100%;
  height: 420px;
  margin: 0 auto;
  column-count: 5;
  column-gap: 0;
  list-style: none;
  column-fill: balance;
}

.item {
  padding: 2px;
  width: 100%;
  color: #3e3e3e;
  font-size: 18px;
  font-weight: bolder;
  text-align: center;
  break-inside: avoid;
}
.image-slot {
  width: 308px;
  height: 173px;
}
.mapcontainer {
  height: 60vh;
  width: 1160px;
  overflow: hidden;
}
.mars3d-clockAnimate {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 28px;
  z-index: 999;
  color: white;
  background: linear-gradient(to bottom, rgba(116, 117, 119, 1) 0%, rgba(58, 68, 82, 1) 11%, rgba(46, 50, 56, 1) 46%, rgba(53, 53, 53, 1) 81%, rgba(53, 53, 53, 1) 100%);
}
</style>
