<template>
  <view class="uni-flex-item">
    <web-view id="web-view" class="uni-flex-item" :style="{ 'pointer-events': pointerEvents }" :src="src"
      :webview-styles="webview_styles" :horizontalScrollBarAccess="horizontalScrollBarAccess" :verticalScrollBarAccess="verticalScrollBarAccess" :bounces="bounces" @message="message" @error="error" @loading="loading"
      @load="load" @download="download" @touchstart="touchstart" @tap="tap">
    </web-view>
    <!-- #ifdef APP -->
    <view class="uni-padding-wrap uni-common-mt">
      <view class="uni-btn-v">
        <input class="uni-input" confirmType="go" placeholder="输入网址跳转" @confirm="confirm" maxlength="-1" />
      </view>
      <view class="uni-row uni-btn-v">
        <button class="uni-flex-item" type="primary" :disabled="!canGoBack" @click="back">后退</button>
        <button class="margin-left-5 uni-flex-item" type="primary" :disabled="!canGoForward"
          @click="forward">前进</button>
      </view>
      <view class="uni-row uni-btn-v">
        <button class="uni-flex-item" type="primary" @click="reload">重新加载</button>
        <button class="margin-left-5 uni-flex-item" type="primary" @click="stop">停止加载</button>
      </view>
      <!-- #ifndef APP-HARMONY -->
      <!-- TODO harmony 执行 alert 无反应 -->
      <view class="uni-btn-v">
        <button type="primary" @click="nativeToWeb">原生和Web通信</button>
      </view>
      <!-- #endif -->
      <view class="uni-btn-v">
        <navigator url="/pages/component/web-view/web-view-scroll">
          <button type="primary">scroll-view嵌套web-view</button>
        </navigator>
      </view>
      <!-- #ifdef APP-ANDROID || APP-HARMONY || APP-IOS -->
      <view class="uni-row uni-btn-v">
        <view class="uni-row uni-flex-item align-items-center">
          <text>显示横向滚动条</text>
          <switch :checked="true" @change="changeHorizontalScrollBarAccess"></switch>
        </view>
        <view class="uni-row uni-flex-item align-items-center">
          <text>显示竖向滚动条</text>
          <switch :checked="true" @change="changeVerticalScrollBarAccess"></switch>
        </view>
      </view>
      <view class="uni-row uni-btn-v">
        <view class="uni-row uni-flex-item align-items-center">
          <text>开启bounces</text>
          <switch :checked="true" @change="changeBounces"></switch>
        </view>
      </view>
      <!-- #endif -->
      <!-- #ifdef APP-IOS -->
      <view class="uni-row uni-btn-v" v-if="isProd() === false">
        <view class="uni-row uni-flex-item align-items-center">
          <text>前进、后退功能在Windows端需要打自定义基座，MAC端需要配置Xcode环境后进行真机运行或者打自定义基座</text>
        </view>
      </view>
      <!-- #endif -->
    </view>
    <!-- #endif -->
    <!-- #ifdef APP-ANDROID || APP-IOS -->
    <view class="safe-area-inset-bottom"></view>
    <!-- #endif -->
  </view>
</template>

