import Taro from "@tarojs/taro";
import { useRef } from "react";

import RecordRTC from "recordrtc";
let recorderStopCallback: (res: any) => void;
let isStop = false;
export const useVoiceRecord = () => {
  // const audioCtxRef = useRef<AudioContext | null>();
  const recorderRef = useRef<RecordRTC | null>(null);
  // const analyserRef = useRef<AnalyserNode | null>(null);
  const streamRef = useRef<MediaStream | null>(null);
  const startRecordingTime = useRef<Date | null>(null);

  // console.log("[ aaaaaaa ] >");
  const start = async () => {
    console.log("[ 开始录音 111 ] >");
    console.log("[ navigator ] >", navigator);
    const stream = await navigator.mediaDevices.getUserMedia({
      audio: true,
      video: false,
    });
    if (!stream) {
      recorderStopCallback && recorderStopCallback(null);
      return;
    }
    console.log('[ 录音初始化完成 ] >', )
    streamRef.current = stream;
    const recorder = new RecordRTC(stream, {
      type: "audio",
      mimeType: "audio/wav",
      recorderType: RecordRTC.StereoAudioRecorder,
      sampleRate: 44100,
      desiredSampRate: 16000,
      numberOfAudioChannels: 1,
    });
    recorderRef.current = recorder;
    recorderRef.current.startRecording();
    startRecordingTime.current = new Date();

    // 小程序是假的频率图，此处暂时不做处理
  };

  const onVolumeChange = (callback: (volume: number, n: any) => void) => {};
  const onStop = (callback: (res: any) => void) => {
    recorderStopCallback = callback;
  };

  const stop = () => {


    if (recorderRef.current && !isStop) {
      console.log("[ 停止录音 ] >");
      isStop = true;
      recorderRef.current.stopRecording(async () => {
        isStop = false;
        const duration =
          new Date().getTime() - startRecordingTime.current!.getTime();

        if (duration < 1000) {
          Taro.showToast({
            title: "录音不能小于 1 秒",
            icon: "none",
          });
        } else {
          // 处理音频数据
          const blob = recorderRef.current?.getBlob?.();

          if (blob) {
            // 测试音频数据
            // const url = URL.createObjectURL(blob);
            // const a = document.createElement("a");
            // a.href = url;
            // a.download = "audio_blob_test.wav";
            // a.click();
            const arrayBuffer = await blob?.arrayBuffer();
            recorderStopCallback &&
              recorderStopCallback({
                arrayBuffer,
              });
          }
        }

        // 清理资源
        // fixme: 这里不能直接 destroy，否则会导致移动端报错
        // recorderRef.current?.destroy?.();
        recorderRef.current = null;
        // if (streamRef.current) {
        //   streamRef.current.getTracks().forEach((track) => {
        //     track.stop();
        //   });
        //   streamRef.current = null;
        // }
      });
    }
  };

  return {
    start,
    stop,
    onVolumeChange,
    onStop,
  };
};
