<template>
  <div
    v-loading="videoLoading"
    class="c-detail"
  >
    <div class="c-detail-header">
      <div class="c-detail-header__name u-ellipsis"> {{ camera.name }}</div>
      <i
        class="c-detail-header__close el-icon-close u-pointer"
        @click="close"
      />
    </div>
    <video
      ref="player"
      class="o-simple-video"
      muted
      autoplay
      controls
      :poster="poster"
    />
    <div class="c-detail-footer has-padding">
      <div class="l-flex--row c-sibling-item--v c-video-controls">
        <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">
          <i
            class="status u-pointer"
            :class="{ stop: !playing }"
            @click="onPlayOrPause"
          />
        </div>
        <i
          class="setting u-pointer"
          @click="onSettings"
        />
        <i
          class="refresh u-pointer"
          @click="onRefresh"
        />
      </div>
      <div class="l-flex c-sibling-item--v far">
        <div class="l-flex__none c-sibling-item c-block c-camera-info">
          <div class="c-sibling-item--v">
            <span class="c-camera-info__title">ID：</span><span>{{ camera.identifier }}</span>
          </div>
          <div class="c-sibling-item--v">
            <span class="c-camera-info__title">用户名：</span><span>{{ camera.username }}</span>
          </div>
          <div class="c-sibling-item--v">
            <span class="c-camera-info__title">备注：</span><span>{{ camera.remark }}</span>
          </div>
        </div>
        <div class="l-flex__auto c-sibling-item far c-block">
          <div
            id="main"
            class="o-canvas"
          />
          <div class="c-choose-date">
            <div class="c-sibling-item c-choose-date__time u-pointer">
              <span
                class="c-choose-date__item"
                :class="{ active: active === 'hour' }"
                @click="onTimeTypeChanged('hour')"
              >
                1小时
              </span>
              <span
                class="c-choose-date__item"
                :class="{ active: active === 'day' }"
                @click="onTimeTypeChanged('day')"
              >
                1天
              </span>
            </div>
            <el-date-picker
              v-model="datevalue"
              class="c-sibling-item far"
              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>
      </div>
    </div>
  </div>
</template>

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

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

