<template>
  <!-- 右侧弹框 -->
  <van-popup :value="levitatedSphereVisible" @input="showChange" position="right" class="levitated-sphere-drawer"
      overlay-class="levitated-sphere-overlay" :overlay-style="{'background-color': 'transparent !important'}">
      <div class="flex-column" style="min-width: 50px;">
          <div class="flex-column-container">
              <div>
                  <div v-for="item in definitionList" :key="item.key"
                      :class="['tc drawer-item mb-4', {active: actDefinition === item.name}]"
                      @click.prevent="definitionFun(item)">
                      {{item.name}}
                  </div>
                  <!-- <div class="tc drawer-item mb-4" @click.prevent="resolutionRatio">
                      分辨率
                  </div> -->
                  <div class="tc drawer-item mb-4" @click.prevent="volumeControl(24)">
                      音量 +
                  </div>
                  <div class="tc drawer-item" @click.prevent="volumeControl(25)">
                      音量 -
                  </div>
              </div>
          </div>
          <div class="exit">
              <template v-for="(item, index) in exitList">
                  <div :key="item.key" :class="['tc', {'mb-4': index !== exitList.length - 1}, item.key]"
                      @click.prevent="exitFun(item.key)">
                      <img :src="item.img" alt="">
                      <div class="drawer-item">
                          {{item.name}}
                      </div>
                  </div>
              </template>
          </div>
      </div>
  </van-popup>
</template>

<script>
import * as uni from '../../../static/static/js/uni.webview.1.5.2.js';

export default {
  name: 'RightPopup',
  props: {
    // 拉流渲染引擎实例
    engine: {
      type: Object,
      default: () => ({})
    },
    userCardId: {
      type: String,
      default: ''
    },
    // popup是否显示
    levitatedSphereVisible: {
      type: Boolean,
      default: false
    },
    // 清晰度默认值
    definitionValue: {
      type: String,
      default: ()=> localStorage.getItem('definitionValue') ?? '自动',
    },
    // 清晰度列表
    definitionList: {
      type: Array,
      default: () => [{
            name: '自动',
            value: 2800
        }, {
            name: '高清',
            value: 2800
        }, {
            name: '标清',
            value: 1500,
        }, {
            name: '流畅',
            value: 1000,
        }]
    },
    // 清晰度对应分辨率和帧率列表
    resolutionRatioList: {
      type: Object,
      default: () => ({
          '自动': { width: 720, height: 1280, fps: 30 },
          '高清': { width: 720, height: 1280, fps: 30 },
          '标清': { width: 540, height: 960, fps: 25 },
          '流畅': { width: 360, height: 640, fps: 20 },
      })
    },
    // url中获取的参数, 父组件传递
    parametersData: {
      type: Object,
      default: () => ({})
    },
  },
  data() {
    return {
      // 当前清晰度
      actDefinition: this.definitionValue,
    }
  },
  computed: {
    // 右侧弹框退出相关按钮
    exitList() {
      let arr = [{
          name: '剪贴版',
          key: "shearplate",
          img: '../static/img/wx/jianqieban_icon.png'
      }, {
          name: '退出',
          key: 'signout',
          img: '../static/img/wx/tuichu_icon.png'
      }]
      // 1、2、3：年卡、普通计时、自动续费普通计时卡
      if ([1, 2, 3].includes(+this.parametersData.userCardType)) {
          arr.push({
              name: '退出并下机',
              key: 'dormant',
              img: '../static/img/wx/tuichu_icon.png'
          })
      }
      return arr
    }
  },
  methods: {
    showChange(val){
      this.$emit('update:levitatedSphereVisible', val);
    },
    // 清晰度 画质
    definitionFun(item) {
      try {
        this.actDefinition = item.name;

        // 设置日志参数 推流质量
        // logReportObj.setParams({ imageQuality: item.name });
        
        localStorage.setItem('definitionValue', item.name);

        // 设置码率
        this.setBitrate(item);

        this.$emit('update:levitatedSphereVisible', false);
      } catch (err) {
        console.log(err)
      }
    },
    // 设置码率
    setBitrate(item) {
      // 设置码率和是否允许自动
      this.engine?.setCustomBitrate(item.value, item.name === '自动');
  
      // 获取并设置编码器分辨率和帧率
      const config = this.resolutionRatioList[item.name];
      if (config) {
          this.engine?.setEncoderSize(config);
      }
    },
    // 分辨率 已无用,2.0sdk只能固定的几个分辨率值 resolutionRatioList
    resolutionRatio() {
      request.get('/api/resources/v5/machine/resolution/getResolvingPower', { params: { userCardId: this.parametersData.userCardId } }).then(res => {
        if (res.success) {
          this.resolutionRatioList = res.data.map(item => {
              item.height = item.high
              return item
          })
        }
      })
    },
    // 音量控制 24: 音量+ 25: 音量-
    volumeControl(value) {
      this.engine.sendKey && this.engine.sendKey(value);
    },
    // 退出相关按钮操作
    exitFun(key) {
      switch (key) {
        case 'dormant': // 退出并下机
          this.$dialog.alert({
              title: '提示',
              message: '确定退出云手机并下机',
              confirmButtonText: '确定',
              confirmButtonColor: '#3cc51f',
              showCancelButton: true,
              beforeClose: (action, done) => {
                  if (action === 'cancel') done()
                  if (action === 'confirm') {
                      this.downline(done)
                  }
              }
          })
          break;
        case 'shearplate': // 剪贴板
          // 打开剪贴板
          this.$emit('shearplate');
          // 关闭popup
          this.$emit('update:levitatedSphereVisible', false);
          break;
        case 'signout':
          // 关闭popup
          this.$emit('update:levitatedSphereVisible', false);
          this.$emit('exit');
          break;
      }
    },
    // 退出并下机
    async downline(fun = () => {}) {
      try {
        const res = await this.$axios.get('/resources/yearMember/downline?userCardId=${this.userCardId}`');
        if(!res.status){
          fun(true);
          // 判断是否是顶级窗口（不是嵌套在 iframe 中）目前只有ios的浏览器中才会是顶级窗口
          const isTopWindow = window.parent === window.self;
          if(isTopWindow){
            // 通信给h5项目告知是退出并下机
            parent.postMessage({ type: 'exit' }, '*');
            uni.postMessage({ data: { type: 'exit' }});
          }

          this.$emit('exit');
          return
        }
        fun(false)
        this.$toast(res.msg);
      } catch (error) {
        console.log(error);
      }
    },
  }
}
</script>

<style lang="less" scoped>
.levitated-sphere-drawer {
  height: 100%;
  max-height: none !important;
  min-width: 1rem;
  color: #fff;
  background-color: rgba(2, 2, 6, 0.5);
  padding: 30px 10px 0;
  box-sizing: border-box;
}
.levitated-sphere-drawer .drawer-item {
  line-height: 30px;
  border-radius: 3px;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  -khtml-user-select: none;
  user-select: none;
}
.levitated-sphere-drawer .drawer-item.active {
  background: rgb(255, 255, 255);
  color: #000;
}
.levitated-sphere-drawer .exit {
  line-height: 30px;
}
.levitated-sphere-drawer .exit img {
  width: 24px;
  height: 24px;
}

.flex-column {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.flex-column-container {
    flex: 1;
    overflow-y: auto;
}

.tc {
    text-align: center;
}
</style>