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

import iconLoop from '../../image/icon-loop.png';
import iconLoopActive from '../../image/icon-loop-active.png';
import iconplay from '../../image/icon-play.png';
import iconpause from '../../image/icon-pause.png';
import { NSlider } from 'naive-ui';
import Vudio from 'vudio.js';
import { getSecondRPM } from '@/helpers/utils';
import { Slider, showToast } from 'vant';
import tickMp3 from '../../image/tick.mp3';

export default defineComponent({
  name: 'video-play',
  props: {
    item: {
      type: Object,
      default: () => {
        return {};
      }
    },
    show: {
      type: Boolean,
      default: false
    },
    pageVisibility: {
      type: String,
      default: ''
    },
    showModel: {
      type: Boolean,
      default: false
    },
    isEmtry: {
      type: Boolean,
      default: false
    }
  },
  emits: ['loadedmetadata', 'togglePlay', 'ended', 'reset', 'close'],
  setup(props, { emit }) {
    const { item, isEmtry } = toRefs(props);
    const data = reactive({
      speedInKbps: '',
      isOnline: true,
      timer: null as any,
      currentTime: 0,
      duration: 0.1,
      loop: false,
      dragStatus: false, // 是否开始拖动
      playState: 'pause' as 'play' | 'pause',
      vudio: null as any,
      afterMa3: true,
      count: 0
    });
    const canvasRef: any = ref();
    const audioRef: any = ref();
    const contetRef = ref();
    // const audioSlider =
    //   'audioSlider' + Date.now() + Math.floor(Math.random() * 100);

    watch(
      () => props.show,
      val => {
        data.count = 0;
        if (val && props.item.autoPlay) {
          // data.count = 0;
          // audioRef.value.src = item.value.content;
          onToggleAudio();
        } else {
          audioRef.value.pause();
          // audioRef.value.src = '';
          data.playState = 'pause';
          // data.vudio = null;
        }
      }
    );
    // watch(
    //   () => props.item,
    //   () => {
    //     // data.count = 0;
    //     // audioRef.value.src = item.value.content;
    //     onToggleAudio();
    //   }
    // );
    watch(
      () => props.pageVisibility,
      val => {
        if (val === 'hidden' && props.show) {
          audioRef.value.pause();
          data.playState = 'pause';
        }
      }
    );

    // 切换音频播放
    const onToggleAudio = () => {
      if (audioRef.value.paused) {
        audioRef.value.play();
        data.playState = 'play';
        //
        nextTick(() => {
          // onInit(audioRef.value, canvasRef.value);
          // setTimeout(() => {
          //   onInit(audioRef.value, canvasRef.value);
          // }, 100);
          // console.log(data.vudio, 'data.vudio');
          // if (data.vudio) {
          //   data.vudio.dance();
          // }
        });
      } else {
        audioRef.value.pause();
        data.playState = 'pause';
      }
    };

    const onInit = (audio: undefined, canvas: undefined) => {
      if (!data.vudio && data.count > 1) {
        console.log(data.vudio, 'data.vudio');
        try {
          const rect = contetRef.value.getBoundingClientRect() || {
            width: 200,
            height: 200
          };

          data.vudio = new Vudio(audio, canvas, {
            effect: 'waveform',
            accuracy: 128,
            width: rect.width,
            height: rect.height,
            waveform: {
              maxHeight: 160,
              color: [
                [0, '#44D1FF'],
                [0.5, '#44D1FF'],
                [0.5, '#198CFE'],
                [1, '#198CFE']
              ],
              prettify: false
            }
          });
          data.vudio.dance();
        } catch (e) {
          console.log(e, 'e');
        }
      } else {
      }
    };
    /** 加载成功 */
    const onLoadedmetadata = () => {
      data.duration = audioRef.value?.duration;
      // onInit(audioRef.value, canvasRef.value);
      if (props.item.autoPlay && audioRef.value && props.show) {
        // data.vudio = null;
        // data.count = 0;
        onToggleAudio();
      }

      // if (audioRef.value) {
      //   audioRef.value.stop = () => {
      //     audioRef.value?.pause();
      //   };
      //   audioRef.value.onPlay = () => {
      //     audioRef.value?.play();
      //     onInit(audioRef.value, canvasRef.value);
      //   };
      // }
      emit('loadedmetadata', audioRef.value);
    };

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

    /** 播放结束 */
    const onEnded = () => {
      data.playState = 'pause';
      // emit('ended');
    };

    let vudio1 = null;
    const canvas1: any = ref();
    const audio1: any = ref();
    nextTick(() => {
      const rect = contetRef.value.getBoundingClientRect() || {
        width: 200,
        height: 200
      };
      vudio1 = new Vudio(audio1.value, canvas1.value, {
        effect: 'waveform',
        accuracy: 128,
        width: rect.width,
        height: rect.height,
        waveform: {
          maxHeight: 160,
          color: [
            [0, '#44D1FF'],
            [0.5, '#44D1FF'],
            [0.5, '#198CFE'],
            [1, '#198CFE']
          ],
          prettify: false
        }
      });
      vudio1.dance();
    });

    const calculateSpeed = (element: any) => {
      let previousBytesLoaded = 0;
      let timer: any = null;
      let previousTime = Date.now();
      let buffterCatchArray = [] as any; // 缓存数据显示
      let isWaiting = false;

      // 缓存检测状态
      let isBuffering = false;
      // 缓存检测计时器
      let bufferTimeout: any = null;
      // 设定一个检测缓存停止的时间间隔，这里我们设置为2500毫秒（2秒）
      const BUFFER_CHECK_INTERVAL = 2500;

      function resetDownloadSpeed() {
        timer = setTimeout(() => {
          // displayElement.textContent = `视屏下载速度: 0 KB/s`;
          data.speedInKbps = `0 KB/s`;
        }, 1500);
      }

      function buffterCatch(time = 0) {
        // 设定一个计时器，检查是否在指定的时间内再次触发了progress事件
        bufferTimeout = setTimeout(() => {
          if (isBuffering) {
            // 如果计时器到达且isBuffering仍为true，则认为缓存停止
            console.log('停止缓存数据。');
            isBuffering = false;
            data.speedInKbps = '';
          }
        }, time || BUFFER_CHECK_INTERVAL);
      }

      function resetBuffterCatch() {
        // 如果有缓存检测计时器，则清除它
        if (bufferTimeout) {
          clearTimeout(bufferTimeout);
        }
        // 标记为正在缓存
        isBuffering = true;

        buffterCatch();
      }

      /**
       * 格式化视屏播放有效时间 - 合并区间
       * @param intervals [[], []]
       * @example [[4, 8],[0, 4],[10, 30]]
       * @returns [[0, 8], [10, 30]]
       */
      const formatEffectiveTime = (intervals: any[]) => {
        const res: any = [];
        intervals.sort((a, b) => a[0] - b[0]);
        let prev = intervals[0];
        for (let i = 1; i < intervals.length; i++) {
          const cur = intervals[i];
          if (prev[1] >= cur[0]) {
            // 有重合
            prev[1] = Math.max(cur[1], prev[1]);
          } else {
            // 不重合，prev推入res数组
            res.push(prev);
            prev = cur; // 更新 prev
          }
        }
        res.push(prev);
        return res;
      };

      console.log(element, 'element');

      // 获取视频总时长
      let noData = false;
      const onProgress = () => {
        const duration = element.duration;
        const currentTime = Date.now();
        const buffered = element.buffered;
        let currentBytesLoaded = 0;
        let currentLength = 0;

        // 计算视频已缓存的总时长
        let cachedDuration = 0;
        if (buffered.length > 0) {
          for (let i = 0; i < buffered.length; i++) {
            currentBytesLoaded += buffered.end(i) - buffered.start(i);
            cachedDuration += buffered.end(i) - buffered.start(i);
            buffterCatchArray = formatEffectiveTime([
              ...buffterCatchArray,
              [buffered.start(i), buffered.end(i)]
            ]);
          }
          // for (let i = 0; i < buffered.length; i++) {
          //   // 寻找当前时间之后最近的点
          //   if (buffered.start(buffered.length - 1 - i) < element.currentTime) {
          //     currentLength =
          //       (buffered.end(buffered.length - 1 - i) / duration) * 100;
          //     break;
          //   }
          // }
          currentBytesLoaded *= element.duration * element.seekable.end(0); // 更精确地近似字节加载量
        }

        // 计算未缓存的时间段
        const uncachedDuration = duration - cachedDuration;
        let uncachedTime = true; // 没有缓存时间
        buffterCatchArray.forEach((item: any) => {
          if (element.currentTime >= item[0] && uncachedTime <= item[1]) {
            uncachedTime = false;
          }
        });
        // console.log(
        //   uncachedTime,
        //   duration,
        //   cachedDuration,
        //   'duration',
        //   buffterCatchArray,
        //   element.currentTime,
        //   currentLength + '%',
        //   isWaiting,
        //   currentBytesLoaded <= previousBytesLoaded
        // );

        const isNoBuffer = currentBytesLoaded <= previousBytesLoaded;
        // console.log(
        //   'progress',
        //   currentBytesLoaded,
        //   previousBytesLoaded,
        //   currentBytesLoaded > previousBytesLoaded
        // );
        // 计算未缓存的时间段
        // const uncachedDuration = duration - cachedDuration;
        // console.log(uncachedDuration, duration, cachedDuration, 'duration');
        // 如果存在未缓存的时间段，可以根据具体情况做出相应处理
        if (uncachedDuration > 0) {
          if (currentBytesLoaded > previousBytesLoaded && data.isOnline) {
            const timeDiff = (currentTime - previousTime) / 1000; // 时间差转换为秒
            const bytesDiff = currentBytesLoaded - previousBytesLoaded; // 字节差值
            const speed = bytesDiff / timeDiff; // 字节每秒

            if (!element.paused) {
              const kbps = speed / 1024;
              const speedInKbps = kbps.toFixed(2); // 转换为千字节每秒并保留两位小数
              if (kbps > 1024) {
                data.speedInKbps = `${Number((kbps / 1024).toFixed(2))} M/s`;
              } else {
                data.speedInKbps = `${Number(speedInKbps)} KB/s`;
              }

              // 如果1秒钟没有返回就重置数据
              clearTimeout(timer);
              resetDownloadSpeed();
            }

            previousBytesLoaded = currentBytesLoaded;
            previousTime = currentTime;
            noData = false;
          }

          if (isNoBuffer && !uncachedTime) {
            // 如果1秒钟没有返回就重置数据

            if (!noData) {
              clearTimeout(timer);
              clearTimeout(bufferTimeout);
              setTimeout(() => {
                if (isBuffering) {
                  // 如果计时器到达且isBuffering仍为true，则认为缓存停止
                  console.log('停止缓存数据');
                  isBuffering = false;
                  data.speedInKbps = '';
                }
              }, 800);
            }

            noData = true;
          }

          if (element.paused || !data.isOnline) {
            clearTimeout(timer);
            data.speedInKbps = '';
          }

          if (!isWaiting) {
            resetBuffterCatch();
          }
        } else {
          clearTimeout(timer);
          buffterCatch(1000);
        }
      };

      const onWaiting = () => {
        console.log('waiting');
        isWaiting = true;
        let uncachedTime = true; // 没有缓存时间
        buffterCatchArray.forEach((item: any) => {
          if (element.currentTime >= item[0] && uncachedTime <= item[1]) {
            uncachedTime = false;
          }
        });

        if (!element.paused && data.isOnline && uncachedTime) {
          // 如果1秒钟没有返回就重置数据
          clearTimeout(timer);
          resetDownloadSpeed();
        }

        // 如果有缓存检测计时器，则清除它
        if (bufferTimeout) {
          clearTimeout(bufferTimeout);
        }
      };

      const onCanplay = () => {
        console.log('canplay');
        isWaiting = false;
        resetBuffterCatch();
      };

      const onPause = () => {
        clearTimeout(timer);
        // 如果有缓存检测计时器，则清除它
        if (bufferTimeout) {
          clearTimeout(bufferTimeout);
        }
        data.speedInKbps = '';
      };

      // element.removeEventListener('progress', onProgress);
      // element.removeEventListener('waiting', onWaiting);
      // element.removeEventListener('canplay', onCanplay);
      // element.removeEventListener('pause', onPause);

      element.addEventListener('progress', onProgress);
      element.addEventListener('waiting', onWaiting);
      element.addEventListener('canplay', onCanplay);
      element.addEventListener('pause', onPause);
    };

    const onChangeOnlineStatus = (val: any) => {
      if (val.type === 'online') {
        data.isOnline = true;
      } else if (val.type === 'offline') {
        data.isOnline = false;
      }
    };
    onMounted(() => {
      nextTick(() => {
        calculateSpeed(audioRef.value);
      });
      window.addEventListener('online', onChangeOnlineStatus);
      window.addEventListener('offline', onChangeOnlineStatus);
    });

    onUnmounted(() => {
      window.removeEventListener('online', onChangeOnlineStatus);
      window.removeEventListener('offline', onChangeOnlineStatus);
    });
    return () => (
      <div class={styles.videoWrap}>
        <div class={styles.content}>
          <div ref={contetRef} class={styles.contentWrap}>
            <canvas ref={canvasRef}></canvas>
            <audio
              src={isEmtry.value ? '' : item.value.content}
              ref={audioRef}
              loop={data.loop}
              onLoadedmetadata={onLoadedmetadata}
              onTimeupdate={() => {
                if (data.timer && data.playState === 'pause') return;
                if (data.count <= 1) {
                  data.count += 1;
                  onInit(audioRef.value, canvasRef.value);
                }
                // 开始拖动时也不能更新
                if (data.dragStatus) return;
                data.currentTime = audioRef.value?.currentTime;
              }}
              onError={() => {
                console.log('error');
                audioRef.value.pause();
                data.playState = 'pause';
              }}
              onPause={() => {
                console.log('pause');
                data.playState = 'pause';
              }}
              onProgress={() => {
                console.log('progress');
              }}
              onEnded={onEnded}
              crossorigin="anonymous"
              playsinline="false"></audio>

            {data.afterMa3 && (
              <div class={styles.tempVudio}>
                <audio ref={audio1} src={tickMp3} />
                <canvas ref={canvas1}></canvas>
              </div>
            )}
          </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]}>
            <Slider
              step={0.01}
              class={styles.timeProgress}
              v-model={data.currentTime}
              max={data.duration}
              onUpdate:modelValue={val => {
                handleChangeTime(val);
              }}
              onDragStart={() => {
                data.dragStatus = true;
                console.log('onDragStart');
              }}
              onDragEnd={() => {
                data.dragStatus = false;
                console.log('onDragEnd');
              }}
            />
          </div>
          <div class={styles.actions} onClick={() => emit('close')}>
            <div class={styles.actionBtn} onClick={() => onToggleAudio()}>
              <img src={data.playState === 'pause' ? iconplay : iconpause} />
            </div>
            <div
              class={styles.actionBtn}
              onClick={() => {
                data.loop = !data.loop;
                if (data.loop) {
                  setTimeout(() => {
                    showToast('已打开循环播放');
                  }, 60);
                } else {
                  setTimeout(() => {
                    showToast('已关闭循环播放');
                  }, 60);
                }
              }}>
              <img src={data.loop ? iconLoopActive : iconLoop} />
            </div>

            <div class={styles.downloadSpeed}>{data.speedInKbps}</div>
          </div>
        </div>
      </div>
    );
  }
});
