import {
  defineComponent,
  onMounted,
  ref,
  watch,
  Transition,
  toRefs,
  nextTick
} from 'vue';
import styles from './index.module.less';
import { Slider } from 'vant';
import iconplay from '../coursewarePlay/image/icon-play.svg';
import iconpause from '../coursewarePlay/image/icon-pause.svg';
import iconVideobg from '../coursewarePlay/image/icon-videobg.png';
import { getSecondRPM } from '@/helpers/utils';
import TCPlayer from 'tcplayer.js';
import 'tcplayer.js/dist/tcplayer.min.css';
export default defineComponent({
  name: 'video-class',
  props: {
    item: {
      type: Object,
      default: () => {
        return {};
      }
    },
    /** 是否会员 */
    isMember: {
      type: Boolean,
      default: true
    },
    modal: {
      type: Boolean,
      default: true
    }
  },
  emits: [
    'loadedmetadata',
    'togglePlay',
    'ended',
    'reset',
    'error',
    'close',
    'changeModal',
    'pause',
    'seeked',
    'seeking',
    'waiting',
    'timeupdate'
  ],
  setup(props, { emit }) {
    const { item, modal } = toRefs(props);
    const videoItem = ref();
    const videoID = 'video' + Date.now() + Math.floor(Math.random() * 100);

    const __init = () => {
      if (videoItem.value) {
        nextTick(() => {
          videoItem.value?.pause();
        });
        // console.log(props.item, item.value, props.isMember, '-----');
        videoItem.value.poster(props.item.coverImg); // 封面
        videoItem.value.src(props.item.content); // url 播放地址
        videoItem.value.loop(props.item.loop);
        // videoItem.value.muted(props.item.muted)
        videoItem.value.autoplay(props.item.autoplay);

        // 初步加载时
        videoItem.value.one('loadedmetadata', () => {
          // 获取时长
          const videoEle = videoItem.value;
          item.value.duration = videoEle.duration();
          item.value.videoEle = videoEle;
          item.value.loaded = true;
          emit('loadedmetadata', videoItem.value);

          if (item.value.autoplay && videoItem.value) {
            item.value.muted = false;
            videoItem.value?.muted(false);
            videoItem.value?.volume(1);
            // videoItem.value?.pause()
            videoItem.value?.play();
          } else {
            item.value.muted = false;
            videoItem.value?.muted(false);
            videoItem.value?.volume(1);
            videoItem.value?.pause();
          }
        });

        // 视频播放时加载
        videoItem.value.on('timeupdate', () => {
          if (!item.value.loaded) return;
          const videoEle = videoItem.value;
          item.value.currentTime = videoEle.currentTime();
          emit('timeupdate');
        });

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

        //
        videoItem.value.on('pause', () => {
          console.log('暂停');
          //暂停
          item.value.paused = true;
          videoItem.value?.pause();
          setTimeout(() => {
            videoItem.value?.pause();
          }, 100);
          emit('pause');
        });

        videoItem.value.on('play', () => {
          item.value.paused = false;
          // 播放
          // console.log(JSON.parse(JSON.stringify(item.value)), 'play ------ ')
          if (item.value.muted) {
            item.value.muted = false;
            videoItem.value?.muted(false);
            videoItem.value?.volume(1);
            videoItem.value?.pause();
          }
        });

        videoItem.value.on('seeked', () => {
          emit('seeked');
        });

        videoItem.value.on('seeking', () => {
          emit('seeking');
        });
        videoItem.value.on('waiting', () => {
          emit('waiting');
        });

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

    onMounted(() => {
      videoItem.value = TCPlayer(videoID, {
        appID: '',
        controls: false,
        loop: item.value.loop,
        muted: false
        // autoplay: true
      }); // player-container-id 为播放器容器 ID，必须与 html 中一致

      __init();
    });

    watch(
      () => props.item,
      () => {
        // item.value.videoEle?.pause()
        __init();
      }
    );
    return () => (
      <>
        <div
          class={styles.itemDiv}
          onClick={() => {
            clearTimeout(item.value.timer);
            // activeData.model = !activeData.model
            emit('changeModal', !modal.value);
          }}>
          <video
            id={videoID}
            style={{ height: '100%', width: '100%' }}
            playsinline="false"
            preload="auto"
            class="player"
            poster={iconVideobg}
            data-vid={item.value.id}
            src={item.value.content}
            // loop={item.value.loop}
            // autoplay={item.value.autoplay}
            // muted={item.value.muted}
          >
            <source src={item.value.content} type="video/mp4" />
          </video>
          <div class={styles.videoSection}></div>
        </div>
        <Transition name="bottom">
          {modal.value && !item.value.muted && (
            <div class={styles.bottomFixedContainer}>
              <div class={styles.time}>
                <span>{getSecondRPM(item.value.currentTime)}</span>/
                <span>{getSecondRPM(item.value.duration)}</span>
              </div>
              <div class={styles.slider}>
                {item.value.duration && (
                  <Slider
                    buttonSize={16}
                    modelValue={item.value.currentTime}
                    min={0}
                    max={item.value.duration}
                  />
                )}
              </div>

              <div class={styles.actions}>
                <div class={styles.actionBtn}>
                  {item.value.paused ? (
                    <img
                      src={iconplay}
                      onClick={() => {
                        clearTimeout(item.value.timer);
                        item.value.videoEle?.play();
                        item.value.paused = false;
                        item.value.timer = setTimeout(() => {
                          // activeData.model = false
                          emit('changeModal', false);
                        }, 4000);
                      }}
                    />
                  ) : (
                    <img
                      src={iconpause}
                      onClick={() => {
                        clearTimeout(item.value.timer);
                        item.value.videoEle?.pause();
                        item.value.paused = true;
                      }}
                    />
                  )}
                </div>
              </div>
            </div>
          )}
        </Transition>
      </>
    );
  }
});
