<template>
  <view>
    <view class="status_bar">
      <div class="item" @click="goBack">
        <u-icon name="arrow-left"></u-icon>
      </div>
      <div class="item">视频监控</div>
      <div class="item"></div>
    </view>
    <!-- 视频监控 -->
    <div class="video">
      <video v-if="type === 0" id="videoPlayer" ref="videoPlayer" class="video-player" autoplay controls="controls"
             @click="checkVideo(1)" />
      <video
        v-if="type === 1"
        id="myVideo"
        ref="myVideo"
        src="https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/wap2appvsnative.mp4"
        controls
      ></video>
    </div>
    <div class="action">
      <u-tabs
        :list="tabList"
        @click="clickTab"
        :current="currentIndex"
        :activeStyle="{ fontWeight: 500, fontSize: '14px', color: '#0F274B' }"
        :inactiveStyle="{ fontWeight: 400, fontSize: '12px', color: 'rgba(15, 39, 75, 0.5)' }"
      />
      <div class="action-item">
        <div class="top" @click="handleCloud('top')">
          <u-icon name="arrow-up"></u-icon>
        </div>
        <div class="center">
          <div class="w-h" @click="handleCloud('left')">
            <u-icon name="arrow-left"></u-icon>
          </div>
          <div class="w-h circle" @click="handleCloud('center')"></div>
          <div class="w-h">
            <u-icon name="arrow-right" @click="handleCloud('right')"></u-icon>
          </div>
        </div>
        <div class="bottom" @click="handleCloud('bottom')">
          <u-icon name="arrow-down"></u-icon>
        </div>
      </div>
    </div>
    <!-- 底部操作栏 -->
    <u-tabbar :fixed="true" :placeholder="false" activeColor="">
      <u-tabbar-item text="拍照" icon="/static/images/imgs/film.png" @click="clickTabItem(1)"></u-tabbar-item>
      <u-tabbar-item text="全屏" icon="/static/images/imgs/full-screen.png" @click="clickTabItem(2)"></u-tabbar-item>
      <div class="talk-back" @click="clickTabItem(3)">
        <u-icon name="/static/images/imgs/talkback.png"></u-icon>
      </div>
      <u-tabbar-item text="放大" icon="/static/images/imgs/enlargement.png" @click="clickTabItem(4)"></u-tabbar-item>
      <u-tabbar-item text="缩小" icon="/static/images/imgs/lessen.png" @click="clickTabItem(5)"></u-tabbar-item>
    </u-tabbar>
  </view>
</template>

