<template>
  <div class="main">
    <template v-if="webViewSrc">
      <web-view
        id="myWebView"
        ref="myWebView"
        :src="webViewSrc"
        @message="onMessage"
      ></web-view>
    </template>
    <!-- @load="onMinLoad" -->

    <!-- <span @click="handleGetPoint">获取位置信息</span> -->
  </div>
  <!-- src="https://saas.eshangtech.com/goaliPay/index.html" -->

  <!-- src="https://ahyd.eshangtech.com/goaliPay/index.html" -->
</template> 
  
<script>
import { mapGetters } from "vuex";
export default {
  data() {
    return {
      message: "",
      webViewSrc: ``,
      nowObj: {},
      loginType: "",
    };
  },
  computed: {
    ...mapGetters({
      user: "user",
    }),
  },
  async onLoad() {
    this.webViewSrc = `https://eshangtech.com/goaliPay/testwx.html`;
    return;

    let type = uni.getStorageSync("loginType");
    console.log("loginType", type);
    this.loginType = type;
    let obj = {
      loginType: type,
      phone: this.user.MEMBERSHIP_MOBILEPHONE,
    };
    this.nowObj = obj;
    const jsonString = JSON.stringify(obj);
    const encodedData = encodeURIComponent(jsonString);
    console.log("encodedData", encodedData);
    if (type === "min") {
      // const code = await this.login();
      // console.log("dasldhasodhbasoudh", code);
      // const codeString = JSON.stringify(code);
      // const encodedCode = encodeURIComponent(codeString);
      // console.log("encodedCode", encodedCode);
      this.webViewSrc = `https://eshangtech.com/goaliPay/testwx.html`;
      // https://ahyd.eshangtech.com/goaliPay/index.html
      // https://saas.eshangtech.com/goaliPay/index.html
    } else {
      this.webViewSrc = `https://saas.eshangtech.com/goaliPay/index.html#${encodedData}`;
    }
    console.log("this.webViewSrc", this.webViewSrc);
  },
  methods: {
    async onMinLoad() {
      // console.log("111", 11);
      // const code = await this.login();
      // console.log("dasldhasodhbasoudh", code);
      // const codeString = JSON.stringify(code);
      // const encodedCode = encodeURIComponent(codeString);
      // console.log("encodedCode", encodedCode);
      // this.webViewSrc = `https://eshangtech.com/goaliPay/testwx.html#${encodedCode}`;
      // this.webViewSrc = `https://eshangtech.com/goaliPay/testwx.html`;
      // console.log("this.webViewSrc", this.webViewSrc);
    },
    handleGetPoint() {
      $wanmeiyizhan.handleGetPosition().then((res) => {});
    },
    onMessage(event) {
      let _this = this;
      console.log("收到 H5 的消息:", event.detail.data[0]);
      if (event.detail.data[0].action === "scanCode") {
        uni.scanCode({
          success: function (res) {
            console.log("res", res);
            _this.sendMessageToH5({ type: "scanCode", res: res });
          },
        });
      } else if (event.detail.data[0].action === "position") {
        // let req = {
        //   membershipId: _this.user.MEMBERSHIP_ID,
        // };

        // _this.$api.$get("/Html5/GetMemberLocation", req).then((res) => {
        //   console.log("resdasda", res);
        // });

        plus.geolocation.getCurrentPosition(async function (position) {
          console.log("当前位置:", position);
          let res = position.coords;
          let seatInfo = {
            latitude: res.latitude,
            longitude: res.longitude,
          };
          _this.sendMessageToH5({ type: "position", res: seatInfo });
        });
      } else if (event.detail.data[0].action === "openLocation") {
        let obj = event.detail.data[0].res;
        console.log("openLocation", obj);
        uni.openLocation({
          latitude: obj.latitude * 1,
          longitude: obj.longitude * 1,
          scale: 16, // 缩放比例
          name: obj.name,
          address: "", // 这个可能会影响地图的定位，所以可以选择不填
          success(data) {
            console.log(data);
          },
          fail(err) {
            console.log(err);
          },
        });
      } else if (event.detail.data[0].action === "openNewPage") {
        let obj = event.detail.data[0].res;
        console.log("openNewPage", obj);
        uni.navigateTo({
          url: `/pages/thirdParty/newPage?url=${obj.url}&title=${obj.title}`,
        });
      } else if (event.detail.data[0].action === "backPage") {
        uni.navigateBack({
          delta: 1,
        });
      }
      // event.data 包含 H5 发送过来的消息内容
    },
    sendMessageToH5(data) {
      console.log("收到消息", data);
      let obj = this.nowObj;
      obj[data.type] = data.res;
      this.nowObj = obj;
      console.log("obj", obj);
      const jsonString = JSON.stringify(obj);
      const encodedData = encodeURIComponent(jsonString);
      console.log("encodedData", encodedData);
      this.webViewSrc = `https://saas.eshangtech.com/goaliPay/index.html#${encodedData}`;
      console.log("this.webViewSrc", this.webViewSrc);
      // const webView = this.$refs.myWebView;
      // webView.postMessage(data);
    },
    async login() {
      let str = Math.random().toString(36).substr(2, 15);
      let time = Math.floor(Date.now() / 1000);

      let jsapi_ticket = await this.$api.$get(
        "/EShangApiMain/WeChat/GetJsapiTicket",
        {
          appId: "wx4c497eddcec4a0e7",
          sourcePlatform: "minprogram",
          // minprogram
          // publicprogram
        }
      );
      console.log("jsapi_ticket", jsapi_ticket);
      const req = {
        jsapi_ticket: jsapi_ticket.Result_Data,
        appId: "wx4c497eddcec4a0e7",
        // wx4c497eddcec4a0e7 min
        //  wxcf4dbe1815d5d872
        timestamp: time,
        nonceStr: str,
        url: `https://eshangtech.com/goaliPay/testwx.html`,
        jsApiList: ["openLocation", "getLocation", "scanQRCode"],
      };
      console.log("req321312", req);
      const data = await this.$api.$post(
        "/EShangApiMain/WeChat/GetConfigSignature",
        req
      );
      console.log("datalogin", data);
      req.result = data.Result_Data;
      return req;

      // let str = this.generateNonceStr();
      // let time = new Date().getTime();
      // fetch(
      //   `https://api.eshangtech.com/EShangApiMain/WeChat/GetJsapiTicket?appId=wx4c497eddcec4a0e7&sourcePlatform=minprogram`
      // )
      //   .then((response) => response.json())
      //   .then((data) => {
      //     wx.config({
      //       debug: true, // 开启调试模式
      //       appId: "wx4c497eddcec4a0e7", // 微信公众号或小程序的AppID
      //       timestamp: time, // 时间戳
      //       nonceStr: str, // 随机字符串
      //       signature: data.signature, // 签名
      //       jsApiList: ["openLocation", "scanQRCode", "getLocation"], // 需要调用的API列表
      //     });

      //     wx.ready(function () {});
      //   });
    },
    generateNonceStr(length = 16) {
      let nonceStr = "";
      const characters =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      // 使用当前时间戳作为随机种子
      const timestamp = Date.now();
      // 拼接时间戳和随机数
      for (let i = 0; i < length; i++) {
        nonceStr += characters.charAt(
          Math.floor(Math.random() * characters.length)
        );
      }
      return nonceStr + timestamp.toString(36).slice(-4); // 添加时间戳的后4位，增加唯一性
    },
  },
};
</script>
<style scoped lang="less">
.main {
  width: 100vw;
  height: 100vh;
}
</style>