import Taro from "@tarojs/taro"
import { checkPermission, showAuthModal } from '@/utils/auth'
interface H5RecordResult {
  arrayBuffer?: ArrayBuffer | any;
}
type TOnStopRes = (Taro.RecorderManager.OnStopCallbackResult & H5RecordResult) | null
let audioCtx:Taro.WebAudioContext = Taro.createWebAudioContext();
export const useVoiceRecord = (format: keyof Taro.RecorderManager.Format = 'mp3')=> {
  let recorder = Taro.getRecorderManager()
  let volumeChangeCallback: (volume: number, n:any)=> void
  let recorderStopCallback: (res: TOnStopRes)=> void

  //@ts-ignore
  const analyser = audioCtx.createAnalyser();
  recorder.onStop((res)=> {
    console.log('recorder stop')
    const {
      duration,
    } = res
    if(duration < 1000){
      Taro.showToast({
        title: '录音不能小于 1 秒',
        icon: 'none'
      })
      return
    }
    recorderStopCallback && recorderStopCallback(res)
  })
  recorder.onFrameRecorded(listener => {
      if (listener.isLastFrame) {
          console.log('soundIntensity',0)
      } else {
          //@ts-ignore
          // audioCtx.decodeAudioData(listener.frameBuffer, buffer => {

          //     let source = audioCtx.createBufferSource()
          //     source.buffer = buffer
          //     source.connect(analyser)
          //     source.start()

          //     let n = new Uint8Array(analyser.frequencyBinCount)

          //     analyser.getByteTimeDomainData(n)

          //     let i = 0, r = 0, s = 0

          //     r = Math.max.apply(null, n)

          //     s = Math.min.apply(null, n)

          //     i = (r - s) / 128

          //     i = Math.round(i * 100 / 2)

          //     i = i > 100 ? 100 : i
          //     const volume = listener.isLastFrame ? 0 : i
          //     console.log('soundIntensity', volume)
          //     volumeChangeCallback && volumeChangeCallback(volume, n)
          // }, err => {

          // console.error('decodeAudioData fail', err)

          // })

      }

  })





  const start = async () => {
    const authed = await checkPermission('scope.record')
    if(!authed){
      showAuthModal('需要您允许录音权限')
      recorderStopCallback && recorderStopCallback(null)
      return
    }
    recorder.start({

      duration: 1000 * 60 * 20,

      sampleRate: 16000, //采样率

      numberOfChannels: 1, //录音通道数

      encodeBitRate: 96000, //编码码率

      format: format, //音频格式，有效值 aac/mp3

      frameSize: 1
    })
  }

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

  const stop = ()=> {
    recorder.stop()
  }

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