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.png';
import iconLoopActive from '../../image/icon-loop-active.png';
import iconplay from '../../image/icon-play.svg';
import iconpause from '../../image/icon-pause.svg';
import iconSpeed from '../../image/icon-speed.png';
import { NSlider } from 'naive-ui';
import { getSecondRPM } from '@/helpers/utils';
import { Slider, showToast } from 'vant';

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: ['canplay', 'pause', 'togglePlay', 'ended', 'reset', 'close', 'error', 'loadedmetadata'],
  setup(props, { emit, expose }) {
    const videoID = 'video' + Date.now() + Math.floor(Math.random() * 100);
    const speedBtnId = 'speed' + 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,
      speedControl: false,
      speedStyle: {
        left: '1px'
      },
      defaultSpeed: 1 // 默认速度
    });
    const contetRef = ref();

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

    let playTimer = null as any;
    // 切换音频播放
    const onToggleAudio = (state: 'play' | 'pause') => {
      data.speedControl = false;
      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 = () => {
      data.speedControl = false;
      if (videoItem.value) {
        videoItem.value.src(item.value.content);
        emit('reset');
      }
    };

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

    let videoTimer = null as any;
    let videoTimerErrorCount = 0;
    const handlePlayVideo = () => {
      if (videoTimerErrorCount > 5) {
        return;
      }
      clearTimeout(videoTimer);
      nextTick(() => {
        videoItem.value?.play().catch((err: any) => {
          // console.log('🚀 ~ err:', err)
          videoTimer = setTimeout(() => {
            if (err?.message?.includes('play()')) {
              // emit('play');
            }
            handlePlayVideo();
          }, 1000);
        });
      });
      videoTimerErrorCount++;
    };

    const __init = () => {
      // videoEle
      if (videoItem.value) {
        console.log(videoItem.value, 'item.value', item.value);
        videoItem.value.poster(props.item.coverImg); // 封面
        videoItem.value.src(item.value.content); // url 播放地址
        videoItem.value.playbackRate(data.defaultSpeed);
        // 初步加载时
        videoItem.value.one('loadedmetadata', (e: any) => {
          videoItem.value.playbackRate(data.defaultSpeed);
          data.reload = false;
          // 获取时长
          data.duration = videoItem.value.duration();
          emit('canplay', videoItem.value);

          if (item.value.autoPlay && videoItem.value) {
            // videoItem.value?.play()
            nextTick(() => {
              videoTimerErrorCount = 0;
              videoItem.value.currentTime(0);
              nextTick(handlePlayVideo);
            });
          }
          emit('loadedmetadata', videoItem.value)
        });
        // 视频开始播放
        videoItem.value.on('play', () => {
          emit('close');
          emit('canplay');
        });
        //
        videoItem.value.on('pause', () => {
          data.playState = 'pause';
          emit('pause');
        });

        // 视频播放时加载
        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('playing', () => {
          data.playState = 'play';
        });

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

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

    watch(
      () => props.item,
      () => {
        videoItem.value.pause();
        videoItem.value.currentTime(0);
        if (item.value?.id) {
          __init();
          data.playState = 'pause';
        } else {
          videoItem.value.pause();
        }
      }
    );
    watch(
      () => props.showModel,
      () => {
        data.speedControl = false;
      }
    );

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

      document.getElementById(speedBtnId)?.addEventListener('click', e => {
        e.stopPropagation();
        data.speedControl = !data.speedControl;
      });
    });

    const pause = () => {
      videoItem.value.pause();
    };

    expose({
      onPlay,
      pause
    });
    return () => (
      <div class={styles.videoWrap}>
        <div class={styles.content}>
          <div ref={contetRef} class={styles.contentWrap}>
            <video
              style={{ width: '100%', height: '100%' }}
              id={videoID}
              preload="auto"
              playsinline
              webkit-playsinline
              x5-video-player-type="h5"></video>
          </div>
          <div class={styles.videoSection}></div>
        </div>

        <div
          class={[styles.controls, props.showModel ? '' : styles.hide]}
          onClick={(e: Event) => {
            e.stopPropagation();
            if (videoItem.value.paused()) return;
            emit('close');
          }}
          onTouchmove={(e: Event) => {
            if (videoItem.value.paused()) return;
            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}>
            <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;
                data.speedControl = false;
                videoItem.value.loop(data.loop);
                if (data.loop) {
                  setTimeout(() => {
                    showToast('已打开循环播放');
                  }, 60);
                } else {
                  setTimeout(() => {
                    showToast('已关闭循环播放');
                  }, 60);
                }
              }}>
              <img src={data.loop ? iconLoopActive : iconLoop} />
            </div>

            <div class={styles.actionBtn} id={speedBtnId}>
              <img src={iconSpeed} />
            </div>
          </div>
        </div>

        <div
          style={{
            display: data.speedControl ? 'block' : 'none'
          }}>
          <div
            class={styles.sliderPopup}
            onClick={(e: Event) => {
              e.stopPropagation();
            }}>
            <i
              class={styles.iconAdd}
              onClick={() => {
                if (data.defaultSpeed >= 1.5) {
                  return;
                }

                if (videoItem.value) {
                  data.defaultSpeed = (data.defaultSpeed * 10 + 1) / 10;
                  videoItem.value.playbackRate(data.defaultSpeed);
                }
              }}></i>
            <Slider
              min={0.5}
              max={1.5}
              step={0.1}
              v-model={data.defaultSpeed}
              vertical
              barHeight={5}
              reverse
              onChange={() => {
                if (videoItem.value) {
                  videoItem.value.playbackRate(data.defaultSpeed);
                }
              }}>
              {{
                button: () => (
                  <div class={styles.sliderPoint}>
                    {data.defaultSpeed}
                    <span>x</span>
                  </div>
                )
              }}
            </Slider>
            <i
              class={[styles.iconCut]}
              onClick={() => {
                if (data.defaultSpeed <= 0.5) {
                  return;
                }
                if (videoItem.value) {
                  data.defaultSpeed = (data.defaultSpeed * 10 - 1) / 10;
                  videoItem.value.playbackRate(data.defaultSpeed);
                }
              }}></i>
          </div>
        </div>
      </div>
    );
  }
});
