<template>
  <div
    class="o-video"
    :class="{ offline: !online, mask: !isPlaying, controls }"
  >
    <template v-if="online">
      <video
        ref="video"
        class="o-video__player o-simple-video"
        :poster="poster"
        autoplay
        muted
        @play="onVideoPlay"
        @pause="onVideoPause"
        @waiting="onVideoWaiting"
        @playing="onVideoPlaying"
        @error="onVideoError"
        @ended="onVideoEnded"
      />
      <div class="o-video__mask">
        <div
          class="l-flex--row center o-video__btn u-pointer"
          @click.stop="onPlayOrPause"
        >
          <i :class="statusIconClass" />
        </div>
      </div>
    </template>
    <div
      v-else
      class="o-video__tag"
    />
    <div
      v-if="controls"
      class="l-flex--row c-footer"
    >
      <div class="l-flex__fill c-sibling-item u-ellipsis">{{ device.name }}</div>
      <template v-if="recordConfig">
        <i
          v-if="loadingQuality"
          class="c-sibling-item el-icon-loading"
        />
        <div
          v-else
          class="l-flex__none c-sibling-item o-quality-menu u-pointer"
          @click.stop="toggleQualityMenu"
        >
          <div
            v-if="showQualityMenu"
            class="o-quality-menu__list"
          >
            <div
              v-for="item in qualities"
              :key="item.value"
              class="o-quality-menu__item u-pointer"
              :class="{ active: quality.value === item.value }"
              @click="changeQuality(item)"
            >
              {{ item.label }}
            </div>
          </div>
          <span class="has-active">{{ quality.label }}</span>
        </div>
        <i
          class="c-sibling-item el-icon-full-screen has-active u-pointer"
          @click="onFullScreen"
        />
      </template>
    </div>
  </div>
</template>

<script>
import {
  authCode,
  getRecordConfig,
  addRecordConfig,
  updateRecordConfig
} from '@/api/device'
import { GATEWAY } from '@/constant'
import playerMixin from '../player'

const Quality = {
  fff: {
    videoWidth: 640,
    videoHeight: 360,
    videoBitRate: 36 * 1024,
    frameRate: 1
  },
  ff: {
    videoWidth: 1280,
    videoHeight: 720,
    videoBitRate: 100 * 1024,
    frameRate: 10
  },
  f: {
    videoWidth: 1920,
    videoHeight: 1080,
    videoBitRate: 1024 * 1024,
    frameRate: 20
  }
}

export default {
  name: 'DevicePlayer',
  mixins: [playerMixin],
  props: {
    device: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      qualities: [
        { value: 'fff', label: '标清' },
        { value: 'ff', label: '高清' },
        { value: 'f', label: '超清' }
      ],
      loadingQuality: false,
      showQualityMenu: false,
      quality: null,
      recordConfig: null
    }
  },
  computed: {
    online () {
      return this.device.activate === 2 && this.device.onlineStatus === 1
    }
  },
  watch: {
    online (val) {
      if (val) {
        this.$nextTick(this.createPlayer)
      } else {
        this.hideQualityMenu()
        this.destroyPlayer()
        this.recordConfig = null
        this.$playerInfo = null
      }
    }
  },
  created () {
    this.$timer = -1
    if (this.online) {
      this.createPlayer()
    }
  },
  beforeDestroy () {
    this.hideQualityMenu()
  },
  methods: {
    onVideoEnded () {
      console.log('Device onVideoEnded')
      this.destroyPlayer()
      this.recordConfig = null
      this.$playerInfo = null
      this.createPlayer()
    },
    getRecordConfig () {
      this.loadingQuality = true
      getRecordConfig(this.device.id, { custom: true }).finally(() => {
        this.loadingQuality = false
      }).then(
        ({ data }) => {
          if (data) {
            const { frameRate } = data
            const key = Object.keys(Quality).find(key => Quality[key].frameRate === frameRate) || 'fff'
            this.quality = this.qualities.find(({ value }) => value === key) || this.qualities[0]
            this.recordConfig = data
            this.createPlayer()
          } else {
            this.setRecordConfig(this.qualities[0])
          }
        },
        () => {
          this.destroyPlayer()
        }
      )
    },
    setRecordConfig (quality) {
      this.loadingQuality = true
      ;(this.recordConfig ? updateRecordConfig : addRecordConfig)({
        deviceId: this.device.id,
        ...Quality[quality.value]
      }, { custom: true }).then(
        ({ data }) => {
          this.quality = quality
          this.recordConfig = data
          this.createPlayer()
        },
        () => {
          this.destroyPlayer()
        }
      ).finally(() => {
        this.loadingQuality = false
      })
    },
    hideQualityMenu () {
      if (this.showQualityMenu) {
        this.showQualityMenu = false
        document.removeEventListener('click', this.hideQualityMenu)
      }
    },
    toggleQualityMenu () {
      if (this.showQualityMenu) {
        this.hideQualityMenu()
      } else {
        document.addEventListener('click', this.hideQualityMenu)
        this.showQualityMenu = true
      }
    },
    changeQuality (quality) {
      if (this.quality.value !== quality.value) {
        this.$playerInfo = null
        this.setRecordConfig(quality)
      } else if (this.needReset) {
        this.createPlayer()
      }
    },
    getAuthCode () {
      this.$playerInfo = null
      authCode(this.recordConfig.stream).then(
        ({ data }) => {
          if (this.$timer !== null) {
            this.$playerInfo = data
            this.createPlayer()
          }
        },
        () => {
          this.destroyPlayer()
        }
      )
    },
    createPlayer () {
      if (this.$timer === null) {
        return
      }
      this.loading = true
      clearTimeout(this.$timer)
      if (!this.recordConfig) {
        this.getRecordConfig()
        return
      }
      if (!this.$playerInfo) {
        this.getAuthCode()
        return
      }
      const { vhost = '__defaultVhost__', token, timestamp, expire } = this.$playerInfo
      if (Number(timestamp) + Number(expire) * 1000 <= Date.now()) {
        this.getAuthCode()
        return
      }
      this.destroyPlayer()
      this.playUrl(`${GATEWAY}/live/${this.recordConfig.stream}.flv?vhost=${vhost}&authorization=${token}&timestamp=${timestamp}&expire=${expire}`)
    }
  }
}
</script>

<style lang="scss" scoped>
.o-quality-menu {
  display: inline-block;
  position: relative;
  padding: 0 6px;
  z-index: 1;

  &__list {
    position: absolute;
    right: 0;
    bottom: 100%;
    margin-bottom: 6px;
    width: 100%;
    font-size: 14px;
    text-align: center;
    border-radius: $radius;
    background-color: rgba(#000, 0.85);
    z-index: -1;
  }

  &__item {
    padding: 4px 0;
    color: #fff;

    &.active {
      color: $success;
    }

    &:hover {
      color: $primary;
    }
  }
}
</style>
