<template>
  <div
    v-loading="videoLoading"
    class="detail"
  >
    <i
      class="el-icon-close closeDetail"
      @click="close"
    />
    <video
      ref="player"
      style="width: 100%"
      class="video"
      muted
      autoplay
      :poster="require('@/assets//video-post.png')"
    />
    <div class="detail-buttom">
      <el-row :gutter="16">
        <el-col :span="24">
          <div class="video-controls l-flex--row">
            <div
              v-show="settingBshow"
              class="settingB"
            >
              <div v-show="settingTab">
                <div
                  v-for="(item, index) in setData"
                  :key="index"
                  class="settingT"
                  @click="setClick(index)"
                >
                  {{ item }} <i class="el-icon-arrow-right" />
                </div>
              </div>
              <div v-show="!settingTab">
                <div
                  class="settingT settingsub"
                  @click="setBack"
                >
                  <i class="el-icon-arrow-left" />{{ setData[settingActive] }}
                </div>
                <div class="settingHeight">
                  <div
                    v-for="(item, index) in settingData[settingActive]"
                    :key="index"
                    class="settingT settingsub"
                    @click="settingClick(index)"
                  >
                    <i :class="{ 'el-icon-check': item.active }" />
                    {{ item.value }}
                  </div>
                </div>
              </div>
            </div>
            <div class="l-flex__auto">
              <img
                :src="imgUrl.stop"
                class="stop"
                @click="stopbtn"
              >
            </div>
            <img
              :src="imgUrl.setting"
              class="setting"
              @click="settingShow"
            >
            <img
              :src="imgUrl.refresh"
              class="refresh"
              @click="refresh"
            >
          </div>
        </el-col>
        <el-col :span="8">
          <div class="o-detail">
            <div>
              <span class="o-detail_title">设备名称：</span><span>{{ detailobj.name }}</span>
            </div>
            <div>
              <span class="o-detail_title">ID：</span><span>{{ detailobj.id }}</span>
            </div>
            <div>
              <span class="o-detail_title">用户名：</span><span>{{ detailobj.username }}</span>
            </div>
            <div>
              <span class="o-detail_title">备注：</span><span>{{ detailobj.remark }}</span>
            </div>
          </div>
        </el-col>
        <el-col :span="16">
          <div class="o-detail">
            <div
              id="main"
              style="width: 100%; height: 200px"
            />
            <div class="choosedate">
              <div class="timeBtn">
                <span
                  :class="{ active: active === 'hour' }"
                  @click="timeType('hour')"
                >1小时</span>
                <span
                  :class="{ active: active === 'day' }"
                  @click="timeType('day')"
                >1天</span>
              </div>
              <el-date-picker
                v-model="datevalue"
                type="datetime"
                placeholder="选择日期时间"
                prefix-icon="el-icon-date"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="onDateTimeChange()"
              />
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import flvjs from 'flv.js'
import * as echarts from 'echarts'
import {
  getStatistic,
  getVideoinfo,
  getAvailableParam,
  setCamera
} from '@/api/camera'

const CAMERA_URL = `${location.protocol === 'https:' ? 'wss' : 'ws'}://${process.env.VUE_APP_GATEWAY || location.host}${process.env.VUE_APP_CAMERA_PROXY}`

