<template>
  <view class="content">
    <view class="header">
      <text class="title">Sherpa-onnx ASR 调试</text>
    </view>
    
    <view class="controls">
      <button class="btn" @click="init">1. 初始化模型</button>
      <button class="btn primary" @click="start">2. 开始录音</button>
      <button class="btn danger" @click="stop">3. 停止录音</button>
    </view>

    <view class="result-box">
      <text class="label">识别结果：</text>
      <text class="result-text">{{ resultText }}</text>
    </view>
    
    <view class="log-box">
      <text class="log-text">{{ logText }}</text>
    </view>
  </view>
</template>

<script lang="uts">
	import { initModel,requestAudioPermission,startRecording,stopRecording,disposeModel } from '../../uni_modules/ak-onnx/utssdk/app-android';
export default {
  data() {
    return {
      resultText: "等待录音...",
      logText: "准备就绪"
    }
  },
  onLoad() {
    this.log("页面加载，请求录音权限...");
    // #ifdef APP-ANDROID
    requestAudioPermission((granted: boolean) => {
      if (granted) {
        this.log("录音权限已授予");
      } else {
        this.log("录音权限被拒绝，请在设置中手动开启");
      }
    });
    // #endif
  },
  onUnload() {
    disposeModel
  },
  methods: {
    log(msg: string) {
      console.log(msg);
      this.logText = msg + "\n" + this.logText;
    },
    init() {
      this.log("正在初始化模型...");
      // 异步执行以防阻塞 UI
      setTimeout(() => {
        try {
			initModel();
          this.log("模型初始化成功！");
        } catch (e) {
          this.log("初始化失败: " + (e as Error).message);
        }
      }, 100);
    },
    start() {
      this.log("开始录音...");
      this.resultText = "";
      startRecording((text: string) => {
        this.resultText = text;
      });
    },
    stop() {
      stopRecording();
      this.log("录音已停止");
    }
  }
}
</script>

<style>
.content {
  padding: 20px;
  display: flex;
  flex-direction: column;
}
.header {
  margin-bottom: 20px;
  align-items: center;
}
.title {
  font-size: 20px;
  font-weight: bold;
}
.controls {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 20px;
}
.btn {
  width: 100%;
}
.primary {
  background-color: #007aff;
  color: white;
}
.danger {
  background-color: #dd524d;
  color: white;
}
.result-box {
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 8px;
  min-height: 100px;
  margin-bottom: 20px;
}
.label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}
.result-text {
  font-size: 18px;
  color: #333;
}
.log-box {
  padding: 10px;
  background-color: #333;
  border-radius: 5px;
  min-height: 100px;
}
.log-text {
  font-size: 12px;
  color: #0f0;
}
</style>
