import {
  defineComponent,
  nextTick,
  onMounted,
  onUnmounted,
  reactive,
  toRefs,
  watch
} from 'vue';
import TCPlayer from 'tcplayer.js';
import 'tcplayer.js/dist/tcplayer.min.css';
// import 'plyr/dist/plyr.css';
// import Plyr from 'plyr';
import { ref } from 'vue';
import styles from './video.module.less';
import iconplay from '../image/icon-pause.png';
import iconpause from '../image/icon-play.png';
import iconReplay from '../image/icon-replay.png';
import { NSlider } from 'naive-ui';

export default defineComponent({
  name: 'video-play',
  props: {
    item: {
      type: Object,
      default: () => {
        return {};
      }
    },
    showModel: {
      type: Boolean,
      default: false
    },
    isEmtry: {
      type: Boolean,
      default: false
    }
  },
  emits: [
    'canplay',
    'pause',
    'togglePlay',
    'ended',
    'reset',
    'error',
    'close',
    'loadedmetadata'
  ],
  setup(props, { emit, expose }) {
    const { item, isEmtry } = toRefs(props);
    const videoFroms = reactive({
      paused: true,
      currentTimeNum: 0,
      currentTime: '00:00',
      durationNum: 0,
      duration: '00:00',
      showBar: true,
      showAction: true
    });
    const videoRef = ref();
    const videoItem = ref();
    const videoID = ref('video' + Date.now() + Math.floor(Math.random() * 100));

    // 对时间进行格式化
    const timeFormat = (num: number) => {
      if (num > 0) {
        const m = Math.floor(num / 60);
        const s = num % 60;
        return (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s);
      } else {
        return '00:00';
      }
    };

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

    //
    const toggleHideControl = (isShow: false) => {
      videoFroms.showBar = isShow;
    };

    const onReplay = () => {
      if (!videoItem.value) return;
      videoItem.value.currentTime(0);
    };

    // 切换音频播放
    const onToggleVideo = (e?: MouseEvent) => {
      e?.stopPropagation();
      if (videoFroms.paused) {
        videoItem.value.play();
        videoFroms.paused = false;
      } else {
        videoItem.value.pause();
        videoFroms.paused = true;
      }
      emit('togglePlay', videoFroms.paused);
    };

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

        // 初步加载时
        videoItem.value.one('loadedmetadata', () => {
          console.log(' Loading metadata');

          // 获取时长
          videoFroms.duration = timeFormat(
            Math.round(videoItem.value.duration())
          );
          videoFroms.durationNum = videoItem.value.duration();

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

        // 视频开始播放
        videoItem.value.on('play', () => {
          emit('close');
          emit('canplay');
        });

        // 视频播放时加载
        videoItem.value.on('timeupdate', () => {
          videoFroms.currentTime = timeFormat(
            Math.round(videoItem.value?.currentTime() || 0)
          );
          videoFroms.currentTimeNum = videoItem.value.currentTime();
        });

        // 视频播放结束
        videoItem.value.on('ended', () => {
          videoFroms.paused = true;
          emit('ended');
        });

        //
        videoItem.value.on('pause', () => {
          videoFroms.paused = true;
          emit('pause');
        });

        videoItem.value.on('playing', () => {
          videoFroms.paused = false;
        });

        videoItem.value.on('canplay', (e: any) => {
          // 获取时长
          videoFroms.duration = timeFormat(
            Math.round(videoItem.value.duration())
          );
          videoFroms.durationNum = videoItem.value.duration();
          emit('canplay');
        });

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

    onUnmounted(() => {
      if (videoItem.value) {
        videoItem.value.pause();
        videoItem.value.src('');
        videoItem.value.dispose();
      }
    });

    watch(
      () => props.item,
      (val, oldVal) => {
        videoItem.value.pause();
        videoItem.value.currentTime(0);
        videoItem.value.poster(props.item.coverImg); // 封面
        videoItem.value.src(item.value.content); // url 播放地址
        videoFroms.paused = true;
      }
    );
    watch(
      () => props.showModel,
      () => {
        // console.log(props.showModel, 'props.showModel')
        videoFroms.showAction = props.showModel;
      }
    );
    expose({
      onPlay,
      stop,
      // changePlayBtn,
      toggleHideControl
    });
    return () => (
      <div class={styles.videoWrap}>
        <video
          style={{ width: '100%', height: '100%' }}
          ref={videoRef}
          id={videoID.value}
          preload="auto"
          playsinline
          webkit-playsinline
          x5-video-player-type="h5"></video>

        <div
          class={[
            styles.controls,
            videoFroms.showAction ? '' : styles.sectionAnimate
          ]}
          onClick={(e: MouseEvent) => {
            e.stopPropagation();
            if (videoItem.value.paused()) return;
            emit('close');
            emit('reset');
          }}>
          <div class={styles.actions}>
            <div class={styles.actionWrap}>
              <button class={styles.actionBtn} onClick={onToggleVideo}>
                {videoFroms.paused ? (
                  <img class={styles.playIcon} src={iconplay} />
                ) : (
                  <img class={styles.playIcon} src={iconpause} />
                )}
              </button>
            </div>
            <div class={styles.time}>
              <div
                class="plyr__time plyr__time--current"
                aria-label="Current time">
                {videoFroms.currentTime}
              </div>
              <span class={styles.line}>/</span>
              <div
                class="plyr__time plyr__time--duration"
                aria-label="Duration">
                {videoFroms.duration}
              </div>
            </div>
          </div>

          <div class={styles.slider}>
            <NSlider
              value={videoFroms.currentTimeNum}
              step={0.01}
              max={videoFroms.durationNum}
              tooltip={false}
              onUpdate:value={(val: number) => {
                videoItem.value.currentTime(val);
                videoFroms.currentTimeNum = val;
                videoFroms.currentTime = timeFormat(Math.round(val || 0));
              }}
            />
          </div>

          <div class={styles.actions}>
            <div class={styles.actionWrap}>
              <button class={styles.iconReplay} onClick={onReplay}>
                <img src={iconReplay} />
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }
});