<script>
  // #ifdef APP
  import { canWebViewGoBack, canWebViewGoForward, hasNativeView } from '@/uni_modules/uts-get-native-view';
  // #endif
  let webviewElement =  null as UniWebViewElement | null
  export default {
    data() {
      return {
        src: 'https://www.dcloud.io',
        webview_styles: {
          progress: {
            color: '#FF3333'
          }
        },
        webviewContext: null as WebviewContext | null,
        loadError: false,
        horizontalScrollBarAccess: true,
        verticalScrollBarAccess: true,
        bounces: true,
        canGoBack: false,
        canGoForward: false,
        // 自动化测试
        autoTest: false,
        eventLoading: null as UTSJSONObject | null,
        eventLoad: null as UTSJSONObject | null,
        eventError: null as UTSJSONObject | null,
        pointerEvents: 'auto',
        isTouchEnable: false
      }
    },
    onReady() {
      // #ifdef APP
      // TODO web 实现createWebviewContext
      // this.webviewContext = uni.createWebviewContext('web-view', this)
      // NOTE 绑定到 this 上会被代理导致无法调用方法
      webviewElement = uni.getElementById('web-view') as UniWebViewElement //推荐使用element，功能更丰富
      // console.log('url: ',this.webviewElement?.getAttribute("src"));
      // this.webviewElement?.setAttribute("src","https://ext.dcloud.net.cn/")
      // #endif
    },
    methods: {
      getPackageName() : string {
        let packageName : string = ""

        // #ifdef APP-IOS
        const res = uni.getAppBaseInfo();
        packageName = res.bundleId
        // #endif

        return packageName
      },
      isProd() : boolean {
        if (this.getPackageName() == 'io.dcloud.hellouniappx') {
          return true
        }
        return false
      },
      back() {
        webviewElement?.back();
      },
      forward() {
        webviewElement?.forward();
      },
      reload() {
        webviewElement?.reload();
      },
      stop() {
        webviewElement?.stop();
      },
      nativeToWeb() {
        webviewElement?.evalJS("alert('hello uni-app x')");
      },
      message(event : UniWebViewMessageEvent) {
        console.log(JSON.stringify(event.detail));
      },
      error(event : UniWebViewErrorEvent) {
        this.loadError = true
        console.log(JSON.stringify(event.detail));
        if (this.autoTest) {
          this.eventError = {
            "tagName": event.target?.tagName,
            "type": event.type,
            "errCode": event.detail.errCode,
            "errMsg": event.detail.errMsg,
            "url": event.detail.url,
            "fullUrl": event.detail.fullUrl,
            "src": event.detail.src
          };
        }
      },
      loading(event : UniWebViewLoadingEvent) {
        console.log(JSON.stringify(event.detail));
        if (this.autoTest) {
          this.eventLoading = {
            "tagName": event.target?.tagName,
            "type": event.type,
            "src": event.detail.src
          };
        }
      },
      load(event : UniWebViewLoadEvent) {
        console.log(JSON.stringify(event.detail));
        // #ifdef APP
        this.canGoBack = canWebViewGoBack('web-view');
        this.canGoForward = canWebViewGoForward('web-view');
        // #endif
        if (this.autoTest) {
          this.eventLoad = {
            "tagName": event.target?.tagName,
            "type": event.type,
            "src": event.detail.src
          };
        }
      },
      download(event : UniWebViewDownloadEvent) {
        console.log(JSON.stringify(event.detail));
        uni.showModal({
          content: "下载链接: " + event.detail.url + "\n文件大小: " + event.detail.contentLength / 1024 + "KB",
          showCancel: false
        });
      },
      confirm(event : UniInputConfirmEvent) {
        let url = event.detail.value;
        if (!url.startsWith('https://') && !url.startsWith('http://')) {
          url = 'https://' + url;
        }
        this.src = url;
      },
      changeHorizontalScrollBarAccess(event : UniSwitchChangeEvent) {
        this.horizontalScrollBarAccess = event.detail.value;
      },
      changeVerticalScrollBarAccess(event : UniSwitchChangeEvent) {
        this.verticalScrollBarAccess = event.detail.value;
      },
      changeBounces(event : UniSwitchChangeEvent) {
        this.bounces = event.detail.value;
      },
      // 自动化测试
      touchstart(event : UniTouchEvent) {
        if (this.autoTest) {
          this.isTouchEnable = event.touches[0].clientX > 0 && event.touches[0].clientY > 0;
        }
      },
      tap(event : UniPointerEvent) {
        if (this.autoTest) {
          this.isTouchEnable = event.clientX > 0 && event.clientY > 0;
        }
      },
      //自动化测试专用
      checkNativeWebView() : boolean {
        // #ifdef APP
        return hasNativeView('web-view')
        // #endif
        // #ifdef WEB
        return true
        // #endif
      }
    }
  }
</script>

<style>
  .margin-left-5 {
    margin-left: 5px;
  }

  .align-items-center {
    align-items: center;
  }

  .safe-area-inset-bottom {
    height: var(--uni-safe-area-inset-bottom);
  }
</style>
