import { ref } from 'vue';

import { message } from 'ant-design-vue';

import { uploadChatFile } from '#/api/core/upload';

export function useRecording() {
  const isRecording = ref(false);
  const mediaRecorder = ref<MediaRecorder | null>(null);
  const audioChunks = ref<Blob[]>([]);
  const recordingStartTime = ref(0);

  const startRecording = () => {
    if (isRecording.value) return;

    navigator.mediaDevices
      .getUserMedia({ audio: true })
      .then((stream) => {
        isRecording.value = true;
        audioChunks.value = [];
        recordingStartTime.value = Date.now();

        // 尝试获取支持的MIME类型
        const options = { mimeType: 'audio/webm' };
        mediaRecorder.value = new MediaRecorder(stream, options);

        mediaRecorder.value.ondataavailable = (event) => {
          audioChunks.value.push(event.data);
        };

        mediaRecorder.value.onstop = () => {
          // 1. 获取实际录制的MIME类型
          const mimeType = mediaRecorder.value?.mimeType || 'audio/webm';

          // 2. 根据MIME类型确定文件扩展名
          const extension = mimeType.includes('webm')
            ? '.webm'
            : mimeType.includes('mp4')
              ? '.mp4'
              : mimeType.includes('ogg')
                ? '.ogg'
                : '.wav';

          // 3. 创建正确类型的Blob
          const audioBlob = new Blob(audioChunks.value, { type: mimeType });

          // 4. 创建带扩展名的文件名
          const fileName = `recording_${Date.now()}${extension}`;
          const duration = Math.floor(
            (Date.now() - recordingStartTime.value) / 1000,
          );

          // 5. 创建File对象（包含文件名和类型）
          const audioFile = new File([audioBlob], fileName, {
            type: mimeType,
            lastModified: Date.now(),
          });

          uploadChatFile({
            file: audioFile, // 使用File对象替代Blob
          })
            .then((res) => {
              // 触发音频消息发送事件
              const event = new CustomEvent('audioRecorded', {
                detail: {
                  url: res.url,
                  duration,
                  blob: audioBlob,
                },
              });
              window.dispatchEvent(event);
            })
            .catch((error) => {
              console.error('上传录音失败:', error);
              message.error('录音上传失败');
            })
            .finally(() => {
              // 确保在任何情况下都停止音频轨道
              stream.getTracks().forEach((track) => track.stop());
            });
        };

        mediaRecorder.value.start();
      })
      .catch((error) => {
        console.error('录音失败:', error);
        message.error('无法访问麦克风，请检查权限设置');
        isRecording.value = false;
      });
  };

  const stopRecording = () => {
    if (!isRecording.value || !mediaRecorder.value) return;

    isRecording.value = false;
    mediaRecorder.value.stop();
  };

  return {
    isRecording,
    startRecording,
    stopRecording,
  };
}
