<template>
  <div
    v-show="visible"
    class="right-click-menu"
    :style="{ left: position.x + 'px', top: position.y + 'px' }"
  >
    <div v-if="showSelectionMenu" class="menu-item" @click="onChangeCopy('select-all')">全部选择</div>
    <div v-if="showSelectionMenu" class="menu-item" @click="onChangeCopy('cancel-select')">取消选择</div>
    <div
      v-if="showCopySubShopNumber"
      class="menu-item"
      @click="onChangeCopy('copy_code')"
    >
      复制生产单号
    </div>
    <div
      v-if="showCopyShopNumber"
      class="menu-item"
      @click="onChangeCopy('copy_shopNumber')"
    >
      复制店铺单号
    </div>

    <div v-if="showCopyCount" class="menu-item" @click="onChangeCopy('count')">
      统计数量
    </div>
    <slot></slot>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

const visible = ref(false)
const position = ref({ x: 0, y: 0 })
const emit = defineEmits(['onChange'])

defineProps({
  showCopyShopNumber: {
    type: Boolean,
    default: true,
  },
  showCopyCount: {
    type: Boolean,
    default: true,
  },
  showCopySubShopNumber: {
    type: Boolean,
    default: true,
  },
  showSelectionMenu: {
    type: Boolean,
    default: true,
  },
})

const setPosition = ({ x, y }: { x: number; y: number }) => {
  position.value = { x, y }
  visible.value = true
}

const onChangeCopy = (value: string) => {
  emit('onChange', value)
  visible.value = false
}

// 点击其他地方关闭菜单
const handleClickOutside = () => {
  if (visible.value) {
    visible.value = false
  }
}

// 监听全局点击事件
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

defineExpose({
  setPosition,
})
</script>

<style scoped lang="scss">
.right-click-menu {
  position: fixed;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 3000;
}

.right-click-menu {
  :deep(.menu-item) {
    padding: 8px 16px;
    cursor: pointer;
    font-size: 14px;
    color: #606266;
  }
}

.right-click-menu {
  :deep(.menu-item):hover {
    background-color: #f5f7fa;
    color: #409eff;
  }
}
</style>
