import { defineComponent, PropType } from 'vue';
import styles from './index.module.less';
import Plyr from 'plyr';
import 'plyr/dist/plyr.css';
import { Loading } from 'vant';
import { browser } from '@/helpers/utils';
export default defineComponent({
  name: 'm-video',
  props: {
    setting: {
      type: Object,
      default: () => ({})
    },
    controls: Boolean,
    height: String,
    src: {
      type: String,
      default: ''
    },
    poster: {
      type: String,
      default: ''
    },
    styleValue: {
      type: Object,
      default: () => ({})
    },
    preload: {
      type: String as PropType<'auto' | 'metadata' | 'none'>,
      default: 'auto'
    },
    currentTime: {
      type: Boolean,
      default: true
    },
    playsinline: {
      type: Boolean,
      default: true
    },
    preLoading: {
      type: Boolean,
      default: true
    }
    // onPlay: {
    //   type: Function,
    //   default: () => {}
    // }
  },
  emits: ['exitfullscreen', 'play', 'ready', 'enterfullscreen'],
  data() {
    return {
      player: null as any,
      loading: true // 首次进入加载中
    };
  },
  mounted() {
    this.loading = this.preLoading;
    this._init();
  },
  methods: {
    _init() {
      // controls: [
      //   'play-large' ,  // 中间的大播放按钮
      //   'restart' ,  // 重新开始播放
      //   'rewind' ,  // 按寻道时间倒带（默认 10 秒）
      //   'play' ,  // 播放/暂停播放
      //   'fast-forward' ,  // 快进查找时间（默认 10 秒）
      //   'progress' ,  // 播放和缓冲的进度条和滑动条
      //   'current-time' ,  // 播放的当前时间
      //   ' duration' ,  // 媒体的完整持续时间
      //   'mute' ,  // 切换静音
      //   'volume', // 音量控制
      //   'captions' ,  // 切换字幕
      //   'settings' ,  // 设置菜单
      //   'pip' ,  // 画中画（当前仅 Safari）
      //   'airplay' ,  // Airplay（当前仅 Safari）
      //   'download ' ,  // 显示一个下载按钮，其中包含指向当前源或您在选项中指定的自定义 URL 的链接
      //   'fullscreen' ,  // 切换全屏
      // ] ;
      const controls = [
        'play-large',
        'play',
        'progress',
        'captions',
        'fullscreen'
      ];
      // if (browser().isApp) {
      //   controls.push('fullscreen');
      // }

      if (this.currentTime) {
        controls.push('current-time');
      }
      const params: any = {
        controls: controls,
        ...this.setting,
        invertTime: false
      };

      if (browser().iPhone) {
        params.fullscreen = {
          enabled: true,
          fallback: 'force',
          iosNative: true
        };
      }

      this.player = new Plyr((this as any).$refs.video, params);

      this.player.elements.container
        ? (this.player.elements.container.style.height = this.height || '210px')
        : null;

      if (this.preload === 'none') {
        this.loading = false;
      }
      this.player.on('loadedmetadata', () => {
        this.loading = false;
        this.domPlayVisibility(false);
      });

      this.player.on('loadeddata', () => {
        this.$emit('ready', this.player);
      });

      this.player.on('play', () => {
        this.$emit('play', this.player);
      });

      this.player.on('enterfullscreen', () => {
        console.log('fullscreen', this.player.elements);
        const fragment = document.createDocumentFragment();
        const i = document.createElement('i');
        i.id = 'fullscreen-back';
        i.className = 'van-icon van-icon-arrow-left video-back';
        i.addEventListener('click', () => {
          this.player.fullscreen.exit();
        });
        console.log(document.getElementsByClassName('plyr'), i);
        fragment.appendChild(i);
        // const parentNode = document.getElementsByClassName('plyr')[0];
        // parentNode.insertBefore(fragment, parentNode.firstChild);
        this.player.elements.container.appendChild(fragment);

        this.$emit('enterfullscreen');
      });

      this.player.on('exitfullscreen', () => {
        console.log('exitfullscreen');
        const i = document.getElementById('fullscreen-back');
        i && i.remove();
        this.$emit('exitfullscreen');
      });
    },
    // 操作功能
    domPlayVisibility(hide = true) {
      const controls = document.querySelector('.plyr__controls');
      const controls2 = document.querySelector('.plyr__control--overlaid');
      if (hide) {
        controls?.setAttribute('style', 'display:none');
        controls2?.setAttribute('style', 'display:none');
      } else {
        controls?.removeAttribute('style');
        setTimeout(() => {
          controls2?.removeAttribute('style');
        }, 200);
      }
    },
    onStop() {
      this.player.stop();
    },
    onExitScreen() {
      this.player.fullscreen.active && this.player.fullscreen.exit();
    },
    onPlay() {
      this.player?.play();
    }
  },
  unmounted() {
    this.player?.destroy();
  },
  render() {
    return (
      <div class={styles['video-container']}>
        <video
          ref="video"
          class={styles['video']}
          src={this.src}
          playsinline={this.playsinline}
          poster={this.poster}
          preload={this.preload}
          style={{ ...this.styleValue }}></video>
        {/* </div> */}
        {/* 加载视频使用 */}
        {this.loading && (
          <div
            class={styles.loadingVideo}
            style={{
              height: this.height || '210px'
            }}>
            <Loading
              size={36}
              color="#FF8057"
              vertical
              style={{ height: '100%', justifyContent: 'center' }}>
              加载中...
            </Loading>
          </div>
        )}
      </div>
    );
  }
});
