import { onUnmounted, ref } from "vue"

export function useChatRecordInput(options: {
  onRecognize: (text: string) => void;
  onError: (error: any) => void;
}) {
  const isRecording = ref(false)
  const recognizedText = ref('')
  let recordManager = null

  // --- 初始化 ---
  // #ifdef MP-WEIXIN
  // 引入微信同声传译插件
  const plugin = requirePlugin('WechatSI')
  recordManager = plugin.getRecordRecognitionManager()
  recordManager.onStart = () => {
    console.log('录音开始')
    isRecording.value = true
    recognizedText.value = '' // 开始新一次识别，清空旧结果
  }

  // 监听识别结束
  recordManager.onStop = (res: any) => {
    console.log('录音结束，最终结果:', res)
    isRecording.value = false
    recognizedText.value = res.result
    options.onRecognize(res.result)
  }
  // 监听错误
  recordManager.onError = (res: any) => {
    console.error('识别出错:', res)
    isRecording.value = false
    uni.showToast({ title: '识别失败', icon: 'none' })
    options.onError(res.msg)
  }
  // #endif

  // --- 事件处理 ---
  const handleTouchStart = () => {
    // #ifdef MP-WEIXIN
    if (isRecording.value) return
    recordManager.start({
      duration: 30000, // 最长录音时长，单位ms
      lang: 'zh_CN'    // 识别语言
    })
    // #endif
  }
  const handleTouchEnd = () => {
    // #ifdef MP-WEIXIN
    if (!isRecording.value) return
    recordManager.stop()
    // #endif
  }

  // --- 组件卸载清理 ---
  onUnmounted(() => {
    // 组件销毁时，确保停止录音，避免异常
    if (isRecording.value && recordManager) {
      recordManager.stop()
    }
  })

  return {
    isRecording,
    handleTouchStart,
    handleTouchEnd,
  }
}