/* eslint-disable no-lone-blocks */
import React, { useEffect, useRef, useState } from 'react';
import Audio from './Audio';
import { AudioPlayerContainer } from './styled';
import { docPlayerHooks } from '../../../../../../documentModel';
import {
  FileModel,
  markColorsMap,
  ON_SEEKING_CHANGE,
  SETAUDIORSSINFO,
} from '../../../../../../pages/docASR/utils/config';
import bus from '../../../../../../utils/bus';
import {
  CHANGE_AUDIO_HLTMARKSEGINDEX,
  CHANGE_AUDIO_MUTED,
  CHANGE_AUDIO_PAUSE,
  CHANGE_AUDIO_PLAY,
  CHANGE_AUDIO_SKIPBLANK,
  CHANGE_AUDIO_SPEED,
  CHANGE_AUDIO_TIME,
  CHANGE_AUDIO_VOLUME,
} from './audioEvents';

const AudioPlayer = (props: any) => {
  const {
    playbackUrl, // 音频资源
    // audioSegments, // 空白帧
    spectrum, // 音波
    markTokens, // 打标
    titleGenerator, // 章节速览
    shortcutKey = false, // 快捷键开关
    onTimeUpdate = () => {},
    onSeekingToTime = () => {},
    playNext = {},
    playBack = {},
    playChange = {},
    onVolumeChange = () => {},
    onSpeedChange = () => {},
    yuqueVisible = true,
    onReady,
    onSkipBlankSegment = () => {}, // 跳过空白区域
    model,
    rssItemInfo,
    jumpTipsTime,
  } = props;

  const { docPlayerData } = docPlayerHooks.useDocPlayerData();
  const [audio, setAuido] = useState<any>();
  const audioSegmentsRef = useRef<any>([]);
  const modelRef = useRef<any>(model);
  modelRef.current = model;

  useEffect(() => {
    if (docPlayerData) {
      const { audioSegments } = docPlayerData;
      try {
        audioSegmentsRef.current = JSON.parse(String(audioSegments));
      } catch {
        audioSegmentsRef.current = [];
      }
    }
  }, [docPlayerData]);

  // 跳过空白帧
  // eslint-disable-next-line @typescript-eslint/no-shadow
  const onChangeTime = (currentTime: number, audio: any) => {
    onTimeUpdate(currentTime);
    if (audio?.skipBlank) {
      const times = audioSegmentsRef.current.find(
        (item: number[], index: number) => {
          const prevEndTime = audioSegmentsRef.current[index - 1]?.[1] || 0;
          return (
            currentTime * 1000 > prevEndTime && currentTime * 1000 < item[0]
          );
        },
      );
      if (times) {
        const newStartTime = times[0];
        // 超过 100ms 才跳过空白片段
        if (newStartTime - currentTime * 1000 > 100) {
          onSeek(audio, times[0] / 1000);
        }
      }
    }
  };

  // 指定seek、前一句、后一句
  // eslint-disable-next-line @typescript-eslint/no-shadow
  const onSeek = (audio: any, time: number, type = '') => {
    bus.emit(ON_SEEKING_CHANGE);
    if (audio) {
      switch (type) {
        case '':
          {
            audio.onChangePlayTime(time);
            onSeekingToTime(time);
          }
          break;
        case 'prev':
          {
            playBack(time);
          }
          break;
        case 'next':
          {
            playNext(time);
          }
          break;
        default:
          break;
      }
    }
  };

  const onChangePlayCbk = (play: boolean) => {
    playChange(play);
  };

  // eslint-disable-next-line @typescript-eslint/no-shadow
  const onChangeVolumeCbk = (audio: any) => {
    const { volume, muted } = audio;
    onVolumeChange(volume, muted);
  };

  // eslint-disable-next-line @typescript-eslint/no-shadow
  const onChangeSpeedCbk = (audio: any) => {
    const rate = audio.playbackRate;
    onSpeedChange(rate);
  };

  const onChangeSkipBlankCbk = (checked: boolean) => {
    onSkipBlankSegment(checked);
  };

  useEffect(() => {
    // if (getAudioBarParams().isExpendAudioBar) return;

    audio?.Plugins?.controls?.setJumpTipsTime(jumpTipsTime);
  }, [jumpTipsTime, audio]);

  // 初始化音频播放器,不可以监听任何值，只能初始化一次
  useEffect(() => {
    const dom = document.getElementById('audio');
    if (dom) {
      const newMarkPointList = markTokens?.map((item: any) => {
        return {
          ...item,
          color: markColorsMap?.get(item.color)?.color,
        };
      });
      const controls = {
        // 打标
        markPointList: newMarkPointList || [],
        // 章节速览
        markSegmentList: titleGenerator || [],
        // 音波
        spectrum,
        audioRateList: [2, 1.5, 1.25, 1, 0.75],
      };

      const audioIns: any = new Audio(
        dom,
        {
          id: 'audio_player',
          src: playbackUrl,
          autoplay: false,
          volume: 1,
          muted: false,
          controls,
        },
        model,
        rssItemInfo,
      );

      audioIns.onChangeTime = onChangeTime;
      audioIns.onSeek = onSeek;
      audioIns.onChangePlayCbk = onChangePlayCbk;
      audioIns.onChangeVolumeCbk = onChangeVolumeCbk;
      audioIns.onChangeSpeedCbk = onChangeSpeedCbk;
      audioIns.onChangeSkipBlankCbk = onChangeSkipBlankCbk;
      setAuido(audioIns);

      return () => {
        if (audioIns) {
          audioIns.onDestory();
        }
      };
    }
  }, []);

  useEffect(() => {
    if (audio && playbackUrl) {
      audio.onChangeSrc(playbackUrl);
    }
  }, [audio, playbackUrl]);

  useEffect(() => {
    if (audio && rssItemInfo) {
      bus.emit(SETAUDIORSSINFO, rssItemInfo);
    }
  }, [audio, rssItemInfo]);

  // 设置打标
  useEffect(() => {
    if (audio && markTokens) {
      const newMarkPointList = markTokens?.map((item: any) => {
        return {
          ...item,
          color: markColorsMap?.get(item.color)?.color,
        };
      });
      setTimeout(() => {
        audio.Plugins?.controls?.setMarkPointList(newMarkPointList);
      }, 100);
    }
  }, [audio, markTokens]);

  const agendaRef: {
    current: { agendaList: any[]; agendasSummaryList: any[] };
  } = React.useRef<any>({
    agendaList: undefined,
    agendasSummaryList: undefined,
  });

  // 设置章节速览
  useEffect(() => {
    const { agendaList, agendasSummaryList } = agendaRef.current;
    if (audio && agendaList) {
      audio.Plugins?.controls?.setMarkSegmentList(agendaList);
    }
    if (audio && agendaList && agendasSummaryList) {
      const _titleGenerator = agendaList.map((item: any) => {
        const _item = item;

        _item.agendaSummary = agendasSummaryList.find(
          (i: any) => Number(i.id) === Number(item.id),
        );
        return _item;
      });
      audio.Plugins?.controls?.setMarkSegmentList(_titleGenerator);
    }
  }, [
    audio,
    agendaRef.current.agendaList,
    agendaRef.current.agendasSummaryList,
  ]);

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const changeAudioTime = (time: number, type: string) => {
    // 单位是s
    if (audio) {
      audio.onChangePlayTime(time);
      onSeekingToTime(time);
    }
  };

  const changeAudioPlay = () => {
    if (audio) {
      const { Plugins } = audio;
      const { controls } = Plugins;
      // if (audio?.playStatus) {
      //   audio.onPause();
      //   controls.mediaControllerRef.current.setPaused(true);
      // } else {
      audio.onPlay();
      controls.mediaControllerRef.current.setPaused(false);
      playChange(true);
      // }
    }
  };
  const changeAudioPause = () => {
    if (audio) {
      const { Plugins } = audio;
      const { controls } = Plugins;
      // if (audio?.playStatus) {
      //   audio.onPause();
      //   controls.mediaControllerRef.current.setPaused(true);
      // } else {
      audio.onPause();
      controls.mediaControllerRef.current.setPaused(true);
      playChange(false);
      // }
    }
  };

  const changeAudioVolume = (volume: number) => {
    if (audio) {
      const { Plugins } = audio;
      const { controls } = Plugins;
      audio.onChangeVolume(volume);
      controls.mediaControllerRef.current.setVolume(volume * 100);
    }
  };

  const changeAudioMuted = (value: number) => {
    if (audio) {
      const { Plugins } = audio;
      const { controls } = Plugins;
      audio.onMuted(value);
      controls.mediaControllerRef.current.SetMuted(value);
    }
  };

  const changeAudioSpeed = (speed: number) => {
    if (audio) {
      const { Plugins } = audio;
      const { controls } = Plugins;
      audio.onChangePlaybackRate(speed);
      controls.mediaControllerRef.current.setSpeed(speed);
    }
  };

  const changeAudioSkipBlank = (skipBlank: boolean) => {
    if (audio) {
      const { Plugins } = audio;
      const { controls } = Plugins;
      if (controls.mediaControllerRef.current) {
        audio.onChangeSkipBlank(skipBlank);
        controls.mediaControllerRef.current?.setSkipBlank(skipBlank);
      } else {
        setTimeout(() => {
          changeAudioSkipBlank(skipBlank);
        }, 100);
      }
    }
  };

  const changeAudiohltMarkSegIndex = (index: number) => {
    if (audio) {
      const { Plugins } = audio;
      const { controls } = Plugins;
      controls.highlightMark('segment', index);
    }
  };

  // 事件绑定
  useEffect(() => {
    if (audio) {
      bus.on(CHANGE_AUDIO_TIME, changeAudioTime); // 指定播放器时间、前一句、后一句
      bus.on(CHANGE_AUDIO_PLAY, changeAudioPlay); // 播放
      bus.on(CHANGE_AUDIO_PAUSE, changeAudioPause); // 暂停
      bus.on(CHANGE_AUDIO_VOLUME, changeAudioVolume); // 音量
      bus.on(CHANGE_AUDIO_MUTED, changeAudioMuted); // 静音
      bus.on(CHANGE_AUDIO_SPEED, changeAudioSpeed); // 倍速
      bus.on(CHANGE_AUDIO_SKIPBLANK, changeAudioSkipBlank); // 跳过空白帧
      bus.on(CHANGE_AUDIO_HLTMARKSEGINDEX, changeAudiohltMarkSegIndex); // 章节速览高亮
      onReady && onReady();
      return () => {
        bus.off(CHANGE_AUDIO_TIME, changeAudioTime);
        bus.off(CHANGE_AUDIO_PLAY, changeAudioPlay);
        bus.off(CHANGE_AUDIO_PAUSE, changeAudioPause);
        bus.off(CHANGE_AUDIO_VOLUME, changeAudioVolume);
        bus.off(CHANGE_AUDIO_MUTED, changeAudioMuted); // 静音
        bus.off(CHANGE_AUDIO_SPEED, changeAudioSpeed);
        bus.off(CHANGE_AUDIO_SKIPBLANK, changeAudioSkipBlank);
        bus.off(CHANGE_AUDIO_HLTMARKSEGINDEX, changeAudiohltMarkSegIndex);
      };
    }
  }, [audio]);

  useEffect(() => {
    if (audio) {
      const { Plugins } = audio;
      const { controls } = Plugins;
      setTimeout(() => {
        controls?.toggleShortcutKey(shortcutKey);
      }, 100);
    }

    return () => {
      if (audio) {
        const { Plugins } = audio;
        const { controls } = Plugins;
        controls?.toggleShortcutKey(false);
      }
    };
  }, [shortcutKey, audio]);
  return (
    <AudioPlayerContainer
      style={{
        maxWidth: '100%',
        paddingRight: yuqueVisible ? (model === FileModel.Box ? 36 : 40) : 0,
        paddingLeft: model === FileModel.Box ? 36 : 32,
        height: model === FileModel.Box ? '100%' : 97,
      }}
    >
      <div id="audio" />
    </AudioPlayerContainer>
  );
};

export default AudioPlayer;
