<template>
  <div v-on="filteredListeners" 
    @touchstart="!this.isRemove ? handleTouchStart : null"
    @touchmove="!this.isRemove ? handleTouchMove : null"
    @touchend="!this.isRemove ? handleTouchEnd : null">
    <embed
      ref="embedElement"
      :id="embedId"
      :type="embedType"
      :width="embedWidth || '100%'"
      :height="embedHeight || '100%'"
    />
  </div>
</template>

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

export default {
  name: "BaseSameLayer",
  props: {
    hosSameLayerArgs: {
      type: Object,
      required: true
    },
    embedType: {
      type: String,
      required: true,
    },
    defaultWidth: {
      type: Number,
      required: false,
      default: 0,
    },
    defaultHeight: {
      type: Number,
      required: false,
      default: 0,
    },
    listenEvents:{
      type: Array,
      required: false,
      default: () => [],
    },
    isRemove: {
      type: Boolean,
      required: false,
      default: false,
    },
    embedWidth:{
      type: String || Number,
      defalut: '100%'
    },
    embedHeight:{
      type: String || Number,
      defalut: '100%'
    }
  },
  data() {
    return {
      startX: 0,
      startY: 0,
      isHorizontalScroll: false,
    };
  },
  computed: {
    filteredListeners() {
      //指定传给父级标签的vue原生事件 尝试过外面v-on="{ 'click': $listeners.click }" 局部传但是不行
      if (!this.listenEvents.length) { return {} }
      const filtered = {};
      Object.keys(this.$listeners).forEach(event => {
        if (this.listenEvents.includes(event) && this.$listeners[event]) {
          filtered[event] = this.$listeners[event];
        }
      });
      return filtered;
    }
  },
  created() {
    this.embedId = `embedId_${this._uid}_${this.generateNaiveId()}`
    console.log("[sameLayerRendering] web component created.");
    weexModule.callNative("transferSameLayerArgs", {
      componentId: this.embedId,
      embedType: this.embedType,
      ...this.hosSameLayerArgs,
    });
  },
  mounted() {
    console.log("[sameLayerRendering] web component mounted.");
    this.addTouchEvent();
  },
  beforeDestroy() {
    console.log("[sameLayerRendering] web component beforeDestroy.");
    this.removeTouchEvent();
  },
  methods: {
    generateNaiveId() {
        return Date.now().toString(36) + Math.random().toString(36).substring(2);
    },
    // 记录起始触摸位置
    handleTouchStart(e) {
      this.startX = e.changedTouches[0].clientX;
      this.startY = e.changedTouches[0].clientY;
      this.isHorizontalScroll = false;
      // 初始禁用 embed 的交互
      this.$refs.embedElement.style.pointerEvents = 'none';
    },
    // 判断滑动方向并动态切换 pointer-events
    handleTouchMove(e) {
      const deltaX = e.changedTouches[0].clientX - this.startX;
      const deltaY = e.changedTouches[0].clientY - this.startY;
      // 判断是否为横向滑动
      if (Math.abs(deltaX) > Math.abs(deltaY)) {
        this.isHorizontalScroll = true;
        e.preventDefault(); // 阻止默认滚动行为
        this.$refs.embedElement.style.pointerEvents = 'none'; // 保持禁用
        this.handleHorizontalScroll(deltaX); // 执行翻页逻辑
      } else {
        // 纵向滑动时恢复交互
        this.$refs.embedElement.style.pointerEvents = 'auto';
      }
    },
   // 滑动结束重置状态
    handleTouchEnd() {
      this.$refs.embedElement.style.pointerEvents = 'auto';
      this.isHorizontalScroll = false;
    },
    // 横向滑动逻辑（示例：控制父容器滚动）
    handleHorizontalScroll(deltaX) {
      this.$el.scrollLeft -= deltaX * 0.5; // 调整滑动灵敏度
    },
    // 必须给embed元素添加touchstart事件监听，addEventListener的第二个参数监听事件对象置空即可（同层渲染事件处理需要）
    addTouchEvent() {
      const embedElement = document.getElementById(this.embedId);
      if (embedElement) {
        console.log(
          "[sameLayerRendering] web component embed addEventListener."
        );
        embedElement.addEventListener("touchstart", {});
      }
    },
    removeTouchEvent() {
      const embedElement = document.getElementById(this.embedId);
      if (embedElement) {
        console.log(
          "[sameLayerRendering] web component embed removeEventListener."
        );
        embedElement.removeEventListener("touchstart", {});
      }
    },
  },
  watch: {
    hosSameLayerArgs: {
      deep: true,
      handler: function (newVal, oldVal) {
        console.log("[sameLayerRendering] web component update.");
        this.$nextTick(() => {
          weexModule.callNative("transferSameLayerArgs", {
            componentId: this.embedId,
            embedType: this.embedType,
            ...newVal,
          });
        });
      },
    },
  },
};
</script>
