<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-left">
        <div class="filter-item">
          设备id:
          <el-input
            v-model="query.deviceId"
            placeholder="请输入设备id"
            style="width: 150px"
          ></el-input>
        </div>
        <div class="filter-item">
          通道id:
          <el-input
            v-model="query.id"
            placeholder="请输入通道id"
            style="width: 150px"
          ></el-input>
        </div>
        <div class="filter-item">
          通道名称:
          <el-input
            v-model="query.name"
            placeholder="请输入通道名称"
            style="width: 150px"
          ></el-input>
        </div>
        <div class="filter-item">
          通道状态:
         <el-select
              v-model="query.status"
              placeholder="请选择通道状态"
              clearable
              size="small"
               style="width: 150px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
        </div>
        <div class="filter-item">
          通道类型:
         <el-select
              v-model="query.cameraType"
              placeholder="请选择通道类型"
              clearable
              size="small"
               style="width: 150px"
            >
              <el-option
                v-for="dict in cameraTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
        </div>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="getData()"
          >搜索</el-button
        >
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          class="search-button"
          @click="getDhDeviceListNew()"
          >同步摄像头信息</el-button
        >
      </div>
      <div class="handle-button-right">
      </div>
    </div>
    <!-- <el-divider></el-divider> -->
    <div ref="table">
      <el-table
      :data="tableData"
      style="width: 100%;margin-top:10px"
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      v-loading="loading"
      :max-height="tableHeight"
    >
      <el-table-column prop="{deviceName}" label="设备名称"  show-overflow-tooltip>
        <template  slot-scope="scope">
            {{scope.row.deviceName}}
        </template>
      </el-table-column>
      <el-table-column prop="deviceId" label="设备Id" show-overflow-tooltip></el-table-column>
      <el-table-column prop="id" label="通道Id" show-overflow-tooltip></el-table-column>
      <el-table-column prop="name" label="通道名称" show-overflow-tooltip></el-table-column>
      <el-table-column prop="status" label="状态" show-overflow-tooltip>
        <template  slot-scope="scope">
            {{scope.row.status == "0" ? "未知" : scope.row.status == "1" ? "在线" : scope.row.status == "2" ? "离线" : ""}}
        </template>
      </el-table-column>
      <el-table-column  prop="type" label="设备类型" show-overflow-tooltip>
         <template  slot-scope="scope">
            {{
              scope.row.type == "1" ? "编码单元" : scope.row.type == "2" ? "解码单元" :
              scope.row.type == "3" ? "报警输入单元" : scope.row.type == "4" ? "报警输出单元" :
              scope.row.type == "5" ? "电视墙输入单元" : scope.row.type == "6" ? "电视墙输出单元" :
              scope.row.type == "7" ? "门禁单元" : scope.row.type == "8" ? "对讲单元" :
              scope.row.type == "10" ? "动环单元" : scope.row.type == "14" ? "闸道单元" :
              scope.row.type == "15" ? "LED 单元" : scope.row.type == "16" ? "周界单元" : ""
            }}
        </template>
      </el-table-column>

      <el-table-column   prop="manufacturer" label="品牌" show-overflow-tooltip>
        <template  slot-scope="scope">
            {{scope.row.manufacturer == "0" ? "未知" : scope.row.manufacturer == "1" ? "大华" :scope.row.manufacturer == "2" ? "海康" : ""}}
        </template>
      </el-table-column>
      <el-table-column   prop="cameraType" label="通道类型" show-overflow-tooltip>
        <template  slot-scope="scope">
            {{scope.row.cameraType == "1" ? "枪机" : scope.row.cameraType == "2" ? "球机"
            : scope.row.cameraType == "3" ? "半球" : scope.row.cameraType == "4" ? "证据通道" :""}}
        </template>
      </el-table-column>
      <el-table-column  prop="longitude" label="经度" show-overflow-tooltip></el-table-column>
      <el-table-column  prop="latitude" label="维度" show-overflow-tooltip></el-table-column>
      <el-table-column  prop="address" label="安装位置" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="190" fixed="right">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-video-play"
            style="color: #406ce5"
            @click="play(scope.row)"
            >播放</el-button
          >
          <el-button
            icon="el-icon-video-play"
            style="color: #406ce5"
            @click="Hplay(scope.row)"
            >回放</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    </div>


    <el-pagination
      background
      @current-change="handleCurrentChange"
      :page-sizes="[10, 15, 20, 30]"
      @size-change="handleSizeChange"
      :current-page="query.pageNo"
      :page-size="query.pageSize"
      layout="sizes,prev, pager, next"
      :total="totalCount"
    >
    </el-pagination>
    <el-dialog title="回放时间选择" :visible.sync="dialogFormVisible3" width="3000">
      <div class="block">
        <el-date-picker
          @change="dateData"
          value-format="yyyy-MM-dd HH:mm:ss"
          v-model="value"
          range-separator
          type="datetimerange"
          align="center"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="picker"
          :default-time="['00:00:00', '23:59:59']">
        </el-date-picker>
        <el-button
          v-if="dateDataJlStatus"
          size="small"
          type="primary"
          class="search-button pickerBut"
          @click="dateDataJl" >确定</el-button>

      </div>
    </el-dialog>
    <!-- 本地注册 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form v-for="(from, index) in from_data" :key="index">
        <el-form-item
          :label="from.label"
          :label-width="formLabelWidth"
          v-if="from.bool == true"
        >
          <el-select
            @change="select_Value(index)"
            v-model="from.value"
            placeholder="请选择"
            style="width: 220px"
          >
            <el-option
              v-for="item in from.array"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          @click="dialogFormVisible = false"
          style="background: #f6f6f6"
          >取 消</el-button
        >
        <el-button type="primary" @click="registerLocalDevice()">{{
          this.title
        }}</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogTable2" @close='closeDialog'>
      <template slot="title">
        <div
          class="titleZise"
          style="font-size: 15px; color: #484848; font-weight: 700"
        >
          {{ this.cameraNo }}
        </div>
      </template>
      <video
        class="hlsVideo monitor-height"
        ref="hlsVideo"
        style="width: 100%"
        controls
        preload="true"
        muted
      ></video>
    </el-dialog>
  </div>
