<template>
  <Theme>
    <view class="record-page">
      <!-- 页面标题 -->
      <view class="page-title">录音留言</view>

      <!-- 录音区域 -->
      <view class="record-section">
        <view
          class="record-area"
          :class="{ recording: isRecording }"
          @click="toggleRecord"
        >
          <view class="record-icon">
            <i class="icon-font icon-microphone"></i>
          </view>
          <view class="record-text">
            {{ isRecording ? "录音中..." : "点击开始录音" }}
          </view>
        </view>
      </view>

      <!-- 录音文件显示区域 -->
      <view class="audio-display" v-if="voicePath">
        <view class="audio-waveform">
          <view
            class="wave-bar"
            v-for="(bar, index) in displayWaveBars"
            :key="index"
            :style="{ height: bar + 'px' }"
          ></view>
        </view>

        <view class="audio-duration">{{ formatTime(recordTime) }}</view>

        <view class="audio-controls">
          <view
            class="control-btn play-btn"
            :class="{ playing: isPlaying }"
            @click="togglePlay"
          >
            <i
              class="icon-font"
              :class="isPlaying ? 'icon-pause' : 'icon-play'"
            ></i>
          </view>

          <view class="control-btn delete-btn" @click="deleteRecord">
            <i class="icon-font icon-delete"></i>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-else>
        <view class="empty-text">暂无录音</view>
      </view>
    </view>
    <Tabbar page="index" />
  </Theme>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import Theme from "@/components/Theme.vue";
import Tabbar from "@/components/tabbar.vue";
import { onShow } from "@dcloudio/uni-app";
// 录音状态
const isRecording = ref(false);
const recordTime = ref(0);
const recordTimer = ref(null);
const voicePath = ref("");

// 播放状态
const isPlaying = ref(false);
let audioContext = null;

// 录音管理器
let recorderManager = null;

// 平台检测
const platform = ref(uni.getSystemInfoSync().platform);
const isH5 = ref(process.env.UNI_PLATFORM === "h5");
const isApp = ref(process.env.UNI_PLATFORM === "app-plus");

// 录音时的波形动画
const waveBars = ref([]);

// 显示时的静态波形
const displayWaveBars = ref([]);

// 开始录音
const startRecord = () => {
  // 检查平台支持
  if (isH5.value) {
    // H5平台使用Web API
    startH5Record();
  } else {
    startAppRecord();
  }
};

// H5录音功能
const startH5Record = () => {
  // 检查浏览器支持
  // if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
  //   uni.showToast({
  //     title: "浏览器不支持录音功能",
  //     icon: "none",
  //   });
  //   return;
  // }

  navigator.mediaDevices
    .getUserMedia({ audio: true })
    .then((stream) => {
      // 创建MediaRecorder
      const mediaRecorder = new MediaRecorder(stream);
      const audioChunks = [];

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

      mediaRecorder.onstop = () => {
        const audioBlob = new Blob(audioChunks, { type: "audio/wav" });
        const audioUrl = URL.createObjectURL(audioBlob);

        // 停止所有音频轨道
        stream.getTracks().forEach((track) => track.stop());

        // 保存录音文件
        saveRecordFile({
          tempFilePath: audioUrl,
          fileSize: audioBlob.size,
        });
      };

      mediaRecorder.onerror = (err) => {
        console.error("H5录音错误", err);
        isRecording.value = false;
        stopRecordTimer();
        stopWaveAnimation();
        uni.showToast({
          title: "录音失败",
          icon: "none",
        });
      };

      // 开始录音
      mediaRecorder.start();
      isRecording.value = true;
      startRecordTimer();
      startWaveAnimation();

      // 保存MediaRecorder引用用于停止
      recorderManager = mediaRecorder;
    })
    .catch((error) => {
      console.error("H5录音权限错误", error);
      uni.showToast({
        title: "需要录音权限",
        icon: "none",
      });
    });
};

// APP录音功能
const startAppRecord = () => {
  try {
    recorderManager = uni.getRecorderManager();

    recorderManager.onStart(() => {
      console.log("录音开始");
      isRecording.value = true;
      startRecordTimer();
      startWaveAnimation();
    });

    recorderManager.onStop((res) => {
      console.log("录音结束", res);
      isRecording.value = false;
      stopRecordTimer();
      stopWaveAnimation();
      saveRecordFile(res);
    });

    recorderManager.onError((err) => {
      console.error("录音错误", err);
      isRecording.value = false;
      stopRecordTimer();
      stopWaveAnimation();
      uni.showToast({
        title: "录音失败",
        icon: "none",
      });
    });

    const options = {
      duration: 60000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 96000,
      format: "mp3",
      frameSize: 50,
    };

    recorderManager.start(options);
  } catch (error) {
    console.error("录音初始化失败", error);
    uni.showToast({
      title: "录音初始化失败",
      icon: "none",
    });
  }
};

