<template>
  <!-- <BaseSameLayer
      :hosSameLayerArgs="hosSameLayerArgs"
      embedType="native/web"
      :defaultWidth="300"
      :defaultHeight="120"
  ></BaseSameLayer> -->
  <iframe :src="src" ref="iframe"></iframe>

</template>

<script>
import BaseSameLayer from "./baseSameLayer.vue";
let count = 0

export default {
name: "HlWeb",
data() {
  return {
    width: 0,
    height: 0
  }
},
props: {
  hosUniqueProps: {
    type: Object,
    default() {
      return {};
    },
  },
  src: {
    type: String,
    required: true,
  },
  harmonyStyle: {
    type: Object,
    required: false,
  }
},

computed: {
  hosSameLayerArgs() {
  return {
      ...this.hosUniqueProps, // 鸿蒙原生组件独有属性
      src: this.src,
      width: this.width,
      height: (this.harmonyStyle && this.harmonyStyle.height) ? this.harmonyStyle.height : this.height,
      pagefinish: this.onPageFinish,
      pagestart: this.onPageStart,
      error: this.onError,
      receivedtitle: this.onReceivedTitle,
      message: this.onMessage,
    }
  }
},
mounted() {
  this.width = this.$el.clientWidth;
  this.height = this.$el.clientHeight;

  this.onPageStart();
  var that = this
  window.addEventListener('message', function (event)  {
    // 可以添加来源检查以确保消息来自预期的源
    if (event.origin === window.origin && that.onMessage) {
      that.onMessage(event.data)
    }
  });

  this.$refs["iframe"].addEventListener('load', this.onPageFinish);

  this.$refs["error"].addEventListener('load', this.onError);
},
methods: { 
  postMessage(message){
    const iframe = this.$refs["iframe"]
    const target = new URL(iframe.src).origin
    iframe.contentWindow.postMessage(message, target)
    //this.$refs["iframe"].contentWindow.postMessage(message, this.src)
  },
  // 自定义拓展其它逻辑
  onPageFinish(res) {
      console.log("[web] pagefinish ", res);
      this.$refs["iframe"].contentWindow.$midea_harmony_native = window.$midea_harmony_native
      this.$refs["iframe"].contentWindow.postMessage(JSON.stringify(window.$midea_harmony_native), '*');
      this.$emit("pagefinish", res);
  },
  onPageStart(res) {
      console.log("[web] pagestart ", res);
      this.$emit("pagestart", res);
  },
  onError(res) {
      console.log("[web] onError ", res);
      this.$emit("error", res);
  },
  onReceivedTitle(res) {
      console.log("[web] onReceivedTitle ", res);
      this.$emit("receivedtitle", res);
  },
  onMessage(res){
    console.log("[web] onMessage ", res);
    this.$emit("message", res);
  },
},
watch: {
  loading(newText, oldText) {
    if (newText !== oldText) {
      this.scheduleTransfer(); // 当loading属性变化时重新调用
    }
  },
},
};
</script>

<style scoped>
</style>