export default {
  name: 'Detail',
  props: {
    detailobj: {
      type: Object,
      default () {
        return {}
      }
    }
    // ['']
  },
  data () {
    return {
      datevalue: new Date(),
      active: 'hour', // hour是小时，day是天
      imgUrl: {
        setting: require('@/assets/icon_setting.png'),
        stop: require('@/assets/icon_stop.png'),
        start: require('@/assets/icon_start.png'),
        refresh: require('@/assets/icon_refresh.png')
      },
      settingActive: 0,
      setData: ['分辨率', '帧率', '码流'],
      settingData: [[], [], []],
      settingTab: true,
      settingBshow: false,
      echartsData: '',
      player: null,
      availableParam: {},
      infoData: {},
      videoLoading: false,
      settingDatacopy: []
    }
  },
  created () {
    this.getAvailableParam()
  },
  mounted () {
    this.getflv()
    this.getStatistic(
      this.getStarttime(new Date(), 'now'),
      this.getStarttime(new Date())
    )
  },

  methods: {
    close () {
      this.destroyPlayer()
      this.$emit('closeDetail')
    },
    getflv () {
      if (flvjs.isSupported()) {
        // 创建一个flvjs实例
        this.player = flvjs.createPlayer({
          type: 'flv',
          isLive: true,
          // hasAudio: false,
          url: `${CAMERA_URL}/${this.detailobj.deviceId}?authorization=${this.$keycloak.token}`
        })

        this.player.on('error', (e) => {
          console.log(e)
        })
        // 将实例挂载到video元素上面
        this.player.attachMediaElement(this.$refs.player)

        try {
          // 开始运行加载 只要流地址正常 就可以在h5页面中播放出画面了
          this.player.load()
          this.player.play()
          this.videoLoading = false
        } catch (error) {
          console.log('连接websocker异常：' + error)
          return false
        }
      }
    },
    setCamera () {
      setCamera({
        deviceId: this.detailobj.deviceId,
        width: this.infoData.withHight.split('*')[0],
        hight: this.infoData.withHight.split('*')[1],
        bitRate: this.infoData.bitRate.slice(0, -4),
        frameRate: this.infoData.frameRate.slice(0, -3)
      }).then(() => {
        this.destroyPlayer()
        this.getflv()
      })
    },
    getAvailableParam () {
      getAvailableParam().then(({ data }) => {
        data.itemList.forEach((item) => {
          this.settingData[0].push({
            value: item.snWidth + '*' + item.snHight,
            active: false
          })
        })
        for (let i = 1; i < 26; i++) {
          this.settingData[1].push({ value: i + 'fps', active: false })
          this.settingDatacopy.push({ value: i + 'fps', active: false })
        }
        data.streamRateTypeList.forEach((item) => {
          this.settingData[2].push({ value: item + 'kb/s', active: false })
        })
        this.availableParam = data
        this.getVideoinfo(data)
      })
    },
    getVideoinfo (param) {
      getVideoinfo(this.detailobj.deviceId).then(({ data }) => {
        this.infoData = {
          withHight: data.width + '*' + data.hight,
          frameRate: data.frameRate + 'fps',
          bitRate: data.bitRate + 'kb/s'
        }
        this.dataInit(param, this.infoData)
      })
    },
    dataInit (param, data) {
      for (let i = 0; i < this.settingData[0].length; i++) {
        if (this.settingData[0][i].value === data.withHight) {
          this.settingData[0][i].active = true
        }
      }
      this.settingData[1] = this.settingDatacopy
      for (let i = 0; i < this.settingData[1].length; i++) {
        if (this.settingData[1][i].value === data.frameRate) {
          this.settingData[1][i].active = true
        } else {
          this.settingData[1][i].active = false
        }
      }
      for (let i = 0; i < this.settingData[2].length; i++) {
        if (this.settingData[2][i].value === data.bitRate) {
          this.settingData[2][i].active = true
        }
      }
      var findobj = param.itemList.find((item) => {
        return item.snWidth + '*' + item.snHight === data.withHight
      })

      this.settingData[1] = this.settingData[1].filter((item) => {
        var splceitem = item.value.slice(0, -3)
        return splceitem <= findobj.resolutionFpsMax
      })
      var findData = this.settingData[1].find((item) => {
        return item.active === true
      })
      this.infoData.frameRate = findData ? this.infoData.frameRate : (this.settingData[1].length + 'fps')
      if (!findData) {
        this.infoData.frameRate = this.settingData[1].length + 'fps'
        this.settingData[1][this.settingData[1].length].active = true
      }
      // this.settingData[1][this.settingData[1].length].value = this.infoData.frameRate

      this.settingData[2] = this.settingData[2].filter((item) => {
        var splceitem = item.value.slice(0, -4)
        return (
          splceitem >= findobj.minBitRateOptions &&
          splceitem <= findobj.maxBitRateOptions
        )
      })
    },
    destroyPlayer () {
      // this.player.pause();
      this.player.unload()
      this.player.detachMediaElement()
      this.player.destroy()
      this.player = null
    },
    stopbtn () {
      if (this.imgUrl.stop === this.imgUrl.start) {
        this.imgUrl.stop = require('@/assets/icon_stop.png')
        this.player.play()
      } else {
        this.imgUrl.stop = this.imgUrl.start
        this.player.pause()
      }
    },
    setClick (index) {
      this.settingActive = index
      this.settingTab = !this.settingTab
    },
    setBack () {
      this.settingTab = !this.settingTab
    },
    settingClick (index) {
      this.settingData[this.settingActive].forEach((element) => {
        element.active = false
      })
      this.settingData[this.settingActive][index].active = !this.settingData[this.settingActive][index].active
      var arr = JSON.stringify(this.infoData)
      // console.log(this.settingData)
      if (this.settingActive === 0) {
        if (
          this.infoData.withHight !==
          this.settingData[this.settingActive][index].value
        ) {
          this.infoData.withHight =
            this.settingData[this.settingActive][index].value
          this.dataInit(this.availableParam, this.infoData)
        }
      } else if (this.settingActive === 1) {
        this.infoData.frameRate =
          this.settingData[this.settingActive][index].value
      } else if (this.settingActive === 2) {
        this.infoData.bitRate =
          this.settingData[this.settingActive][index].value
      }
      if (!(arr === JSON.stringify(this.infoData))) {
        this.setCamera()
      }
      // console.log(this.infoData)
    },
    settingShow () {
      this.settingBshow = !this.settingBshow
    },
    refresh () {
      this.destroyPlayer()
      this.getflv()
    },
    timeType (type) {
      this.active = type
      var startTime
      if (this.datevalue.length) {
        startTime = this.datevalue
      } else {
        this.datevalue = new Date()
        startTime = this.getStarttime(new Date(), 'now')
      }
      this.getStatistic(startTime, this.getStarttime(startTime, type))
    },
    onDateTimeChange () {
      if (this.datevalue) {
        this.getStatistic(this.datevalue, this.getStarttime(this.datevalue, this.active))
      }
    },
    getStarttime (time, type) {
      var time1 = new Date(time)
      time1 = time1.getTime() // 转换为时间戳
      var onehour = 60 * 60 * 1000
      if (type === 'day') {
        onehour = 60 * 60 * 1000 * 24
      } else if (type === 'now') {
        onehour = 0
      }
      var startTime = time1 - onehour
      startTime = new Date(startTime).toLocaleString()
      startTime = startTime.split('/').join('-')
      var arr = startTime.split(' ')[0].split('-')
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].length < 2) {
          arr[i] = '0' + arr[i]
        }
      }
      startTime = arr.join('-') + ' ' + startTime.split(' ')[1]
      return startTime
    },
    getStatistic (endTime, startTime) {
      getStatistic({
        deviceId: this.detailobj.deviceId,
        startTime: startTime,
        endTime: endTime,
        pageIndex: 1,
        pageSize: 10000
      }).then(({ data }) => {
        this.echartsData = data
        this.initEchart()
      })
    },
    getxdata (data) {
      var arr = []
      data.forEach((item) => {
        var time = item.eventTime.slice(11, 16)
        arr.push(time)
      })
      return arr
    },
    getydata (data) {
      var arr = []
      data.forEach((item) => {
        arr.push(item.insidePeopleNum)
      })
      return arr
    },
    initEchart () {
      var data = this.echartsData
      data = data.filter((item) => {
        return item.insidePeopleNum !== 0
      })
      var xdata = this.getxdata(data)
      var ydata = this.getydata(data)
      var chartDom = document.getElementById('main')
      var myChart = echarts.init(chartDom)
      var option
      option = {
        title: {
          text: '123',
          textStyle: {
            color: '#fff',
            fontWeight: 'bold'
          }
          // padding: [0, 30],
        },
        xAxis: {
          type: 'category',
          data: xdata,
          splitLine: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: '#4779BC'
            }
          },
          axisLabel: {
            color: '#A9CEFF'
          }
        },
        yAxis: {
          type: 'value',
          minInterval: 1,
          splitLine: {
            lineStyle: {
              color: '#4779BC',
              type: 'dashed'
            }
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#4779BC'
            }
          },
          axisLabel: {
            color: '#A9CEFF'
          }
        },
        grid: {
          left: '30',
          right: '20',
          top: '40',
          bottom: '20'
        },
        series: [
          {
            data: ydata,
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'transparent'
            },
            itemStyle: {
              color: 'rgba(0, 191, 208, 0.5)'
            },
            select: {
              itemStyle: {
                color: 'rgb(0, 234, 255)'
              }
            }
          }
        ],
        tooltip: {
          formatter: '{b}<br />{c}'
        }
      }
      option && myChart.setOption(option)
    }
  }
}
</script>

