<template>
  <view class="web-view-container">
    <web-view 
      :src="webUrl" 
      @load="onWebLoad" 
      @error="onWebError"
      @message="onWebMessage"
    ></web-view>
    <!-- 设置按钮：点击进入服务器配置页面 -->
    <view class="fab-btn" @tap="goSettings">⚙</view>
  </view>
</template>

<script>
const modal = uni.requireNativePlugin('modal');
const SpeechTTS = uni.requireNativePlugin('MT-TTS-Speech');
export default {
  data() {
    return {
      webUrl: '',
    };
  },
  onLoad() {
    // 防御性检查：确保 ip/port 存在
    // #ifdef APP-PLUS
    var ip = plus.storage.getItem("ip");
    var port = plus.storage.getItem("port");
    if (!ip || !port) {
      uni.showModal({
        title: '提示',
        content: '服务器地址未配置，请先配置',
        showCancel: false,
        success: () => {
          uni.redirectTo({ url: '/pages/sample/settings' });
        }
      });
      return;
    }
    this.webUrl = 'http://' + ip + ':' + port + '/login_pda';
    // #endif
    this.speak_init();
  },
  onShow() {
    // 从 settings 页面返回时，重新加载 webUrl
    // #ifdef APP-PLUS
    var ip = plus.storage.getItem("ip");
    var port = plus.storage.getItem("port");
    if (ip && port) {
      var newUrl = 'http://' + ip + ':' + port + '/login_pda';
      if (this.webUrl !== newUrl) {
        this.webUrl = newUrl;
      }
    }
    // #endif
  },
  onUnload() {
    SpeechTTS.destroy();
  },
  methods: {
    speak_init() {
      SpeechTTS.init((callback) => {
        SpeechTTS.setEngine("com.google.android.tts");
        SpeechTTS.setPitch(50);
        SpeechTTS.setSpeed(65);
      });
      SpeechTTS.onDone((res) => {
        console.log("语音播报结束:", res);
      });
    },
    onWebLoad(e) {
      console.log('网页加载完成:', e.detail.url);
    },
    
    onWebError(e) {
      console.error('网页加载失败:', e);
      uni.showToast({
        title: '网页加载失败，请检查地址', 
        icon: 'none', 
        duration: 2000
      });
    },
    
    onWebMessage(e) {
      console.log('收到网页消息1:', e.detail);
      if (e.detail && e.detail.data) {
        const msgData = e.detail.data[0]
        SpeechTTS.speak({
          text: msgData.text,
        });
        modal.toast({
          message: msgData.text,
          duration: 6,
        });
      }
    },
    goSettings() {
      uni.navigateTo({ url: '/pages/sample/settings' });
    }
  }
};
</script>

<style scoped>
.web-view-container {
  width: 100vw;
  height: 100vh;
  margin: 0 !important;
  padding: 0 !important;
  position: relative;
}
uni-web-view, web-view {
  width: 100%;
  height: 100%;
  margin: 0 !important;
  padding: 0 !important;
}
.fab-btn {
  position: fixed;
  right: 20px;
  bottom: 40px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 24px;
  text-align: center;
  line-height: 50px;
  z-index: 999;
}
</style>