// src/utils/wechat.js - 微信录音工具

import wx from 'weixin-js-sdk'
import { getSignature } from "@/api";
import { h5Url } from '@/common/config.js';

/**
 * 初始化微信 JS-SDK（包含录音功能）
 */
export async function initWechatSDKWithRecorder() {
  return new Promise((resolve, reject) => {
    if (typeof wx === 'undefined') {
      reject(new Error('微信 JS-SDK 未加载'));
      return;
    }
    let url = `${h5Url}/`
    getSignature({ url:url}).then(res => {
      const config = res.data;
      
      wx.config({
        debug: false,
        appId: config.appId,
        timestamp: config.timestamp,
        nonceStr: config.nonceStr,
        signature: config.signature,
        jsApiList: [
          // 分享功能
          'updateAppMessageShareData',
          'updateTimelineShareData',
          // 录音功能
          'startRecord',
          'stopRecord',
          'onVoiceRecordEnd',
          'playVoice',
          'pauseVoice',
          'stopVoice',
          'uploadVoice',
          'downloadVoice'
        ]
      });

      wx.ready(() => {
        console.log('微信 JS-SDK 初始化成功（含录音）');
        resolve();
      });

      wx.error((err) => {
        console.error('微信 JS-SDK 初始化失败:', err);
        reject(err);
      });
    }).catch(err => {
      reject(err);
    });
  });
}

/**
 * 微信录音管理器
 */
class WechatRecorder {
  constructor() {
    this.isRecording = false;
    this.localId = null;
    this.serverId = null;
    
    // 事件回调
    this.callbacks = {
      onStart: null,
      onStop: null,
      onError: null,
      onUpload: null
    };
  }

  /**
   * 开始录音
   */
  startRecording(callback) {
    if (this.isRecording) {
      callback && callback({ errMsg: '录音已在进行中' });
      return;
    }

    // 设置录音自动结束监听（最长60秒）
    wx.onVoiceRecordEnd({
      success: (res) => {
        this.localId = res.localId;
        this.isRecording = false;
        this.callbacks.onStop && this.callbacks.onStop({ localId: this.localId });
      }
    });

    wx.startRecord({
      success: () => {
        this.isRecording = true;
        this.localId = null;
        this.callbacks.onStart && this.callbacks.onStart();
        callback && callback(null, '开始录音');
      },
      cancel: () => {
        this.isRecording = false;
        callback && callback({ errMsg: '用户取消录音' });
      },
      fail: (err) => {
        this.isRecording = false;
        this.callbacks.onError && this.callbacks.onError(err);
        callback && callback(err);
      }
    });
  }

  /**
   * 停止录音
   */
  stopRecording(callback) {
    if (!this.isRecording) {
      callback && callback({ errMsg: '未在录音中' });
      return;
    }

    wx.stopRecord({
      success: (res) => {
        this.localId = res.localId;
        this.isRecording = false;
        this.callbacks.onStop && this.callbacks.onStop({ localId: this.localId });
        callback && callback(null, { localId: this.localId });
      },
      fail: (err) => {
        this.isRecording = false;
        this.callbacks.onError && this.callbacks.onError(err);
        callback && callback(err);
      }
    });
  }

  /**
   * 播放录音
   */
  playVoice(localId, callback) {
    if (!localId) {
      callback && callback({ errMsg: '请先录制音频' });
      return;
    }

    wx.playVoice({
      localId: localId,
      success: () => {
        callback && callback(null);
      },
      fail: (err) => {
        callback && callback(err);
      }
    });
  }

  /**
   * 上传录音到微信服务器
   */
  uploadVoice(localId, callback) {
    if (!localId) {
      callback && callback({ errMsg: '请先录制音频' });
      return;
    }

    wx.uploadVoice({
      localId: localId,
      isShowProgressTips: 1,
      success: (res) => {
        this.serverId = res.serverId;
        this.callbacks.onUpload && this.callbacks.onUpload({ serverId: this.serverId });
        callback && callback(null, { serverId: this.serverId });
      },
      fail: (err) => {
        callback && callback(err);
      }
    });
  }

  /**
   * 设置事件监听
   */
  on(event, callback) {
    if (this.callbacks[event]) {
      this.callbacks[event] = callback;
    }
  }
}

// 创建单例
const wechatRecorder = new WechatRecorder();

export { wechatRecorder };