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 iconLoop from '../image/icon-loop.svg';
import iconLoopActive from '../image/icon-loop-active.svg';
import iconSpeed from '../image/icon-speed.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
    },
    imagePos: {
      type: String,
      default: 'left'
    }
  },
  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,
      loop: false,
      speedControl: false,
      speedStyle: {
        left: '1px'
      },
      defaultSpeed: 1 // 默认速度
    });
    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;
      videoFroms.speedControl = false;
    };

    const onReplay = () => {
      videoFroms.speedControl = false;
      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);
    };

    const 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 = () => {
      if (videoItem.value) {
        videoItem.value.poster(props.item.coverImg); // 封面
        videoItem.value.src(item.value.content); // url 播放地址
        videoItem.value.playbackRate(videoFroms.defaultSpeed);
        // 初步加载时
        videoItem.value.one('loadedmetadata', () => {
          // console.log(' Loading metadata');
          videoItem.value.playbackRate(videoFroms.defaultSpeed);

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

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

          if (item.value.autoPlay && videoItem.value) {
            // videoItem.value?.play()
            nextTick(() => {
              videoTimerErrorCount = 0;
              videoItem.value.currentTime(0);
              nextTick(handlePlayVideo);
            });
          }
        });

        // 视频开始播放
        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');
        });
      }
    };

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

      __init();
    });
    const stop = () => {
      videoItem.value.currentTime(0);
      videoItem.value.pause();
    };

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

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

    watch(
      () => props.item,
      () => {
        // console.log(item.value, 'value----');
        videoItem.value.pause();
        videoItem.value.currentTime(0);
        if (item.value?.id) {
          // videoItem.value.poster(props.item.coverImg); // 封面
          // videoItem.value.src(item.value.content); // url 播放地址
          __init();

          videoFroms.paused = true;
        }
      }
    );
    watch(
      () => props.showModel,
      () => {
        // console.log(props.showModel, 'props.showModel')
        videoFroms.showAction = props.showModel;
        videoFroms.speedControl = false;
      }
    );
    expose({
      onPlay,
      stop,
      pause,
      // 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.videoPop}></div>

        <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.slider}>
            <NSlider
              value={videoFroms.currentTimeNum}
              step={0.01}
              max={videoFroms.durationNum}
              tooltip={false}
              onUpdate:value={(val: number) => {
                videoFroms.speedControl = false;
                videoItem.value.currentTime(val);
                videoFroms.currentTimeNum = val;
                videoFroms.currentTime = timeFormat(Math.round(val || 0));
              }}
            />
          </div>
          <div class={styles.tools}>
            {props.imagePos === 'right' ? (
              <>
                <div class={styles.actions}>
                  <div class={styles.actionWrap}>
                    <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>
                <div class={styles.actions}>
                  <div class={styles.actionWrap}>
                    <div
                      class={styles.actionBtnSpeed}
                      onClick={e => {
                        e.stopPropagation();
                        videoFroms.speedControl = !videoFroms.speedControl;
                      }}>
                      <img src={iconSpeed} />
                      <div
                        style={{
                          display: videoFroms.speedControl ? 'block' : 'none'
                        }}>
                        <div
                          class={styles.sliderPopup}
                          onClick={(e: Event) => {
                            e.stopPropagation();
                          }}>
                          <i
                            class={styles.iconAdd}
                            onClick={() => {
                              if (videoFroms.defaultSpeed >= 1.5) {
                                return;
                              }

                              if (videoItem.value) {
                                videoFroms.defaultSpeed =
                                  (videoFroms.defaultSpeed * 10 + 1) / 10;
                                videoItem.value.playbackRate(
                                  videoFroms.defaultSpeed
                                );
                              }
                            }}></i>
                          <NSlider
                            value={videoFroms.defaultSpeed}
                            step={0.1}
                            max={1.5}
                            min={0.5}
                            vertical
                            tooltip={false}
                            onUpdate:value={(val: number) => {
                              videoFroms.defaultSpeed = val;

                              if (videoItem.value) {
                                videoItem.value.playbackRate(
                                  videoFroms.defaultSpeed
                                );
                              }
                            }}>
                            {{
                              thumb: () => (
                                <div class={styles.sliderPoint}>
                                  {videoFroms.defaultSpeed}
                                  <span>x</span>
                                </div>
                              )
                            }}
                          </NSlider>
                          <i
                            class={[styles.iconCut]}
                            onClick={() => {
                              if (videoFroms.defaultSpeed <= 0.5) {
                                return;
                              }
                              if (videoItem.value) {
                                videoFroms.defaultSpeed =
                                  (videoFroms.defaultSpeed * 10 - 1) / 10;
                                videoItem.value.playbackRate(
                                  videoFroms.defaultSpeed
                                );
                              }
                            }}></i>
                        </div>
                      </div>
                    </div>
                    <button class={styles.iconReplay} onClick={onReplay}>
                      <img src={iconLoop} />
                    </button>
                    <div
                      class={styles.actionBtn}
                      onClick={() => {
                        videoFroms.speedControl = false;
                        onToggleVideo();
                      }}>
                      {videoFroms.paused ? (
                        <img class={styles.playIcon} src={iconplay} />
                      ) : (
                        <img class={styles.playIcon} src={iconpause} />
                      )}
                    </div>
                  </div>
                </div>
              </>
            ) : (
              <>
                <div class={styles.actions}>
                  <div class={styles.actionWrap}>
                    <div
                      class={styles.actionBtn}
                      onClick={() => {
                        videoFroms.speedControl = false;
                        onToggleVideo();
                      }}>
                      {videoFroms.paused ? (
                        <img class={styles.playIcon} src={iconplay} />
                      ) : (
                        <img class={styles.playIcon} src={iconpause} />
                      )}
                    </div>

                    <button class={styles.iconReplay} onClick={onReplay}>
                      <img src={iconLoop} />
                    </button>

                    <div
                      class={styles.actionBtnSpeed}
                      onClick={e => {
                        e.stopPropagation();
                        videoFroms.speedControl = !videoFroms.speedControl;
                      }}>
                      <img src={iconSpeed} />

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

                              if (videoItem.value) {
                                videoFroms.defaultSpeed =
                                  (videoFroms.defaultSpeed * 10 + 1) / 10;
                                videoItem.value.playbackRate(
                                  videoFroms.defaultSpeed
                                );
                              }
                            }}></i>
                          <NSlider
                            value={videoFroms.defaultSpeed}
                            step={0.1}
                            max={1.5}
                            min={0.5}
                            vertical
                            tooltip={false}
                            onUpdate:value={(val: number) => {
                              videoFroms.defaultSpeed = val;

                              if (videoItem.value) {
                                videoItem.value.playbackRate(
                                  videoFroms.defaultSpeed
                                );
                              }
                            }}>
                            {{
                              thumb: () => (
                                <div class={styles.sliderPoint}>
                                  {videoFroms.defaultSpeed}
                                  <span>x</span>
                                </div>
                              )
                            }}
                          </NSlider>
                          <i
                            class={[styles.iconCut]}
                            onClick={() => {
                              if (videoFroms.defaultSpeed <= 0.5) {
                                return;
                              }
                              if (videoItem.value) {
                                videoFroms.defaultSpeed =
                                  (videoFroms.defaultSpeed * 10 - 1) / 10;
                                videoItem.value.playbackRate(
                                  videoFroms.defaultSpeed
                                );
                              }
                            }}></i>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class={styles.actions}>
                  <div class={styles.actionWrap}>
                    <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>
              </>
            )}
          </div>
        </div>
      </div>
    );
  }
});
