<template>
  <div class="main">
    <el-card>
      <div class="top">
        <span class="show-text">摄像头:</span>
        <el-select
          v-model="clickCamera"
          filterable
          placeholder="请选择摄像头"
          style="width: 200px;margin-right: 10px"
          @change="getNowTokenAndRunCheckConnect()">
          <el-option
            v-for="item in CameraList"
            :key="item.deviceSerial"
            :label="item.name"
            :value="item.deviceSerial"
            size="mini"/>
        </el-select>
        <el-button
          icon="el-icon-full-screen"
          size="mini"
          style="width: 100px"
          type="primary"
          @click="fullScreen()">全屏显示
        </el-button>
        <el-button
          icon="el-icon-video-play"
          size="mini"
          style="width: 100px"
          type="success"
          @click="play()">开始播放
        </el-button>
        <el-button
          icon="el-icon-video-pause"
          size="mini"
          style="width: 100px"
          type="warning"
          @click="pause()">暂停播放
        </el-button>
        <el-button
          icon="el-icon-phone-outline"
          size="mini"
          style="width: 100px"
          type="success"
          @click="openSound()">开启声音
        </el-button>
        <el-button
          icon="el-icon-phone"
          size="mini"
          style="width: 100px"
          type="warning"
          @click="closeSound()">关闭声音
        </el-button>
        <!--        <el-button style="width: 200px" @click="getNowTokenAndRunCheckConnect()">【测试用】切换摄像头</el-button>-->
      </div>
      <div class="view">
        <div v-show="UIKitDEMO != null" id="ezuikit-player"/>
        <div v-show="UIKitDEMO == null" id="CameraImg"/>
      </div>
    </el-card>
  </div>
</template>

<script>
import EZUIKit from 'ezuikit-js'
import axios from 'axios'

