<template>
  <view class="uni-flex-item">
    <web-view id="web-view" class="uni-flex-item" :src="src" :webview-styles="webview_styles" @message="message"
      @error="error" @loading="loading" @loaded="loaded" @download="download">
    </web-view>
    <view class="uni-padding-wrap uni-common-mt">
      <view class="uni-input-v">
        <input class="uni-input" confirmType="go" placeholder="输入网址跳转" @confirm="confirm" />
      </view>
      <view class="uni-row uni-btn-v">
        <button class="uni-flex-item" type="primary" @click="back">后退</button>
        <button class="uni-btn-ml uni-flex-item" type="primary" @click="forward">前进</button>
      </view>
      <view class="uni-row uni-btn-v">
        <button class="uni-flex-item" type="primary" @click="reload">重新加载</button>
        <button class="uni-btn-ml uni-flex-item" type="primary" @click="stop">停止加载</button>
      </view>
      <view class="uni-btn-v">
        <button type="primary" @click="nativeToWeb">原生和Web通信</button>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        src: 'https://www.dcloud.io',
        webview_styles: {
          progress: {
            color: '#FF3333'
          }
        },
        webviewContext: null as WebviewContext | null,
        loadError: false
      }
    },
    onReady() {
      this.webviewContext = uni.createWebviewContext('web-view', this)
    },
    methods: {
      back() {
        this.webviewContext?.back();
      },
      forward() {
        this.webviewContext?.forward();
      },
      reload() {
        this.webviewContext?.reload();
      },
      stop() {
        this.webviewContext?.stop();
      },
      nativeToWeb() {
        this.webviewContext?.evalJS("alert('hello uni-app x')");
      },
      message(event : WebViewMessageEvent) {
        console.log(JSON.stringify(event));
      },
      error(event : WebViewErrorEvent) {
        this.loadError = true
        console.log(JSON.stringify(event));
      },
      loading(event : WebViewLoadingEvent) {
        console.log(JSON.stringify(event));
      },
      loaded(event : WebViewLoadedEvent) {
        console.log(JSON.stringify(event));
      },
      download(event : WebViewDownloadEvent) {
        console.log(JSON.stringify(event));
        uni.showModal({
          content: "下载链接: " + event.detail.url + "\n文件大小: " + event.detail.contentLength / 1024 + "KB",
          showCancel: false
        });
      },
      confirm(event : InputConfirmEvent) {
        console.log(JSON.stringify(event));
        let url = event.detail.value;
        if (!url.startsWith('https://') && !url.startsWith('http://')) {
          url = 'https://' + url;
        }
        this.src = url;
      }
    }
  }
</script>

<style>
  .uni-input-v {
    padding: 10rpx 0;
  }

  .uni-btn-ml {
    margin-left: 10rpx;
  }
</style>