<script>
// import FlvJs from 'flv.js'
import CryptoJS from 'crypto-js'
let _cf = {
  ver: 'debug',
  q2http_url: 'http://112.31.70.193:1854/icvs/',
  websocket_url: 'ws://112.31.70.193:9580/wss',
  // - 配置登录参数
  connParams: {
    // - 登录平台IP
    address: '112.31.70.193',
    port: '9988',
    // - 登录平台用户名
    user: 'bns3',
    // - 登录平台密码
    password: 'Bns@admin**',
    // - 登录平台企业ID
    epid: 'system',
    // - 登录平台是否通过网闸模式
    bfix: 1
  }
}
var loginToken = ''
var puId = ''
export default {
  data() {
    return {
      type: 0,
      tabBarValue: 0,
      currentIndex: 0,
      tabList: [{ name: '实时视频' }, { name: '历史录像' }],
      video: null,
      isPlaying: false,
      // 视频播放实例
      videoPlayer: null,
      classStyle: 'ball-content'
    }
  },
  async mounted() {
    console.log('------mounted')
    this.connect()
    console.log('loginToken', loginToken)
    setTimeout(() => {
      console.log('loginToken', loginToken)
      this.initVideo('201115203294827151')
    }, 500)
  },
  methods: {
    goBack() {
      if (getCurrentPages().length == 1) {
        this.$tab.reLaunch('/pages/index')
      } else {
        uni.navigateBack()
      }
    },
    changeTabBar(value) {
      console.log('changeTabBar', value)
      this.tabBarValue = value
    },
    clickTab(val) {
      this.currentIndex = val.index
      console.log('clickTab', val, this.currentIndex)
    },
    clickTabItem(val) {
      console.log('clickTabItem', val)
      // val 1 拍照 2 全屏 3 对讲 4 放大 5 缩小
      // val = 2 全屏播放视频
      if (val === 2) {
        this.video.requestFullScreen()
      }
    },
    handleCloud(val) {
      console.log('handleCloud', val)
      // val top 上 left 左 center 中 right 右 bottom 下
      if (val === 'center') {
        if (this.isPlaying) {
          this.video.pause()
        } else {
          this.video.play()
        }
        this.isPlaying = !this.isPlaying
      }
    },


    checkVideo(index) {
      console.log(index)
    },
//加密
    videoEncrypt(word) {
      var key = CryptoJS.enc.Utf8.parse('297796CCB81D2553')
      var srcs = CryptoJS.enc.Utf8.parse(word)
      var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
      return encrypted.toString()
    },
    // 请求
    requestPost(router, params, callback) {
      uni.request({
        method: 'post',
        url: _cf.q2http_url + router,
        data: params,
        dataType: 'json',
        async: false,
        complete: function(rv) {
          if (typeof callback == 'function') callback(rv)
        }
      })


      // $.ajax({
      //   type: 'post',
      //   url: _cf.q2http_url + router,
      //   data: params,
      //   traditional: true,
      //   dataType: 'json',
      //   async: false,
      //   complete: function (rv) {
      //     if (typeof callback == 'function') callback(rv)
      //   }
      // })
    },
    //连接
    connect() {
      console.log('connect')
      var allDataParams = 'address=' + _cf.connParams.address + '&port=' + _cf.connParams.port +
        '&user=' + _cf.connParams.user + '&password=' + _cf.connParams.password + '&epid=' + _cf.connParams.epid + '&fixaddr=' + _cf.connParams.bfix
      let params = {
        'params': this.videoEncrypt(allDataParams)
      }
      // console.log(params)
      this.requestPost('login2', params, function(rv) {
        console.log('rv=============', rv)
        console.log('rv.data=============', rv.data)
        console.log('rv.statusCode=============', rv.statusCode)

        let result = {
          errcode: -1,
          token: ''
        }
        // let respJSON = JSON.parse(rv.responseText);
        // console.log("respJSON=============",respJSON)
        if (rv.hasOwnProperty('errcode')) {
          result.errcode = rv.errcode
        } else if (rv.hasOwnProperty('statusCode')) {
          result.token = rv.data.token
          result.errcode = 0
          loginToken = result.token//获取Token
          console.log('loginToken', loginToken)
        }
        // if (rv.hasOwnProperty('token')) {
        //   result.token = respJSON.token;
        //   result.errcode = 0;
        //   loginToken = result.token;//获取Token
        // }
      })
    },
    // 初始化视频监控
    initVideo(devId) {
      puId = devId
      console.log('=============intiVideo')
      console.log(puId)
      console.log(loginToken)
      this.$nextTick(() => {
        const videoElement = this.$refs.videoPlayer
        const url = `${_cf.q2http_url}/stream.flv?puid=${puId}&idx=0&stream=0&token=${loginToken}`
        console.log('url', url)
        try {
          this.videoPlayer = FlvJs.createPlayer({
            type: 'flv',
            url: url,
            isLive: true,
            hasAudio: false
          }, {
            enableWorker: true,
            enableStashBuffer: true,
          })
          this.videoPlayer.attachMediaElement(videoElement)
          this.videoPlayer.load()

          setTimeout(() => {
            this.videoPlayer.play()
          }, 200)
        } catch (err) {
          console.log(err)
        }
      })
    },
    // 销毁视频监控
    closeVideo() {
      if (this.videoPlayer) {
        // this.videoPlayer.pause()
        this.videoPlayer.unload()
        this.videoPlayer.detachMediaElement()
        this.videoPlayer.destroy()
      }
    }
  }
}
</script>

<style lang="scss">
.status_bar_placeholder {
  height: 105px;
  width: 100%;
}

.status_bar {
  padding: 0 25px;
  width: 100%;
  height: 106px;
  border: 0;
  background-color: transparent;
  position: fixed;
  z-index: 99;
  display: flex;
  justify-content: center;
  flex-direction: space-between;
  align-items: center;
  font-weight: 500;
  font-size: 16px;
  color: #0f274b;

  .item {
    width: 33%;
    text-align: center;
    color: #fff;
  }
}

.video {
  height: 60vh;
  background-color: #d9d9d9;

  /deep/ uni-video {
    width: 100%;
    height: 98%;
    // z-index: 1;
  }
}

.action {
  height: 350px;
  transform: translateY(-10px);
  background-color: #fff;
  border-radius: 12px 12px 0px 0px;
  z-index: 9 !important;

  .action-item {
    margin: 0 auto;
    width: 220px;
    height: 220px;
    background: url('/static/images/imgs/bg-3.png');
    background-size: 100% 100%;

    // 统一宽高
    .w-h {
      width: 52px;
      height: 52px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .top,
    .bottom {
      width: 52px;
      height: 52px;
      margin: 0 auto;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .center {
      display: flex;
      justify-content: space-between;
      align-items: center;
      transform: translateY(60%);

      .circle {
        width: 52px;
        height: 52px;
        border-radius: 50%;
        background: linear-gradient(180deg, #8ebcff 0%, #3888ff 100%);
        box-shadow: 0px 2px 7px 0px rgba(56, 136, 255, 0.5);
      }
    }

    .bottom {
      transform: translateY(130%);
    }
  }
}

.talk-back {
  width: 52px;
  height: 52px;
  background: linear-gradient(180deg, #8ebcff 0%, #3888ff 100%);
  box-shadow: 0px 2px 7px 0px rgba(56, 136, 255, 0.5);
  border-radius: 50%;
  transform: translateY(-50%);
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
