<template>
  <view class="modal" v-if="visible">
    <view class="modal-content">
      <view class="modal-title">麦克风检测</view>
      <view class="modal-text">请朗读下面的文字</view>
      
      <!-- 语音波形动画 -->
      <view class="wave-container" v-if="isRecording">
        <view class="wave-bar" v-for="(item, index) in waveData" :key="index" 
              :style="{ height: item + 'rpx' }"></view>
      </view>
      
      <!-- 待朗读文字 -->
      <view class="read-text">成为奇才，就是现在，我们开始吧。</view>
      
      <!-- 按钮 -->
      <button class="confirm-btn" @tap="handleConfirm">
        {{ isRecording ? '读完了' : '开始' }}
      </button>
    </view>
  </view>
</template>

<script>
const recorderManager = uni.getRecorderManager();

export default {
  name: 'VoiceCheckModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isRecording: false,
      waveData: Array(20).fill(20), // 初始波形数据
      waveTimer: null
    }
  },
  methods: {
    // 开始录音
    startRecording() {
      this.isRecording = true;
      recorderManager.start({
        duration: 10000,
        sampleRate: 16000,
        numberOfChannels: 1,
        encodeBitRate: 48000,
        format: 'wav'
      });
      
      // 模拟波形动画
      this.waveTimer = setInterval(() => {
        this.waveData = this.waveData.map(() => Math.random() * 40 + 20);
      }, 100);
    },
    
    // 停止录音
    stopRecording() {
      this.isRecording = false;
      recorderManager.stop();
      clearInterval(this.waveTimer);
      this.waveData = Array(20).fill(20);
    },
    
    // 处理确认按钮点击
    handleConfirm() {
      if (!this.isRecording) {
        this.startRecording();
      } else {
        this.stopRecording();
        this.$emit('complete');
      }
    }
  },
  beforeDestroy() {
    clearInterval(this.waveTimer);
  }
}
</script>

<style scoped>
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.modal-content {
  width: 80%;
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  text-align: center;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.modal-text {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 30rpx;
}

.wave-container {
  height: 160rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6rpx;
  margin: 30rpx 0;
}

.wave-bar {
  width: 8rpx;
  background: #0039b3;
  border-radius: 4rpx;
  transition: height 0.1s ease;
}

.read-text {
  background: #f5f5f5;
  padding: 30rpx;
  border-radius: 10rpx;
  font-size: 30rpx;
  margin: 30rpx 0;
}

.confirm-btn {
  width: 80%;
  height: 80rpx;
  line-height: 80rpx;
  background: #0039b3;
  color: #fff;
  border-radius: 40rpx;
  margin-top: 30rpx;
}
</style>