<template>
  <div class="wrapper">
    <div id="mps" ref="mps" @click.stop="showD" style="height: calc(9 / 16 * 100vw)">
      <div class="mpstitle-name">{{ channelInfo.channelName }}</div>
      <div class="videoPlayer" id="videoPlayer" :style="{pointerEvents: (drainage.drainage_status === 0 || count || !(drainage.drainage_model || []).includes('0')) ? 'all' : 'none'}">
        <div style="display:none;">
          <video></video>
        </div>
      </div>
    </div>
    <mark-box></mark-box>
    <watch-state v-show="controlShow"></watch-state>
    <div v-show="!isFullScreen">
      <div class="time-watch-chat" :style="{opacity : controlShow ? '1' : '.5'}">
        <down-time v-if="isDownTime"></down-time>
        <watch-chat v-show="isWatchChat"></watch-chat>
      </div>
      <div class="more-box">
        <more-box :mps="mpsPlayerObj"></more-box>
      </div>
    </div>
  </div>
</template>
<script>
import { traffic } from '@/plugins/openTraffic';
import { getAddressForGet } from '@/plugins/API/apiAll';
import { mapGetters, mapMutations } from 'vuex';
import watermark from '@/plugins/watermark';
import markBox from './mark';
import downTime from './downTime';
import watchChat from './watch-chat';
import moreBox from './more';
import watchState from './watch-state';
export default {
  name: 'player-box',
  components: {
    markBox,
    downTime,
    watchChat,
    moreBox,
    watchState
  },
  data() {
    return {
      mpsPlayerObj: null,
      onePlayer: true, // 切换自动播放问题
      isFullScreen: false,
      count: 0,
      controlShow: true,
    };
  },
  computed: {
    ...mapGetters({
      nowDate: 'nowDate',
      userInfo: 'userInfo',
      channelInfo: 'channelInfo',
      drainage: 'drainage',
      channelConfig: 'channelConfig',
      playerInfo: 'playerInfo'
    }),
    isPeep() {
      const peep = this.channelConfig.peep || {};
      return !!peep.isEnable;
    },
    isDownTime() {
      return (
        this.channelInfo.liveStatus === 0 &&
        this.channelInfo.countdownStatus === 1 &&
        this.channelInfo.liveBegin > this.nowDate / 1000
      );
    },
    isWatchChat() {
      return this.channelInfo.isDisplayWatchNum === 1 || this.channelInfo.chatCountStatus === 1;
    },
    isControl() {
      if (this.playerInfo.playUrl !== this.playerInfo.saveUrl) {
        return true;
      }
      if (this.channelInfo.liveStatus === 1) {
        return true;
      }
      if (this.channelInfo.vodUrl && this.channelInfo.vodStatus) {
        return true;
      }
      return false;
    },
    mpsBackgroundUrl() {
      const bgUrl = this.channelInfo.mpsBackgroundUrl;
      return bgUrl ? `${bgUrl}${process.env.private ? '' : '?x-oss-process=style/twzb_origin'}` : '';
    },
    mpsOptions() {
      let options = {};
      if (this.channelInfo.hlsPwdStatus === 1) {
        options = {
          crypUrl: getAddressForGet(),
          cryptBeforeSendFn: function(XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader('X-Ca-Stage', process.env.X_CA_STAGE);
          },
          cryptUrlType: 'get',
          iv: '1152922081067', // 偏移量
          sendKey: { channelId: this.channelInfo.id }, // 验证参数
          crymode: 'CBC' // 默认CBC
        };
      } else {
        options = {
          hlsUrl: this.channelInfo.livePlayHlsUrl
        };
      }
      return options;
    },
    playerUrl() {
      let playUrl = '';
      let saveUrl = '';
      if (this.channelInfo.liveStatus === 1) {
        playUrl = this.channelInfo.livePlayHlsUrl;
        saveUrl = this.channelInfo.livePlayHlsUrl;
      } else if (this.channelInfo.vodUrl && this.channelInfo.vodStatus) {
        playUrl = this.channelInfo.vodUrl;
        saveUrl = this.channelInfo.vodUrl;
      } else {
        playUrl = 'http://';
        saveUrl = 'http://';
      }
      return {
        playUrl,
        saveUrl
      }
    }
  },
  mounted() {
    this.watermark();
    this.$nextTick(() => {
      const { playUrl } = this.playerUrl
      this._mpsPlayerInit({
        isVr: this.channelInfo.isVr,
        url: playUrl
      });
    });
  },
  methods: {
    ...mapMutations({
      set_playerInfo: 'set_playerInfo'
    }),
    showD() {
      const drainage = this.drainage
      if (drainage.drainage_status === 1){
        if (!(drainage.drainage_model || []).includes('0')) {
         return
        }
        // eslint-disable-next-line no-undef 
        !this.count && traffic(drainage)
        drainage.drainage_type !== 0 && this.count++
      }
    },
    watermark() {
      if (this.isPeep && this.userInfo.id) {
        watermark(`id: ${this.userInfo.id}`);
      }
    },
    _mpsPlayerInit({isVr, url, force}) {
      const self = this;
      const changeControlShow = (flag) => {
        // flag ? this.$Bus.$emit('ws-stop') : this.$Bus.$emit('ws-start')
        this.controlShow = flag
      }
      if (this.mpsPlayerObj && !force) {
        return false;
      }
      if (this.channelInfo.isVr) {
         self._resetConfig();
      }
      const playerOpts = {
        container: 'videoPlayer',
        uin: this.channelInfo.aodianUin,
        appId: this.channelInfo.mpsDynamicVodAppId,
        width: '100%',
        height: '100%',
        controlbardisplay: 'enable',
        orientation: 'portraint',
        enablehtml5: true,
        coverImg: this.mpsBackgroundUrl,
        isShowControlDiv: this.isControl,
        hideScreenBtn: this.isPeep,
        isCheckMulti: true,
        multi: {
          rateList: ['标清', '流畅', '高清', '超清', '蓝光', '4K']
        },
        pauseCallback: function() {
          changeControlShow(true)
        },
        playCallback: function() {
          const liveNowStatus = self.channelInfo.liveNowStatus
          if (liveNowStatus === 1 || liveNowStatus === 2 || liveNowStatus === 3){
            changeControlShow(false)
          }
        },
        ...this.mpsOptions,
        onReady() {
          if (!self.channelInfo.isVr) {
            self._resetConfig();
          }
          // setTimeout(() => {
          self.mpsPlayerObj.addPlayerCallback('Play.Stop', function(fn) {
            fn({ type: 3 });
          });
          self.mpsPlayerObj.addPlayerCallback('enterFullScreen', function() {
            self.isFullScreen = true;
          });
          self.mpsPlayerObj.addPlayerCallback('exitFullScreen', function() {
            self.isFullScreen = false;
          });
          // }, 2000);
        }
      }
      if (isVr && url) {
        playerOpts.type = 'vr'
        playerOpts.url = url
      }
      this.mpsPlayerObj = new mpsPlayer(playerOpts);
    },
    _resetConfig() {
      const { playUrl, saveUrl } = this.playerUrl
      this.set_playerInfo({
        playUrl: playUrl,
        saveUrl: saveUrl,
        cameraId: ''
      });
    },
    _reviseProtocol(url) {
      let path = url;
      if (!path) {
        return '';
      }
      if (window.location.protocol === 'http:') {
        path = path.replace('https://', 'http://');
      } else {
        path = path.replace('http://', 'https://');
      }
      return path;
    },
    _changePlayer() {
      let obj = null;
      if (this.channelInfo.hlsPwdStatus === 1) {
        if (this.playerInfo.playUrl === this.channelInfo.livePlayHlsUrl) {
          obj = { channelId: this.channelInfo.id };
        } else if (this.playerInfo.cameraId) {
          obj = {
            channelId: this.channelInfo.id,
            cameraId: this.playerInfo.cameraId
          };
        } else {
          obj = this._reviseProtocol(this.playerInfo.playUrl);
        }
      } else {
        obj = this._reviseProtocol(this.playerInfo.playUrl);
      }
     if (this.mpsPlayerObj && this.mpsPlayerObj.changePlayer) {
        if (this.onePlayer) {
          this.mpsPlayerObj.changePlayer(obj, !!this.channelInfo.isVr);
          this.onePlayer = false;
        } else {
          this.mpsPlayerObj.changePlayer(obj);
        }
      }
    },
    _seTControlDiv() {
      if (this.mpsPlayerObj && this.mpsPlayerObj.seTControlDiv) {
        this.mpsPlayerObj.seTControlDiv(this.isControl);
      }
    }
  },
  watch: {
    playerInfo: {
      handler() {
        this._changePlayer();
      },
      deep: true
    },
    'channelInfo.liveStatus'(a) {
      setTimeout(() => {
        this._resetConfig();
      }, 10000);
    },
    isControl() {
      this._seTControlDiv();
    },
    'userInfo.id'() {
      this.watermark();
    }
  }
};
</script>
<style lang="less" scoped>
.wrapper {
  position: relative;
  background-color: #000;
  overflow: hidden;
  .time-watch-chat {
    position: absolute;
    bottom: calc(9 / 16 * 100vw - 0.1rem);
    right: 0.1rem;
    z-index: 200;
    transform: translate(0, 100%) scale(0.5);
    transform-origin: 100% 0;
  }
  .more-box {
    position: absolute;
    bottom: 0.5rem;
    right: -0.5rem;
    z-index: 200;
    transition: right 0.5s ease 3s;
  }
  &:hover {
    .more-box {
      right: 0.1rem;
      transition: right 0.5s ease 0s;
    }
  }
}
#mps {
  position: relative;
  ::v-deep div {
    box-sizing: unset;
  }
  ::v-deep #videoBox {
    width: 100% !important;
    height: 100% !important;
  }
  .mpstitle-name {
    position: absolute;
    z-index: 5;
    top: 0;
    left: 0;
    right: 0;
    display: none;
    width: 100%;
    height: 50px;
    line-height: 50px;
    text-align: center;
    font-size: 16px;
    font-weight: 700;
    background-color: #000;
    color: #fff;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .videoPlayer {
    position: relative;
    z-index: 100;
    width: 100%;
    height: calc(9 / 16 * 100vw);
  }
}
</style>
