import {
  defineComponent,
  reactive,
  ref,
  nextTick,
  onMounted,
  watch,
  onUnmounted
} from 'vue';
import styles from './audio.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, useMessage } from 'naive-ui';
import Vudio from 'vudio.js';
import tickMp3 from '../image/tick.mp3';

export default defineComponent({
  name: 'audio-play',
  props: {
    item: {
      type: Object,
      default: () => {
        return {};
      }
    },
    activeStatus: {
      type: Boolean,
      default: false
    },
    isEmtry: {
      type: Boolean,
      default: false
    },
    showModel: {
      type: Boolean,
      default: false
    },
    imagePos: {
      type: String,
      default: 'left'
    }
  },
  emits: ['loadedmetadata', 'togglePlay', 'ended', 'reset'],
  setup(props, { emit, expose }) {
    const message = useMessage()
    const audioForms = reactive({
      paused: true,
      speedInKbps: '',
      currentTimeNum: 0,
      isOnline: false,
      currentTime: '00:00',
      durationNum: 0,
      duration: '00:00',
      showBar: true,
      showAction: true,
      afterMa3: true,
      count: 0,
      previousBytesLoaded: 0,
      previousTime: Date.now(),
      // 添加缓冲状态标识
      isBuffering: false,
      bufferTimeout: null as any
    });
    const canvas: any = ref();
    const audio: any = ref();
    let vudio: any = null;
    // const audioSlider =
    //   'audioSlider' + Date.now() + Math.floor(Math.random() * 100);

    // 切换音频播放
    const onToggleAudio = (e?: any) => {
      e?.stopPropagation();
      // console.log(audio.value.paused, 'audio.value.paused');
      if (audio.value.paused) {
        audio.value.play();
        audioForms.afterMa3 = false;
      } else {
        audio.value?.pause();
      }
      audioForms.paused = audio.value?.paused;
      e?.target?.focus();
      emit('togglePlay', audioForms.paused);
    };

    const onInit = (audio: undefined, canvas: undefined) => {
      if (!vudio) {
        vudio = new Vudio(audio, canvas, {
          effect: 'waveform',
          accuracy: 256,
          width: 1024,
          height: 600,
          waveform: {
            maxHeight: 200,
            color: [
              [0, '#44D1FF'],
              [0.5, '#44D1FF'],
              [0.5, '#198CFE'],
              [1, '#198CFE']
            ],
            prettify: false
          }
        });
        vudio.dance();
      }
    };

    // 对时间进行格式化
    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 toggleHideControl = (isShow: false) => {
      audioForms.showBar = isShow;
    };

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

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

    watch(
      () => props.activeStatus,
      (val: any) => {
        // console.log(val, 'val');
        audioForms.count = 0;
        if (val && props.item.autoPlay) {
          vudio = null;
          onToggleAudio();
        } else {
          audio.value.pause();
          audioForms.paused = audio.value?.paused;
        }
      }
    );

    watch(
      () => props.showModel,
      () => {
        // console.log(props.showModel, 'props.showModel')
        audioForms.showAction = props.showModel;
      }
    );

    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`;
          audioForms.speedInKbps = `0 KB/s`;
        }, 1500);
      }

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

      // 获取视频总时长
      let noData = false;
      const onProgress = () => {
        const duration = element.duration;
        const currentTime = Date.now();
        const buffered = element.buffered;
        let currentBytesLoaded = 0;
        const 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;
          }
        });
        // if (duration) {
        //   const sliderDom: any = document.querySelector(
        //     '#' + audioSlider + ' .n-slider'
        //   );
        //   if (sliderDom) {
        //     sliderDom.style.setProperty(
        //       '--catch-width',
        //       uncachedDuration > 0 ? `${currentLength}%` : 'calc(100% + 17px)'
        //     );
        //   }
        // }
        // 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 && audioForms.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) {
                audioForms.speedInKbps = `${Number(
                  (kbps / 1024).toFixed(2)
                )} M/s`;
              } else {
                audioForms.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;
                  audioForms.speedInKbps = '';
                }
              }, 800);
            }

            noData = true;
          }

          if (element.paused || !audioForms.isOnline) {
            clearTimeout(timer);
            audioForms.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 && audioForms.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);
        }
        audioForms.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') {
        audioForms.isOnline = true;
        const currentTime = audio.value.currentTime;
        audio.value.load();
        audio.value.currentTime = currentTime;
        audio.value.pause();
        audioForms.paused = audio.value?.paused;
      } else if (val.type === 'offline') {
        audioForms.isOnline = false;
        console.log('offline');
        // 去掉检测加载缓存
        audioForms.isBuffering = false;
        audioForms.bufferTimeout && clearTimeout(audioForms.bufferTimeout);
      }
    };
    onMounted(() => {
      nextTick(() => {
        calculateSpeed(audio.value);
      });
      window.addEventListener('online', onChangeOnlineStatus);
      window.addEventListener('offline', onChangeOnlineStatus);
    });

    onUnmounted(() => {
      window.removeEventListener('online', onChangeOnlineStatus);
      window.removeEventListener('offline', onChangeOnlineStatus);
    });

    expose({
      toggleHideControl,
      onToggleAudio
    });

    return () => (
      <div class={styles.audioWrap}>
        <div class={styles.audioContainer}>
          <div class={styles.audioTitle}>{props.item.title}</div>
          <audio
            ref={audio}
            crossorigin="anonymous"
            src={props.item.content}
            onEnded={() => {
              audioForms.paused = true;
              emit('ended');
            }}
            onPlay={() => {
              audioForms.paused = audio.value?.paused;
            }}
            onPause={() => {
              // audioForms.paused = audio.value?.paused;
            }}
            onTimeupdate={() => {
              audioForms.currentTime = timeFormat(
                Math.round(audio.value?.currentTime || 0)
              );
              audioForms.currentTimeNum = audio.value?.currentTime || 0;

              if (audioForms.count <= 1) {
                audioForms.count += 1;
                onInit(audio.value, canvas.value);
              }
            }}
            onLoadedmetadata={() => {
              audioForms.duration = timeFormat(
                Math.round(audio.value?.duration)
              );
              audioForms.durationNum = audio.value?.duration;

              if (props.item.autoPlay && audio.value && props.activeStatus) {
                // audio.value.play();
                onToggleAudio();
              }
              if (audio.value) {
                audio.value.stop = () => {
                  audio.value?.pause();
                  audioForms.paused = true;
                  emit('togglePlay', audioForms.paused);
                };
                audio.value.onPlay = () => {
                  audio.value?.play();
                  audioForms.paused = false;
                  onInit(audio.value, canvas.value);
                  emit('togglePlay', audioForms.paused);
                };
              }
              emit('loadedmetadata', audio.value);
            }}
            onWaiting={() => {
              audioForms.isBuffering = true;

              audioForms.bufferTimeout &&
                clearTimeout(audioForms.bufferTimeout);

              // 设置缓冲超时检测（15秒）
              audioForms.bufferTimeout = setTimeout(() => {
                if (audioForms.isBuffering && audioForms.isOnline) {
                  console.log('缓冲超时，暂停播放');
                  audio.value?.pause();
                  audioForms.paused = true;
                  message.info('网络连接不稳定，请检查网络后继续播放', {
                    showIcon: false,
                    render: (props: any) => {
                      return (
                        <div style="background: rgba(0,0,0,.6); color: #fff; border-radius: 8px; padding: 6px 16px;">
                          {props.content}
                        </div>
                      );
                    }
                  });
                  audio.value.currentTime = audio.value.currentTime + 0.01;
                }
              }, 15000);
            }}
            onCanplay={() => {
              audioForms.isBuffering = false;
              audioForms.bufferTimeout && clearTimeout(audioForms.bufferTimeout); // 清除超时检测
            }}
            onError={() => {
              audio.value?.pause();
              audioForms.paused = audio.value?.paused;
            }}></audio>

          <canvas ref={canvas}></canvas>

          {audioForms.afterMa3 && (
            <div class={styles.tempVudio}>
              <audio ref={audio1} src={tickMp3} />
              <canvas ref={canvas1}></canvas>
            </div>
          )}
        </div>

        <div
          class={[
            styles.controls,
            audioForms.showAction ? '' : styles.sectionAnimate
          ]}
          onClick={(e: MouseEvent) => {
            e.stopPropagation();
            emit('reset');
          }}>
          <div class={styles.slider}>
            {props.imagePos !== 'right' && (
              <div class={styles.time}>
                <div
                  class="plyr__time plyr__time--current"
                  aria-label="Current time">
                  {audioForms.currentTime}
                </div>
                <span class={styles.line}>/</span>
                <div
                  class="plyr__time plyr__time--duration"
                  aria-label="Duration">
                  {audioForms.duration}
                </div>
              </div>
            )}

            <NSlider
              value={audioForms.currentTimeNum}
              step={0.01}
              max={audioForms.durationNum}
              tooltip={false}
              onUpdate:value={(val: number) => {
                audio.value.currentTime = val;
                audioForms.currentTimeNum = val;
                audioForms.currentTime = timeFormat(Math.round(val || 0));
              }}
            />
            {props.imagePos === 'right' && (
              <div class={[styles.time, styles.rightTime]}>
                <div
                  class="plyr__time plyr__time--current"
                  aria-label="Current time">
                  {audioForms.currentTime}
                </div>
                <span class={styles.line}>/</span>
                <div
                  class="plyr__time plyr__time--duration"
                  aria-label="Duration">
                  {audioForms.duration}
                </div>
              </div>
            )}
          </div>
          <div class={styles.tools}>
            {props.imagePos === 'right' ? (
              <>
                <div class={styles.actions}>
                  <div class={styles.title}>{props.item.title}</div>
                  {/* <div class={styles.time}>
                    <div
                      class="plyr__time plyr__time--current"
                      aria-label="Current time">
                      {audioForms.currentTime}
                    </div>
                    <span class={styles.line}>/</span>
                    <div
                      class="plyr__time plyr__time--duration"
                      aria-label="Duration">
                      {audioForms.duration}
                    </div>
                  </div> */}
                </div>
                <div class={styles.actions}>
                  <div class={styles.actionWrap}>
                    <div class={styles.downloadSpeed}>
                      {audioForms.speedInKbps}
                    </div>
                    <button class={styles.iconReplay} onClick={onReplay}>
                      <img src={iconReplay} />
                    </button>
                    <div class={styles.actionBtn} onClick={onToggleAudio}>
                      {audioForms.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={onToggleAudio}>
                      {audioForms.paused ? (
                        <img class={styles.playIcon} src={iconplay} />
                      ) : (
                        <img class={styles.playIcon} src={iconpause} />
                      )}
                    </div>
                    <button class={styles.iconReplay} onClick={onReplay}>
                      <img src={iconReplay} />
                    </button>
                    <div class={styles.downloadSpeed}>
                      {audioForms.speedInKbps}
                    </div>
                  </div>
                </div>
                <div class={styles.actions}>
                  <div class={styles.title}>{props.item.title}</div>
                  {/* <div class={styles.time}>
                    <div
                      class="plyr__time plyr__time--current"
                      aria-label="Current time">
                      {audioForms.currentTime}
                    </div>
                    <span class={styles.line}>/</span>
                    <div
                      class="plyr__time plyr__time--duration"
                      aria-label="Duration">
                      {audioForms.duration}
                    </div>
                  </div> */}
                </div>
              </>
            )}
          </div>
        </div>
      </div>
    );
  }
});