<style lang="scss" scoped>
.detail {
  width: 100%;
  height: 100%;
  position: relative;
  .closeDetail {
    position: absolute;
    right: 20px;
    top: 20px;
    cursor: pointer;
    z-index: 2;
    font-size: 42px;
    color: #000000;
  }
  .video {
    width: 100%;
    height: 100vh;
    object-fit: contain;
  }
  .detail-buttom {
    position: absolute;
    bottom: 0;
    width: 100%;
    left: 0;
    padding: 16px;
    .o-detail {
      padding: 24px 24px 70px;
      background-color: rgba(0, 62, 144, 0.8);
      color: #fff;
      line-height: 36px;
      height: 238px;
      position: relative;
      &_title {
        width: 72px;
        display: inline-block;
        border-radius: 4px;
      }
      .choosedate {
        position: absolute;
        right: 20px;
        top: 10px;
        .timeBtn {
          display: inline-block;
          border-radius: 4px;
          background: #4478bc;
          height: 24px;
          line-height: 24px;
          margin-right: 16px;

          span {
            font-size: 14px;
            background: #4478bc;
            border-radius: 4px;
            padding: 0 7px;
            display: inline-block;
            cursor: pointer;
            width: 50px;
            text-align: center;
          }
          .active {
            background: #0096ff;
          }
        }
      }
    }
    .video-controls {
      background-color: rgba(0, 6, 13, 0.75);
      height: 48px;
      border-radius: 4px;
      margin-bottom: 16px;
      position: relative;
      img {
        cursor: pointer;
      }
      .stop {
        margin-left: 12px;
      }
      .setting {
        margin-right: 50px;
      }
      .refresh {
        margin-right: 38px;
      }
      .settingB {
        position: absolute;
        padding: 10px 0px;
        background-color: rgba($color: #000000, $alpha: 0.85);
        right: 134px;
        transform: translateX(50%);
        bottom: 48px;
        color: #fff;
        .settingT {
          padding: 0px 16px;
          height: 40px;
          line-height: 40px;
          width: 180px;
          cursor: pointer;
          position: relative;
          &:hover {
            background-color: rgba(69, 69, 69, 0.85);
          }
          i {
            position: absolute;
            right: 16px;
            top: 13px;
          }
        }
        .settingHeight {
          max-height: 250px;
          overflow: auto;
        }
        .settingsub {
          width: 140px;
          padding-left: 42px;
          i {
            position: absolute;
            left: 16px;
          }
        }
      }
    }
  }
}

video::-webkit-media-controls-fullscreen-button {
  display: none;
}
//所有控件
video::-webkit-media-controls-enclosure {
  display: none;
}
</style>
<style lang="scss">
.choosedate {
  input {
    background-color: transparent;
    height: 24px;
    line-height: 24px;
    font-size: 14px;
    color: #fff;
    // padding: 0 10px !important;
  }
  .el-input__prefix {
    top: -2px;
  }
}
</style>
