// https://github.com/xiangyuecn/Recorder

import Recorder from "recorder-core";
//需要使用到的音频格式编码引擎
import 'recorder-core/src/engine/mp3'
import 'recorder-core/src/engine/mp3-engine'
//可选的扩展编码引擎
import 'recorder-core/src/extensions/waveview'

/*const videoConfig = {
    type: 'mp3',
    bitRate: 16,
    sampleRate: 16000,
    duration: 0,
    durationTxt: "0",
    powerLevel: 0,
    logs: []
}*/
export const useRecording = () => {
  let recorderInstance = null;
  let inRecording = ref(false)
  const openPermission = () => {
    return new Promise((resolve, reject) => {
      if (recorderInstance && Recorder.IsOpen()) resolve()
      if (!recorderInstance) {
        recorderInstance = Recorder({
          type: 'mp3',
          bitRate: 16,
          sampleRate: 16000,
          duration: 0,
          onProcess: function (buffers, powerLevel, duration, sampleRate) {
            console.log('录制中~')
            inRecording.value = true
          }
        });
        recorderInstance.open(
          () => {
            resolve()
          },
          () => {
            reject()
          }
        )
        return
      }
      if (!Recorder.IsOpen()) {
        recorderInstance.open(
          () => {
            resolve()
          },
          () => {
            reject()
          }
        )
        return;
      }
    })
  }

  const startRecording = async () => {
    try {
      await openPermission()
      recorderInstance.start()
    } catch (e) {
      console.error(e, 'startRecording')
    }
  }
  const stopRecording = async () => {
    return new Promise((resolve, reject) => {
      if (!recorderInstance || !Recorder.IsOpen()) {
        console.log('未开启录音！')
        resolve({
          success: false,
          errorMessage: '未开启录音'
        })
      }

      recorderInstance.stop(
        (blob, duration) => {
          inRecording.value = false
          console.log('----录制完成-----', blob, duration)
          if ((duration / 1000) < 1) {
            console.log(duration, '录音小于一秒')
            resolve({
              success: false,
              errorMessage: '说话时间太短'
            })
          } else {
            console.log(duration, '录音合格')
            resolve({
              success: true,
              audio: {
                blob: blob,
                duration: duration,
                durationTxt: formatMs(duration),
                href: (window.URL || webkitURL).createObjectURL(blob)
              },
              errorMessage: ''
            })
            /*const o = {
              blob: blob,
              duration: duration,
              durationTxt: formatMs(duration),
              rec: recorderInstance
            }
            let name = "rec-" + o.duration + "ms-" + (o.rec.set.bitRate || "-") + "kbps-" + (o.rec.set.sampleRate || "-") + "hz." + (o.rec.set.type || (/\w+$/.exec(o.blob.type) || [])[0] || "unknown");
            let downA = document.createElement("A");
            downA.href = (window.URL || webkitURL).createObjectURL(o.blob);
            downA.download = name;
            downA.click();
            alert('下载成功')*/
          }
        },
        (e) => {
          inRecording.value = false
          resolve({
            success: false,
            errorMessage: e
          })
        }
      )
    })
  }
  const cancelRecording = async () => {
    return new Promise((resolve) => {
      if (!recorderInstance || !Recorder.IsOpen()) {
        console.log('未开启录音！')
        resolve({
          success: true,
          errorMessage: ''
        })
      }

      recorderInstance.stop(
        (blob, duration) => {
          inRecording.value = false
          resolve({
            success: true,
            errorMessage: ''
          })

        },
        (e) => {
          inRecording.value = false
          resolve({
            success: false,
            errorMessage: e
          })
        }
      )
    })
  }
  const formatMs = (ms, all) => {
    let ss = ms % 1000;
    ms = (ms - ss) / 1000;
    let s = ms % 60;
    ms = (ms - s) / 60;
    let m = ms % 60;
    ms = (ms - m) / 60;
    let h = ms;
    let t = (h ? h + ":" : "")
      + (all || h + m ? ("0" + m).substr(-2) + ":" : "")
      + (all || h + m + s ? ("0" + s).substr(-2) + "″" : "")
      + ("00" + ss).substr(-3);
    return t;
  }

  const closeRecording = () => {
    recorderInstance && recorderInstance.close()
  }

  onUnmounted(() => {
    closeRecording()
  })
  return {
    inRecording, // 是否在录音中
    openPermission,// 开启录音系统权限
    startRecording,// 开始录音
    stopRecording,// 停止录音
    cancelRecording,//  取消录音
    closeRecording,// 关闭录音权限
  }

}