export default {
  name: 'CameraDetail',
  props: {
    camera: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      poster: videoPoster,
      datevalue: new Date(),
      active: 'hour', // hour是小时，day是天
      playing: true,
      settingActive: 0,
      setData: ['分辨率', '帧率', '码流'],
      settingData: [[], [], []],
      settingTab: true,
      settingBshow: false,
      echartsData: '',
      player: null,
      availableParam: {},
      infoData: {},
      videoLoading: false,
      settingDatacopy: []
    }
  },
  created () {
    this.getAvailableParam()
  },
  mounted () {
    this.createPlayer()
    this.getStatistic(
      this.getStartTime(new Date(), 'now'),
      this.getStartTime(new Date())
    )
  },
  methods: {
    close () {
      this.destroyPlayer()
      this.$emit('close')
    },
    createPlayer () {
      if (flvjs.isSupported()) {
        // 创建一个flvjs实例
        this.player = flvjs.createPlayer({
          type: 'flv',
          isLive: true,
          // hasAudio: false,
          url: `${CAMERA_URL}/${this.camera.identifier}?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)
        }
      }
    },
    setCamera () {
      setCamera({
        deviceId: this.camera.identifier,
        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.createPlayer()
      })
    },
    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.camera.identifier).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
        }
      }
      const findobj = param.itemList.find(item => `${item.snWidth}*${item.snHight}` === data.withHight)

      this.settingData[1] = this.settingData[1].filter(item => {
        const splceitem = item.value.slice(0, -3)
        return splceitem <= findobj.resolutionFpsMax
      })
      const findData = this.settingData[1].find(item => item.active === true)
      if (!findData) {
        this.infoData.frameRate = 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 => {
        const splceitem = item.value.slice(0, -4)
        return (
          splceitem >= findobj.minBitRateOptions
          && splceitem <= findobj.maxBitRateOptions
        )
      })
    },
    destroyPlayer () {
      this.player.unload()
      this.player.detachMediaElement()
      this.player.destroy()
      this.player = null
    },
    onPlayOrPause () {
      if (this.$refs.player.paused) {
        this.playing = true
        this.player.play()
      } else {
        this.playing = false
        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
      const 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()
      }
    },
    onSettings () {
      this.settingBshow = !this.settingBshow
    },
    onRefresh () {
      this.destroyPlayer()
      this.createPlayer()
    },
    onTimeTypeChanged (type) {
      this.active = type
      let 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) {
      let onehour = 60 * 60 * 1000
      if (type === 'day') {
        onehour = 60 * 60 * 1000 * 24
      } else if (type === 'now') {
        onehour = 0
      }
      const startTime = new Date(new Date(time).getTime() - onehour)
        .toLocaleString('zh', { hour12: false })
        .split('/')
        .join('-')
      const arr = startTime.split(' ')[0].split('-')
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].length < 2) {
          arr[i] = `0${arr[i]}`
        }
      }
      return `${arr.join('-')} ${startTime.split(' ')[1]}`
    },
    getStatistic (endTime, startTime) {
      getStatistic({
        deviceId: this.camera.identifier,
        startTime,
        endTime,
        pageIndex: 1,
        pageSize: 10000
      }).then(({ data }) => {
        this.echartsData = data
        this.initEchart()
      })
    },
    getXData (data) {
      const arr = []
      data.forEach(item => {
        const time = item.eventTime.slice(11, 16)
        arr.push(time)
      })
      return arr
    },
    getYData (data) {
      const arr = []
      data.forEach(item => {
        arr.push(item.insidePeopleNum)
      })
      return arr
    },
    initEchart () {
      const data = this.echartsData.filter(item => item.insidePeopleNum !== 0)
      const xdata = this.getXData(data)
      const ydata = this.getYData(data)
      const chartDom = document.getElementById('main')
      const myChart = echarts.init(chartDom)
      myChart.setOption({
        title: {
          text: '区域内人数',
          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}'
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
$theme-blue: #003e90;

.o-simple-video {
  width: 100%;
  height: 100%;
}

.c-detail {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.c-detail-header {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  padding-top: $spacing;
  color: #fff;
  font-size: 24px;
  text-align: center;
  background-color: rgba($theme-blue, 0.8);
  z-index: 9;

  &::after {
    content: "";
    position: absolute;
    top: 100%;
    left: 50%;
    width: 700px;
    height: 0;
    border-top: 16px solid rgba($theme-blue, 0.8);
    border-right: 16px solid transparent;
    border-bottom: 16px solid transparent;
    border-left: 16px solid transparent;
    transform: translateX(-50%);
  }

  &__name {
    display: inline-block;
    width: 600px;
  }

  &__close {
    position: absolute;
    top: 50%;
    right: 0;
    padding: $spacing;
    color: #fff;
    font-size: 42px;
    transform: translateY(-50%);
  }
}

.c-detail-footer {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
}

.c-block {
  position: relative;
  height: 238px;
  padding: $spacing $spacing 0;
  color: #fff;
  line-height: 1;
  background-color: rgba($theme-blue, 0.8);
}

.c-camera-info {
  width: 25%;

  &__title {
    display: inline-block;
    width: 72px;
  }
}

.c-video-controls {
  position: relative;
  height: 48px;
  border-radius: $radius--mini;
  background-color: rgba(0, 6, 13, 0.75);

  .status {
    display: inline-block;
    width: 30px;
    height: 30px;
    margin-left: 12px;
    background-image: url("~@/assets/icon_stop.png");

    &.stop {
      background-image: url("~@/assets/icon_start.png");
    }
  }

  .setting {
    display: inline-block;
    width: 30px;
    height: 30px;
    margin-right: 50px;
    background-image: url("~@/assets/icon_setting.png");
  }

  .refresh {
    display: inline-block;
    width: 30px;
    height: 30px;
    margin-right: 38px;
    background-image: url("~@/assets/icon_refresh.png");
  }

  .settingB {
    position: absolute;
    padding: 10px 0px;
    background-color: rgba($color: #000000, $alpha: 0.85);
    right: 134px;
    transform: translateX(50%);
    bottom: 48px;
    color: #fff;

    .settingT {
      position: relative;
      padding: 0px 16px;
      width: 180px;
      height: 40px;
      line-height: 40px;
      cursor: pointer;

      &:hover {
        background-color: rgba(69, 69, 69, 0.85);
      }

      i {
        position: absolute;
        top: 13px;
        right: 16px;
      }
    }

    .settingHeight {
      max-height: 250px;
      overflow: auto;
    }

    .settingsub {
      width: 140px;
      padding-left: 42px;
      i {
        position: absolute;
        left: 16px;
      }
    }
  }
}

.c-choose-date {
  position: absolute;
  right: $spacing;
  top: $spacing;

  &__time {
    display: inline-block;
    border-radius: $radius--mini;
    background: #4478bc;
    height: 24px;
    line-height: 24px;
  }

  &__item {
    display: inline-block;
    width: 50px;
    font-size: 14px;
    text-align: center;
    border-radius: $radius--mini;
    background-color: #4478bc;

    &.active {
      background: #0096ff;
    }
  }

  ::v-deep input {
    height: 24px;
    color: #fff;
    font-size: 14px;
    line-height: 24px;
    background-color: transparent;
  }

  ::v-deep .el-input__icon {
    line-height: 24px;
  }
}

.o-canvas {
  width: 100%;
  height: 200px;
}
</style>