</template>
<script>
// 引入导出Excel表格依赖
import FileSaver from "file-saver";
import XLSX from "xlsx";
import Hls from "hls.js";
import { getLocalChannel, getDhDeviceListNew } from "@/api/device/camera";
export default {
  name: "javascriptthree",
  data() {
    return {
      // 状态数据字典
      statusOptions: [
        {
          dictLabel:"未知",
          dictValue:0
        },{
          dictLabel:"在线",
          dictValue:1
        },{
          dictLabel:"离线",
          dictValue:2
        }
      ],

      cameraTypeOptions:[
        {
          dictLabel:"枪机",
          dictValue:1
        },{
          dictLabel:"球机",
          dictValue:2
        },{
          dictLabel:"半球",
          dictValue:3
        },{
          dictLabel:"证据通道",
          dictValue:4
        }
      ],
      listQuery:{
        deviceCode:undefined,
        deviceName:undefined,
        dwtype:undefined,
        pageNo:1,
        pageSize:15,
        sort:undefined,
      },
      dialogWidth: "60%",
      dialogWidth1: "70%",
      formLabelWidth: "130px",
      //input输入框--设备id
      device_id: "",
      //input输入框--设备名称
      device_name: "",

      dialogTable: false,
      gridData: [],
      gridData1: [],
      dialogTable1: false,
      cameraNo: "",
      dialogTable2: false,
      hls: "",
      //动态列表信息存储
      tableData:[],
      cols: [],
      //列表总数存储
      totalCount: 0,
      // //列表起始页
      // pageNo: 1,
      // //列表每页长度
      // pageSize: 15,
      //本地注册弹窗
      dialogFormVisible: false,
      //公共title （本地注册）
      title: "",
      //from表单提交
      from_data: [],
      //本地注册列表单条信息存储
      row: "",
      status2:false,

      value: '',
      dialogFormVisible3:false,
      starTime:undefined,
      endTime:undefined,
      hrow:undefined,
      loading:true,
      query:{
        id:undefined,
        deviceId:undefined,
        uuid:undefined,
        cameraType:undefined,
        name:undefined,
        status:undefined,
        pageNo:1,
        pageSize:15,
        unitType:1,
      },
      dateDataJlStatus:false,//回放记录时间button状态
      //表格自适应高度
      tableHeight:undefined,
    };
  },
  mounted() {
    // table高度
    if(window.innerWidth <1920){
      this.tableHeight = window.innerHeight - 300
    }else{
      this.tableHeight = window.innerHeight - 295
    }
    // 监听窗口大小变化
    let self = this;
    window.onresize = function() {
      self.tableHeight = window.innerHeight - 300
    }
  },
  created() {
    this.$once("hook:beforeDestroy", () => {
      this.destroyHls();
    });
    this.getData();
  },
  methods: {
    
      /** 重置按钮操作 */
      resetQuery() {
        this.query = {
          id:undefined,
          deviceId:undefined,
          uuid:undefined,
          cameraType:undefined,
          name:undefined,
          status:undefined,
          pageNo:1,
          pageSize:15,
          unitType:1,
        },
        this.handleQuery();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getData();
      },
    //同步信息
    getDhDeviceListNew(){
      getDhDeviceListNew().then((res)=>{
        this.$message.success("数据同步请求已发送，请稍后刷新查看")
      })
    },
    //回放时间选项
    dateData(val){
      this.starTime = new Date(val[0]).getTime()
      this.endTime = new Date(val[1]).getTime()
      this.dialogFormVisible3 = false
      this.playH(this.starTime/1000,this.endTime/1000)
    },
    //记录回放时间选项
    dateDataJl(){
      this.dialogFormVisible3 = false
      this.playH(this.starTime/1000,this.endTime/1000)
    },
    //数据初始化
    getData(){
      let arr = []
      getLocalChannel(this.query).then(Response =>{
        for(let i = 0; i<Response.data.pageList.length; i++){
          arr[i] = {}
          arr[i] = Response.data.pageList[i]
        }
        this.tableData = arr
        this.totalCount = Response.data.totalCount
        this.loading = false
        this.status2 = true
      })
    },
    Select() {
      this.Select_DeviceList();
    },
    Select_DeviceList(data) {
      var that = this;
      that.cols = [
        {
          property: "id",
          label: "设备id",
          width: "",
        },
        // {
        //   property:"uuid",
        //   label:"设备唯一编码",
        //   width:""
        // },
        {
          property: "name",
          label: "设备名称",
          width: "",
        },
        {
          property: "deviceIp",
          label: "设备IP",
          width: "",
        },
        {
          property: "manufacturer",
          label: "厂商类型",
          width: "",
        },
        {
          property: "unitnum",
          label: "单元数目",
          width: "",
        },
        {
          property: "devicePort",
          label: "设备端口",
          width: "",
        },
        {
          property: "registerStatus",
          label: "本地注册",
          width: "",
        },
        {
          property: "status",
          label: "设备状态",
          width: "",
        },
      ];
      //获取视频设备列表
      api.getLocalDeviceList(data).then((request) => {
        that.tableData = [];
        that.totalCount = request.totalCount;
        for (let i = 0; i < request.pageList.length; i++) {
          var pageList = request.pageList[i];
          that.tableData.push(pageList);

          pageList.manufacturer == 1
            ? (pageList.manufacturer = "大华")
            : pageList.manufacturer == 2
            ? (pageList.manufacturer = "海康")
            : (pageList.manufacturer = "未知");

          pageList.status == 1
            ? (pageList.status = "在线")
            : pageList.status == 2
            ? (pageList.status = "离线")
            : "";
        }
      });
    },
    //分页查询
    handleCurrentChange(val) {
      this.query.pageNo = val;
      this.getData();
    },
    //分页查询
    handleSizeChange(val) {
      this.query.pageSize = val;
      this.getData();
    },
    handleEdit(index, row) {
      var that = this;
      that.title = "本地注册";
      that.row = row;
      that.from_data = [
        {
          prop: "buildUuid",
          label: "建筑名称:",
          value: "",
          array: [],
          bool: true,
        },
        {
          prop: "floorUuid",
          label: "楼层名称:",
          value: "",
          array: [],
          bool: false,
        },
        // { prop: "roomUuid", label: "房间名称:", value: "" ,array: [],bool: false},
        {prop: "deviceUuid", label: "楼层ID:", value: "" ,array: [] , bool: false}
      ];
      api
        .queryBuild({
          buildAddr: "",
          buildName: "",
          latitude: "",
          longitude: "",
          pageNo: "",
          pageSize: "",
        })
        .then((requset) => {
          for (let i = 0; i < requset.pageList.length; i++) {
            var pageList = requset.pageList[i];
            that.from_data[0].array.push({
              label: pageList.buildName,
              value: pageList.buildUuid,
            });
          }
        });
      that.dialogFormVisible = true;
    },
    select_Value(index) {
      var that = this;
      if (index == 0) {
        that.from_data[1].array = [];
        that.from_data[1].value = "";

        api
          .queryFloor({
            floorBuildUuid: that.from_data[index].value,
            floorName: "",
            pageNo: "",
            pageSize: "",
          })
          .then((requset) => {
            var requset = requset.pageList;
            if (requset.length > 0) {
              that.from_data[1].bool = true;
              for (let i = 0; i < requset.length; i++) {
                var pageList = requset[i];
                that.from_data[1].array.push({
                  label: pageList.floorName,
                  value: pageList.floorUuid,
                });
              }
            } else {
              that.from_data[1].bool = false;
            }
          });
        api.queryThingsjFloorId().then((requset)=>{
          if (requset.data.length > 0) {
            that.from_data[2].bool = true;
            for (let i = 0; i < requset.data.length; i++) {
              var pageList = requset.data[i];
              that.from_data[2].array.push({
                label: pageList.thingjsFloorId,
                value: pageList.thingjsFloorId,
              });
            }
          }else{
            that.from_data[2].bool = false;
          }
        })
      }
    },
    registerLocalDevice() {
      var that = this;
      var row = that.row;
      var from = that.from_data;
      api
        .registerLocalDevice({
          buildUuid: from[0].value,
          deviceIp: row.deviceIp,
          devicePort: row.devicePort,
          floorUuid: from[1].value,
          thingjsFloor: from[2].value,
          nvrIp: row.nvrIp,
          nvrPort: row.nvrPort,
          deviceName:row.name,
          status: row.registerStatus === "已注册" ? 0 : 1,
        })
        .then((requset) => {
          this.dialogFormVisible = false
          this.Select();
        });
    },
    //定义导出Excel表格事件
    exportExcel() {
      /* 从表生成工作簿对象 */
      var wb = XLSX.utils.table_to_book(document.querySelector("#out-table"));
      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          "sheetjs.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    //播放按钮
    play(row) {
      this.destroyHls()
      let url = "http://" + row.nvr_ip + ":" + row.hls_port + "/live/cameraid/" + row.deviceId + "%24" + row.id.split("$")[(row.id.split("$")).length-1]  + "/substream/1.m3u8"
      this.loadVideoFn(url)
    },
    //回放url
    playH(start,end){
      this.destroyHls()
      let row = this.hrow
      let url = "http://" + row.nvr_ip + ":" + row.hls_port + "/vod/device/cameraid/" + row.deviceId + "%24" + row.id.split("$")[(row.id.split("$")).length-1] + "/substream/1/recordtype/1/totallength/" + Number(end-start) + "/begintime/" + start + "/endtime/" + end + ".m3u8"
      this.loadVideoFn(url)
    },

    destroyHls: function () {
      if (this.hls) {
        this.$refs.hlsVideo.pause();
        this.hls.destroy();
        this.hls = null;
      }
    },
    loadVideoFn(url) {
      this.dialogTable2 = true
      setTimeout(() =>{
        if (Hls.isSupported()) {
          this.hls = new Hls();
          this.hls.loadSource(url);
          this.hls.attachMedia(this.$refs.hlsVideo);
          this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
            console.log("加载成功");
            this.$refs.hlsVideo.play();
          });

          this.hls.on(Hls.Events.ERROR, (event, data) => {
            // console.log(event, data);
            // 监听出错事件
            console.log("加载失败");
          });
        }
      },1000)
    },

    //设备列表序号
    indexMethod(index) {
      return index + 1;
    },

    //回放视频
    Hplay(row){
      this.dialogFormVisible3 = true
      if(this.endTime){
        this.dateDataJlStatus = true
      }else{
        this.dateDataJlStatus = false
      }
      this.hrow = row
    },
    //关闭弹框
    closeDialog(){
      this.destroyHls()
    },
  },

};
</script>
<style>
.el-dialog__headerbtn{
  top:3px;
}
.el-range-editor.el-input__inner{
  width:80%;
  margin:0 10% !important;
}
.pickerBut{
  width:10%;display: inline-block;
  margin:20px 45% 0;
}
</style>
