import {
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  toRefs,
  watch
} from 'vue';
import { ref } from 'vue';
import styles from './index.module.less';

import TCPlayer from 'tcplayer.js';
import 'tcplayer.js/dist/tcplayer.min.css';
import iconLoop from '../../image/icon-loop.svg';
import iconLoopActive from '../../image/icon-loop-active.svg';
import iconplay from '../../image/icon-play.svg';
import iconpause from '../../image/icon-pause.svg';
import { NSlider } from 'naive-ui';
import { getSecondRPM } from '@/helpers/utils';

export default defineComponent({
  name: 'video-play',
  props: {
    item: {
      type: Object,
      default: () => {
        return {};
      }
    },
    pageVisibility: {
      type: String,
      default: ''
    },
    show: {
      type: Boolean,
      default: false
    },
    showModel: {
      type: Boolean,
      default: false
    },
    isEmtry: {
      type: Boolean,
      default: false
    }
  },
  emits: ['loadedmetadata', 'togglePlay', 'ended', 'reset', 'close', 'error'],
  setup(props, { emit, expose }) {
    const videoID = 'video' + Date.now() + Math.floor(Math.random() * 100);
    const videoItem = ref();
    const { item, isEmtry } = toRefs(props);
    const data = reactive({
      timer: null as any,
      currentTime: 0,
      duration: 0,
      loop: false,
      playState: 'pause' as 'play' | 'pause',
      vudio: null as any,
      reload: false
    });
    const contetRef = ref();

    watch(
      () => props.show,
      val => {
        onToggleAudio('pause');
      }
    );
    watch(
      () => props.pageVisibility,
      val => {
        if (val === 'hidden' && props.show) {
          onToggleAudio('pause');
        }
      }
    );

    let playTimer = null as any;
    // 切换音频播放
    const onToggleAudio = (state: 'play' | 'pause') => {
      clearTimeout(playTimer);
      if (state === 'play') {
        playTimer = setTimeout(() => {
          videoItem.value?.play();
          data.playState = 'play';
        }, 100);
      } else {
        videoItem.value?.pause();
        data.playState = 'pause';
      }
      emit('togglePlay', data.playState);
    };

    // 如果视屏异常后，需要重新播放视屏
    const onPlay = () => {
      if (videoItem.value) {
        videoItem.value.src(item.value.content);
        emit('reset');
      }
    };

    /** 改变播放时间 */
    const handleChangeTime = (val: number) => {
      data.currentTime = val;
      clearTimeout(data.timer);
      data.timer = setTimeout(() => {
        // elRef.value.currentTime = val;
        // data.timer = null;
        videoItem.value.currentTime(val);
        data.timer = null;
      }, 300);
    };

    const __init = () => {
      videoItem.value = TCPlayer(videoID, {
        appID: '',
        controls: false
      }); // player-container-id 为播放器容器 ID，必须与 html 中一致
      if (videoItem.value) {
        console.log(videoItem.value);
        videoItem.value.poster(props.item.coverImg); // 封面
        videoItem.value.src(isEmtry.value ? '' : item.value.content); // url 播放地址

        // 初步加载时
        videoItem.value.one('loadedmetadata', (e: any) => {
          console.log(' Loading metadata', e);
          data.reload = false;
          // 获取时长
          data.duration = videoItem.value.duration();

          emit('loadedmetadata', videoItem.value);
        });

        // 视频播放时加载
        videoItem.value.on('timeupdate', () => {
          if (data.timer) return;
          data.currentTime = videoItem.value.currentTime();
        });

        // 视频播放结束
        videoItem.value.on('ended', () => {
          data.playState = 'pause';
          emit('ended');
        });

        //
        videoItem.value.on('pause', () => {
          data.playState = 'pause';
        });

        videoItem.value.on('playing', () => {
          data.playState = 'play';
        });

        videoItem.value.on('canplay', (e: any) => {
          console.log('canplay', e);
        });

        // 视频播放异常
        videoItem.value.on('error', (e: any) => {
          emit('error');
          console.log(e, 'error');
        });
      }
    };

    onMounted(() => {
      __init();
    });

    expose({
      onPlay
    });
    return () => (
      <div class={styles.videoWrap}>
        <div class={styles.content}>
          <div ref={contetRef} class={styles.contentWrap}>
            {!data.reload && (
              <video
                style={{ width: '100%', height: '100%' }}
                poster={props.item.coverImg}
                src={isEmtry.value ? '' : item.value.content}
                id={videoID}
                preload="auto"
                playsinline
                webkit-playsinline></video>
            )}
          </div>
          <div class={styles.videoSection}></div>
        </div>

        <div
          class={[styles.controls, props.showModel ? '' : styles.hide]}
          onClick={(e: Event) => {
            e.stopPropagation();
          }}
          onTouchmove={(e: TouchEvent) => {
            emit('close');
          }}>
          <div class={styles.time}>
            <div>{getSecondRPM(data.currentTime)}</div>
            <div>{getSecondRPM(data.duration)}</div>
          </div>
          <div class={styles.slider}>
            <NSlider
              tooltip={false}
              step={0.01}
              class={styles.timeProgress}
              value={data.currentTime}
              max={data.duration}
              onUpdate:value={val => handleChangeTime(val)}
            />
          </div>
          <div class={styles.actions} onClick={() => emit('close')}>
            <div
              class={styles.actionBtn}
              onClick={() =>
                onToggleAudio(data.playState === 'pause' ? 'play' : 'pause')
              }>
              <img src={data.playState === 'pause' ? iconplay : iconpause} />
            </div>
            <div
              class={styles.actionBtn}
              onClick={() => (data.loop = !data.loop)}>
              <img src={data.loop ? iconLoopActive : iconLoop} />
            </div>
          </div>
        </div>
      </div>
    );
  }
});
