<template>
  <web-view :src="url" @message="handleWebviewMsg" />
</template>
<script>
import sdkMethods from "@/pages/webview/mpSdkMethods.mixins";
import { getGroupBuyUrl } from "@/api/ka.api.js";
import { param } from "@/utils/index.js";
export default {
  mixins: [sdkMethods],
  data() {
    return {
      currentFullPath: "",
      url: "",
      viewUrl: ""
    };
  },
  async onLoad(option) {
    console.log(option, "webview");
    const token = uni.getStorageSync("token") || "";
    const paramsAsMD5 = option.scene ? JSON.stringify(option.scene).match(/^"m\*\*(\S*)"/)[1] : "";
    this.currentFullPath = getCurrentPages()[getCurrentPages().length - 1].$page.fullPath;
    option.sampshare && (option.url = decodeURIComponent(option.url));
    if (option.scene && paramsAsMD5) {
      console.log("paramsAsMD5", paramsAsMD5);
      let [url] = await getGroupBuyUrl(paramsAsMD5);
      if (url.indexOf("vccToken=") === -1) {
        if (token) {
          url += `&vccToken=${token}`;
        } else {
          url += `&vccToken={token}`;
        }
      }
      this.url = encodeURIComponent(JSON.stringify(url));
      console.log("urlurlurl,", url);
      this.viewUrl = JSON.parse(decodeURIComponent(this.url));
    } else {
      if (Object.keys(option).includes("from")) {
        const link = option.link;
        delete option.link;
        this.viewUrl = decodeURIComponent(`${link}${param(option, true)}`);
      } else {
        this.viewUrl = JSON.parse(decodeURIComponent(decodeURIComponent(option.url)));
        console.log("----url", this.viewUrl);
      }

      // if () {}
      // const url =
      //   option.url.indexOf("vccToken=") == -1
      //     ? option.url + encodeURIComponent(JSON.stringify(`&vccToken=${token}`))
      //     : option.url;
    }

    this.handleChangeUrl();
    uni.$on("WEBVIEW_URL_CHANGE", this.handleWebviewUrl);
  },
  onUnload() {
    uni.$off("WEBVIEW_URL_CHANGE");
  },
  onShareAppMessage() {
    return {
      title: this.shareInfo.title,
      imageUrl: this.shareInfo.imgUrl,
      path: this.shareInfo.link || this.currentFullPath
    };
  },
  methods: {
    handleWebviewMsg(e) {
      e.detail.data.forEach(item => {
        this[item.event](item.data);
      });
    },
    changeURLArg(url, arg, arg_val) {
      let pattern = arg + "=([^&]*)";
      let replaceText = arg + "=" + arg_val;
      if (url.match(pattern)) {
        let tmp = `(${arg}=)([^&]*)`;
        tmp = url.replace(new RegExp(tmp, "gi"), replaceText);
        return tmp;
      } else {
        if (url.match("[?]")) {
          return url + "&" + replaceText;
        } else {
          return url + "?" + replaceText;
        }
      }
    },
    handleWebviewUrl(data) {
      const router = getCurrentPages();
      const currentRoute = router[router.length - 2];
      const nextRoute = router[router.length - 1];
      if (
        nextRoute.route === "pages/webview/middleWay" &&
        currentRoute.$page.fullPath === this.currentFullPath
      ) {
        let url = this.viewUrl;
        const hashQuery = url.indexOf("?") > -1;
        if (data.event === "getToken") {
          if (url.indexOf("vccToken") === -1) {
            url += (hashQuery ? "&" : "?") + `vccToken=${uni.getStorageSync("token")}`;
          } else {
            url = this.changeURLArg(url, "vccToken", uni.getStorageSync("token") || "");
          }
        }
        this.viewUrl = url;
        this.handleChangeUrl(true);
      }
    },
    handleChangeUrl(refreshWV) {
      let url = this.viewUrl;
      url = url.replace("{token}", uni.getStorageSync("token") || "");
      // url = url.replace("!", "?");
      // url = url.replaceAll("$", "&");
      console.log(url, "=================");
      if (refreshWV) {
        const timer = setTimeout(() => {
          uni.redirectTo({
            url: `/pages/groupbuy/webview?url=${encodeURIComponent(JSON.stringify(url))}`
          });
          clearTimeout(timer);
        }, 1000);
      } else {
        this.url = url;
      }
    }
  }
};
</script>
