<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">轨迹回放</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="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 id="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>
          {{formatDate(item.time)}}
        </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'

export default {
  name: 'peopleLogData',
  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,
      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: [],
      videoDate: '',
      videoList: [],
      peoItem: null,
      posDate: [],
      posList: [],
      pagePos: 1,
      sizePos: 10,
      totalPos: 0,
    }
  },
  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: {
    loadData() {
      var param = this.query;
      param.page = this.page - 1;
      param.size = this.size;
      param.vague = {cameraid:param.cameraid||undefined,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;
            }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,
      };
      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)}`;
    },
    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 = {cameraid:param.cameraid||undefined,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;
    },
    // 点击搜索
    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" scope>
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;
}

.item {
  padding: 2px;
  width: 100%;
  color: purple;
  font-size: 18px;
  font-weight: bolder;
  text-align: center;
}
.image-slot {
  width: 308px;
  height: 173px;
}
</style>
