<template>
  <web-view :src="url" @message="handleWebviewMsg" />
</template>
<script>
import sdkMethods from "./mpSdkMethods.mixins";
import { kaGetNextUrl, getKaData } from "@/api/ka.api.js";
export default {
  mixins: [sdkMethods],
  data() {
    return {
      currentFullPath: "",
      url: "",
      viewUrl: "",
      kaChannel: {},
      vccChannel: "",
      sonVccChannel: "",
      refreshWhenShow: false,
      firstShow: true
    };
  },
  computed: {
    /**
     * 560867, '青海移动',
     * 560868, '江苏移动',
     * 560761, '羊小咩',
     */
    tenantId: {
      get: function() {
        return uni.getStorageSync("tenantId") ?? "";
      }
    },
    appId: {
      get: function() {
        let appId;
        //#ifdef MP-ALIPAY
        appId = uni.getAppIdSync().appId;
        //#endif

        // #ifndef MP-ALIPAY
        const accountInfo = uni.getAccountInfoSync();
        appId = accountInfo.miniProgram.appId;
        // #endif
        return appId;
      }
    }
  },
  async onLoad(option) {
    // uni.setNavigationBarTitle({ title: this.$config("defaultTitle") });
    this.refreshWhenShow = !!option.refresh;
    this.currentFullPath = getCurrentPages()[getCurrentPages().length - 1].$page.fullPath;
    if (option.channel === "kaLZJM") {
      if (option.vccChannel) {
        uni.setStorageSync("vccChannel", option.vccChannel);
        this.vccChannel = option.vccChannel;
      }
      if (option.sonVccChannel) {
        uni.setStorageSync("sonVccChannel", option.sonVccChannel);
        this.sonVccChannel = option.sonVccChannel;
      }
      uni.$on("WEBVIEW_URL_CHANGE", this.handleWebviewUrl);
      this.getKaDataFn();
    } else if (option.channel === "ka") {
      delete option.channel;
      this.kaChannel = option;
      this.getKaGetNextUrl("ka");
    } else if (option.from === "pay") {
      console.log(option);
      this.getKaGetNextUrl("pay");
      // this.url = option.url
    } else if (option.from === "user") {
      console.log(option);
      this.getKaGetNextUrl("user");
    } else {
      // option.url += `&fromVcc=h5`
      uni.$on("WEBVIEW_URL_CHANGE", this.handleWebviewUrl);
      this.viewUrl = JSON.parse(decodeURIComponent(option.url));
      this.handleChangeUrl();
    }
  },
  onUnload() {
    uni.$off("WEBVIEW_URL_CHANGE");
  },
  onShow() {
    if (this.firstShow) {
      this.firstShow = false;
    } else {
      this.refreshWhenShow && this.handleChangeUrl(true);
    }
  },
  onShareAppMessage() {
    return {
      title: this.shareInfo.title,
      imageUrl: this.shareInfo.imgUrl,
      path: decodeURIComponent(this.currentFullPath)
    };
  },
  methods: {
    handleWebviewMsg(e) {
      e.detail.data.forEach(item => {
        this[item.event](item.data);
      });
    },
    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" && url.indexOf("vccToken") === -1) {
          url += (hashQuery ? "&" : "?") + `vccToken=${uni.getStorageSync("token")}`;
        }
        this.viewUrl = url;
        this.handleChangeUrl(true);
      }
    },
    handleChangeUrl(refreshWV) {
      let url = this.viewUrl;
      if (url.indexOf("://quantum-h5") > -1 || url.indexOf("/maxMember") > -1) {
        // 量子积木url增加同盾ID键，feat: 量子积木领券同盾埋点; PM: 崔倩倩
        const shumeiKey = uni.getStorageSync("shumeiKey");
        if (shumeiKey && url.indexOf("shumeiKey") == -1)
          url = this.addParamToURL(url, "shumeiKey", shumeiKey);
      }

      url = url.replace("{vccToken}", uni.getStorageSync("token") || "");
      url = url.replace("{token}", uni.getStorageSync("token") || "");
      url = url.replace("{uuid}", uni.getStorageSync("userAuthInfo").uuid || "");
      url = url.replace("{phone}", uni.getStorageSync("phone") || "");
      url = url.replace("{appId}", this.appId || "");
      url = url.replace("{tenantId}", this.tenantId || "");
      if (refreshWV) {
        const timer = setTimeout(() => {
          uni.redirectTo({
            url: `/pages/webview/webview?url=${encodeURIComponent(JSON.stringify(url))}`
          });
          clearTimeout(timer);
        }, 1000);
      } else {
        this.url = url;
      }
    },
    addParamToURL(url, key, value) {
      let newUrl = url.indexOf("?") < 0 ? url + "?" : url + "&";
      return newUrl + key + "=" + value;
    },
    // 获取ka地址
    async getKaGetNextUrl(val) {
      const token = uni.getStorageSync("token");
      console.log(this.kaChannel);
      if (token) {
        const [data] = await kaGetNextUrl({
          ...this.kaChannel,
          "x-auth-token": token,
          fromXcxPage: val
        });
        let nextUrl = data.nextUrl;
        nextUrl = nextUrl.replace("{tenantId}", this.tenantId || "");
        nextUrl = nextUrl.replace("{appId}", this.appId || "");
        this.url = nextUrl;
      }
    },
    // ka量子积木落地url
    async getKaDataFn() {
      const [data] = await getKaData({
        vccChannel: this.vccChannel,
        sonVccChannel: this.sonVccChannel,
        pageType: "1"
      });
      console.log(data);
      if (data) {
        const hashQuery = data.thirdJumpUrl.indexOf("?") > -1;
        data.thirdJumpUrl += (hashQuery ? "&" : "?") + `vccToken=${uni.getStorageSync("token")}`;
        this.viewUrl = data.thirdJumpUrl;
        this.handleChangeUrl();
      }
    }
  }
};
</script>
