<template>
  <div>
    <embed
      :id="embedId"
      type="native/textarea"
      :width="width"
      :height="height"
      src=""
    />
  </div>
</template>

<script>
const weexModule = weex.requireModule("weexModule");

export default {
  name: "HlTextareaTest",
  props: {
    placeholder: {
      type: String,
      required: true,
    },
    width: {
      type: Number,
      required: false,
      default: 300,
    },
    height: {
      type: Number,
      required: false,
      default: 120,
    },
    backgroundColor: {
      type: String,
      required: false,
    }
  },
  data() {
    return {
      embedId: `textarea_${this._uid}`, // 使用Vue实例的唯一ID来生成embed元素的唯一ID
      isTransferScheduled: false, // 添加一个标志来检查是否已经安排了transferPropsAndListeners的调用
    };
  },
  created() {
    console.log("[weex] hl-textarea created!");
    this.transferPropsAndListeners(); // 组件创建时调用
  },
  mounted() {
    this.addTouchEvent();
  },
  beforeDestroy() {
    this.removeTouchEvent();
  },
  methods: {
    transferPropsAndListeners() {
      // 构建一个包含所需信息的对象
      const args = {
        componentId: this.embedId,
        width: this.width,
        height: this.height,
        placeholder: this.placeholder,
        backgroundColor: this.backgroundColor,
        onChange: this.handleonInput,
      };
      // 调用JSbridge方法，传递属性和监听方法到原生组件
      weexModule.callNative("transferSameLayerArgs", args);
    },
    // 必须给embed元素添加touchstart事件监听，addEventListener的第二个参数监听事件对象置空即可（同层渲染事件处理需要）
    addTouchEvent() {
      const embedElement = document.getElementById(this.embedId);
      if (embedElement) {
        console.log("[weex] hl-textarea-embed addEventListener");
        embedElement.addEventListener('touchstart', {});
      }
    },
    removeTouchEvent() {
      const embedElement = document.getElementById(this.embedId);
      if (embedElement) {
        console.log("[weex] hl-textarea-embed removeEventListener");
        embedElement.removeEventListener('touchstart', {});
      }
    },
    scheduleTransfer() {
      if (!this.isTransferScheduled) {
        this.isTransferScheduled = true;
        this.$nextTick(() => {
          this.transferPropsAndListeners();
          this.isTransferScheduled = false;
        });
      }
    },
    handleonInput(res) {
      console.log("[weex] handleonInput ", res);
      this.$emit("nativeOnInput", res);
    }
  },
  watch: {
    text(newText, oldText) {
      if (newText !== oldText) {
        this.scheduleTransfer(); // 当text属性变化时重新调用
      }
    },
    width(newWidth, oldWidth) {
      if (newWidth !== oldWidth) {
        this.scheduleTransfer(); // 当width属性变化时重新调用
      }
    },
    height(newHeight, oldHeight) {
      if (newHeight !== oldHeight) {
        this.scheduleTransfer(); // 当width属性变化时重新调用
      }
    },
  },
};
</script>

<style scoped>
</style>