// 停止录音
const stopRecord = () => {
  if (recorderManager) {
    if (isH5.value) {
      // H5平台停止MediaRecorder
      recorderManager.stop();
    } else if (isApp.value) {
      // APP平台停止uni.getRecorderManager
      recorderManager.stop();
    }
  }
};

// 切换录音状态
const toggleRecord = () => {
  if (isRecording.value) {
    stopRecord();
  } else {
    startRecord();
  }
};

// 录音计时器
const startRecordTimer = () => {
  recordTime.value = 0;
  recordTimer.value = setInterval(() => {
    recordTime.value++;
  }, 1000);
};

const stopRecordTimer = () => {
  if (recordTimer.value) {
    clearInterval(recordTimer.value);
    recordTimer.value = null;
  }
};

// 波形动画
const startWaveAnimation = () => {
  const animateWave = () => {
    if (isRecording.value) {
      // 创建更真实的波浪效果
      waveBars.value = Array.from({ length: 25 }, (_, index) => {
        // 使用正弦波创建更自然的波浪
        const time = Date.now() / 100;
        const frequency = 0.1 + (index % 3) * 0.05; // 不同频率
        const amplitude = 30 + Math.random() * 20; // 随机振幅
        const baseHeight = 20;

        return (
          baseHeight +
          Math.abs(Math.sin(time * frequency + index * 0.5)) * amplitude
        );
      });
      setTimeout(animateWave, 150);
    }
  };
  animateWave();
};

const stopWaveAnimation = () => {
  waveBars.value = [];
};

// 生成静态波形显示
const generateDisplayWave = () => {
  // 根据录音时长生成静态波形
  const duration = recordTime.value;
  const waveCount = Math.min(30, Math.max(15, duration * 2)); // 根据时长调整波形数量

  displayWaveBars.value = Array.from({ length: waveCount }, (_, index) => {
    // 使用录音时长作为种子，生成固定的波形
    const seed = duration + index;
    const amplitude = 20 + (seed % 40); // 20-60的振幅
    const baseHeight = 15;

    return baseHeight + amplitude;
  });
};

// 保存录音文件
const saveRecordFile = (res) => {
  voicePath.value = res.tempFilePath;

  // 生成静态波形显示
  generateDisplayWave();

  // 保存到本地存储
  uni.setStorageSync("voicePath", voicePath.value);
  uni.setStorageSync("recordTime", recordTime.value);

  uni.showToast({
    title: "录音保存成功",
    icon: "success",
  });
};

// 播放录音
const togglePlay = () => {
  if (isPlaying.value) {
    // 停止播放
    stopPlay();
  } else {
    // 开始播放
    startPlay();
  }
};

// 开始播放
const startPlay = () => {
  if (!voicePath.value) {
    uni.showToast({
      title: "没有录音文件",
      icon: "none",
    });
    return;
  }

  if (isH5.value) {
    // H5平台使用HTML5 Audio
    startH5Play();
  } else if (isApp.value) {
    // APP平台使用uni.createInnerAudioContext
    startAppPlay();
  } else {
    uni.showToast({
      title: "当前平台不支持播放功能",
      icon: "none",
    });
  }
};

// H5播放功能
const startH5Play = () => {
  if (audioContext) {
    audioContext.pause();
    audioContext = null;
  }

  try {
    audioContext = new Audio(voicePath.value);

    audioContext.onplay = () => {
      isPlaying.value = true;
    };

    audioContext.onended = () => {
      isPlaying.value = false;
    };

    audioContext.onerror = (err) => {
      console.error("H5播放错误", err);
      isPlaying.value = false;
      uni.showToast({
        title: "播放失败",
        icon: "none",
      });
    };

    audioContext.play();
  } catch (error) {
    console.error("H5播放初始化失败", error);
    uni.showToast({
      title: "播放功能不支持",
      icon: "none",
    });
  }
};

// APP播放功能
const startAppPlay = () => {
  if (audioContext) {
    audioContext.destroy();
  }

  try {
    audioContext = uni.createInnerAudioContext();
    audioContext.src = voicePath.value;

    audioContext.onPlay(() => {
      isPlaying.value = true;
    });

    audioContext.onEnded(() => {
      isPlaying.value = false;
    });

    audioContext.onError((err) => {
      console.error("APP播放错误", err);
      isPlaying.value = false;
      uni.showToast({
        title: "播放失败",
        icon: "none",
      });
    });

    audioContext.play();
  } catch (error) {
    console.error("APP播放初始化失败", error);
    uni.showToast({
      title: "播放功能不支持",
      icon: "none",
    });
  }
};

// 停止播放
const stopPlay = () => {
  if (audioContext) {
    if (isH5.value) {
      // H5平台停止Audio
      audioContext.pause();
      audioContext = null;
    } else if (isApp.value) {
      // APP平台停止uni.createInnerAudioContext
      audioContext.stop();
      audioContext.destroy();
      audioContext = null;
    }
  }
  isPlaying.value = false;
};

