<template>
  <div >
    <div :style="menuStyle" class="select-menu" v-show="showMenu">
      <el-button @click="searchText" icon="el-icon-search" round>{{ selectedText }}</el-button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      showMenu: false,
      selectedText: '',
      menuStyle: {
        position: 'absolute',
        top: '0px',
        right: '0px',
      },
    };
  },
  mounted() {
    document.addEventListener('mouseup', this.handleSelection);
    document.addEventListener('mousedown', this.resetSelection);
  },
  beforeDestroy() {
    document.removeEventListener('mouseup', this.handleSelection);
    document.removeEventListener('mousedown', this.resetSelection);
  },
  methods: {
    handleSelection() {
      const selection = window.getSelection();
      if (selection && selection.toString().trim().length > 0) {
        const range = selection.getRangeAt(0).getBoundingClientRect();
        this.menuStyle = {
          position: 'absolute',
          top: `${range.top + window.scrollY - 130}px`,
          right: `${Math.max(0, window.innerWidth - range.right - window.scrollX - 30)}px`,
        };
        this.showMenu = true;
        this.selectedText = selection.toString();
      } else {
        this.showMenu = false;
      }
    },
    resetSelection(event) {
      // 确保 `mousedown` 事件不会影响到 `mouseup` 事件
      if (!this.$el.contains(event.target)) {
        this.showMenu = false;
      }
    },
    searchText() {
      console.log('searchText method triggered');
      const query = encodeURIComponent(this.selectedText);
      // window.open(`https://www.baidu.com/s?wd=${query}`, '_blank');
      this.$router.push({path: '/assetMgr/main', query: {devno: query}});
      this.showMenu = false;
    },
  },
};
</script>

<style scoped>
.select-menu {
  background: rgba(255, 255, 255, 1);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  display: flex;
  border-radius: 50px;
  gap: 5px;
  z-index: 1000;
}

</style>