export default {
  data() {
    return {
      // url: 'ezopen://CAZBSH@open.ys7.com/BC7703777/1.hd.live',
      // accessToken: 'at.cfpiheoj1zs76bij3nkdgyem2j3kdz7y-361phqbj3t-1l86or5-9qt7omao3',
      UIKitDEMO: null,
      CameraList: [],
      clickCamera: '',
      clickCameraRow: null,
      isOpenSound: false, // 是否声音
      isPlay: true, // 开始播放
      time1: null
    }
  },
  mounted() {
    this.getCameraList()
  },
  beforeDestroy() {
    if (this.UIKitDEMO) {
      this.UIKitDEMO.destroy()
    }
    if (this.time1) {
      clearTimeout(this.time1)
    }
  },
  methods: {
    // 查询工位号
    getCameraList() {
      var param = []
      param.push(['Personnel_Number', this.$store.state.user.id])
      var Data = this.CreateData('11', 'WEB_基础_摄像头_查询', param)
      this.ExecDatabase(Data).then(response => {
        this.CameraList = []
        this.CameraList = response.data
        if (this.CameraList.length > 0) {
          this.clickCameraRow = this.CameraList[0]
          this.clickCamera = this.clickCameraRow.deviceSerial
          this.checkConnect()
          // this.createCameraDiv()
        }
      })
    },
    // 根据现有数据检查连接状态
    checkConnect() {
      console.log('---------1111111------clickCameraRow', this.clickCameraRow)
      // 先使用数据库存储的 accessToken 与 deviceSerial 校验是否得到url
      // 如果得到url 调用播放 未 得到 url 重新获取 accessToken 后再次获取url
      axios.post('https://open.ys7.com/api/lapp/v2/live/address/get',
        // 使用 URLSearchParams 对象来编码请求数据
        new URLSearchParams({
          accessToken: this.clickCameraRow.accessToken,
          deviceSerial: this.clickCameraRow.deviceSerial,
          code: this.clickCameraRow.code
        }),
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }).then(res => {
        if (res.data.code == 200) {
          this.url = res.data.data.url
          this.createCameraDiv(res.data.data.url, this.clickCameraRow.accessToken, this.clickCameraRow.deviceSerial)
        } else {
          if (res.data.code == 10002) {
            console.log('【获取播放url】Token失效，自动重新获取~~~~~~~')
            this.getAccessToken()
          } else {
            this.$message.warning('【获取播放url】失败 错误消息：【' + res.data.code + '】' + res.data.msg)
            this.time1 = setTimeout(() => {
              this.checkConnect()
            }, 1000 * 5)
          }
        }
      })
    },
    // 获取工位新Token并连接该工位 用于摄像头change
    getNowTokenAndRunCheckConnect() {
      var param = []
      param[0] = ['deviceSerial', this.clickCamera]
      var Data = this.CreateData('11', 'WEB_基础_摄像头_获取Token', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length !== 0) {
          this.clickCameraRow = response.data[0]
          this.checkConnect()
        }
      })
    },
    getAccessToken() {
      axios.post('https://open.ys7.com/api/lapp/token/get',
        // 使用 URLSearchParams 对象来编码请求数据
        new URLSearchParams({
          appKey: this.clickCameraRow.appKey,
          appSecret: this.clickCameraRow.appSecret
        }),
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }).then(res => {
        if (res.data.code == 200) {
          console.log('新Token获取成功，开始存入~~~~~~')
          // 存储过程存入数据库，将返回的结果重新存入 this.clickCameraRow 重新调用 checkConnect
          var param = []
          param[0] = ['deviceSerial', this.clickCamera]
          param[1] = ['accessToken', res.data.data.accessToken]
          var Data = this.CreateData('11', 'WEB_基础_摄像头_更新Token', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data.length !== 0) {
              this.clickCameraRow = response.data[0]
              this.checkConnect()
            }
          })
        } else {
          if (res.data.code == 10017) {
            this.$message.warning('【appKey】不存在，请联系管理员检查Key是否正确!')
          } else {
            this.$message.warning('获取【accessToken】失败 错误消息：【' + res.data.code + '】' + res.data.msg)
          }
        }
      })
    },
    createCameraDiv(url, accessToken, deviceSerial) {
      // 先判断是否已经存在UIkitDEMO对象了，如果存在则调用切换地址
      if (this.UIKitDEMO) {
        console.log('111111',url, accessToken, deviceSerial)
        this.UIKitDEMO.changePlayUrl({
          url: url,
          accessToken: accessToken,
          deviceSerial: deviceSerial
        })
      } else {
        console.log('222222',url, accessToken, deviceSerial)
        this.UIKitDEMO = new EZUIKit.EZUIKitPlayer({
          id: `ezuikit-player`,
          url: url,
          accessToken: accessToken,
          useHardDev: true, // 开启高性能模式
          height: 755,
          width: 1670,
          quality: 'qp',
          template: 'pcLive',
          handleSuccess: () => {
            console.log('-------------------------------------视频开始播放，调用播放回调-----------------------')
            setTimeout(() => {
              this.UIKitDEMO.closeSound()
            }, 100)
          }
        })
      }
    },
    // 全屏显示
    fullScreen() {
      this.UIKitDEMO.fullScreen()
      this.isPlay = false
    },
    // 暂停播放
    pause() {
      this.UIKitDEMO.pause()
      this.isPlay = false
    },
    // 开始播放
    play() {
      this.UIKitDEMO.play()
      this.isPlay = true
    },
    // 开启声音
    openSound() {
      this.UIKitDEMO.openSound()
      this.isOpenSound = true
    },
    // 关闭声音
    closeSound() {
      this.UIKitDEMO.closeSound()
      this.isOpenSound = false
    }
  }
}
</script>

<style lang="scss" scoped>
.top {
  margin-bottom: 10px;
}

#CameraImg {
  height: 755px;
  width: 1670px;
  background-image: url("/static/CameraImg.png");
  background-size: 100% 100%;
}
</style>