// 删除录音
const deleteRecord = () => {
  uni.showModal({
    title: "确认删除",
    content: "确定要删除这条录音吗？",
    success: (res) => {
      if (res.confirm) {
        // 如果正在播放，先停止
        if (isPlaying.value) {
          stopPlay();
        }

        // 删除录音文件
        if (voicePath.value) {
          if (isH5.value) {
            // H5平台释放Blob URL
            try {
              URL.revokeObjectURL(voicePath.value);
              console.log("H5文件URL释放成功");
            } catch (error) {
              console.error("H5文件URL释放失败", error);
            }
          } else if (isApp.value) {
            // APP平台删除文件
            try {
              uni.getFileSystemManager().unlink({
                filePath: voicePath.value,
                success: () => {
                  console.log("文件删除成功");
                },
                fail: (err) => {
                  console.error("文件删除失败", err);
                },
              });
            } catch (error) {
              console.error("文件删除异常", error);
            }
          }
        }

        // 清除录音数据
        voicePath.value = "";
        recordTime.value = 0;
        displayWaveBars.value = [];

        // 更新本地存储
        uni.removeStorageSync("voicePath");
        uni.removeStorageSync("recordTime");

        uni.showToast({
          title: "删除成功",
          icon: "success",
        });
      }
    },
  });
};

// 格式化时间
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${mins.toString().padStart(2, "0")}:${secs
    .toString()
    .padStart(2, "0")}`;
};

// 提交表单
const submitForm = () => {
  if (!voicePath.value) {
    uni.showToast({
      title: "请先录制语音",
      icon: "none",
    });
    return;
  }

  // 这里可以调用后台接口提交表单数据
  const formData = {
    voiceFile: voicePath.value, // 录音文件路径
    voiceDuration: recordTime.value, // 录音时长
    // 其他表单字段...
  };

  console.log("提交表单数据:", formData);
  uni.showToast({
    title: "表单提交成功",
    icon: "success",
  });

  // 实际项目中这里应该调用API
  // uni.request({
  //   url: 'your-api-url',
  //   method: 'POST',
  //   data: formData,
  //   success: (res) => {
  //     Toast("提交成功");
  //   },
  //   fail: (err) => {
  //     Toast("提交失败");
  //   }
  // });
};

// 加载录音
const loadRecord = () => {
  try {
    const savedVoicePath = uni.getStorageSync("voicePath");
    const savedRecordTime = uni.getStorageSync("recordTime");

    if (savedVoicePath) {
      voicePath.value = savedVoicePath;
      recordTime.value = savedRecordTime || 0;
      generateDisplayWave();
    }
  } catch (error) {
    console.error("加载录音失败", error);
  }
};

onMounted(() => {
  loadRecord();
});

onUnmounted(() => {
  // 清理资源
  stopRecordTimer();
  stopPlay();
});

onShow(() => {
  // 页面显示时重新加载录音
  loadRecord();
});
</script>

<style lang="less" scoped>
.record-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20px;
  padding-bottom: 120rpx;

  .page-title {
    font-size: 18px;
    font-weight: bold;
    color: #000;
    margin-bottom: 20px;
  }

  .record-section {
    margin-bottom: 20px;

    .record-area {
      background: #fff;
      border: 2px solid #007aff;
      border-radius: 12px;
      padding: 20px;
      display: flex;
      align-items: center;
      cursor: pointer;
      transition: all 0.3s ease;

      &.recording {
        border-color: #ff3b30;
        background: #fff5f5;
      }

      .record-icon {
        width: 24px;
        height: 24px;
        margin-right: 12px;
        display: flex;
        align-items: center;
        justify-content: center;

        .icon-font {
          font-size: 24px;
          color: #999;
        }
      }

      .record-text {
        font-size: 16px;
        color: #999;
        flex: 1;
      }
    }
  }

  .audio-display {
    background: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 12px;
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 12px;

    .audio-waveform {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 2px;
      height: 40px;

      .wave-bar {
        width: 3px;
        background: #000;
        border-radius: 1.5px;
        min-height: 4px;
      }
    }

    .audio-duration {
      font-size: 16px;
      color: #000;
      font-weight: 500;
      min-width: 50px;
      text-align: center;
    }

    .audio-controls {
      display: flex;
      gap: 8px;

      .control-btn {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: all 0.2s ease;

        &.play-btn {
          background: #000;

          &.playing {
            background: #ff3b30;
          }

          .icon-font {
            font-size: 14px;
            color: #fff;
          }
        }

        &.delete-btn {
          background: #ff3b30;

          .icon-font {
            font-size: 14px;
            color: #fff;
          }
        }

        &:active {
          transform: scale(0.95);
        }
      }
    }
  }

  .empty-state {
    background: #fff;
    border: 1px solid #e0e0e0;
    border-radius: 12px;
    padding: 40px 20px;
    text-align: center;

    .empty-text {
      font-size: 16px;
      color: #999;
    }
  }
}

// 录音时的脉冲动画
@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.recording {
  animation: pulse 1.5s infinite;
}
</style>