<template>
  <a-menu :style="style" class="contextmenu" v-show="visible" @click="handleClick" :selectedKeys="selectedKeys">
    <a-menu-item :key="item.key" v-for="item in itemList">
      <a-icon role="menuitemicon" v-if="item.icon" :type="item.icon" />{{ item.text }}
    </a-menu-item>
  </a-menu>
</template>

<script>
export default {
  name: 'Contextmenu',
  props: {
    visible: {
      type: Boolean,
      required: false,
      default: false
    },
    itemList: {
      type: Array,
      required: true,
      default: () => []
    }
  },
  data () {
    return {
      left: 0,
      top: 0,
      target: null,
      selectedKeys: []
    }
  },
  computed: {
    style () {
      return {
        left: this.left + 'px',
        top: this.top + 'px'
      }
    }
  },
  created () {
    window.addEventListener('mousedown', e => this.closeMenu(e))
    window.addEventListener('contextmenu', e => this.setPosition(e))
  },
  methods: {
    closeMenu (e) {
      if (this.visible === true && ['menuitemicon', 'menuitem'].indexOf(e.target.getAttribute('role')) < 0) {
        this.$emit('update:visible', false)
      }
    },
    setPosition (e) {
      this.left = e.clientX
      this.top = e.clientY
      this.target = e.target
    },
    handleClick ({ key }) {
      this.$emit('select', key, this.target)
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style lang="less" scoped>
.contextmenu {
  position: fixed;
  z-index: 1;
  box-shadow: 0px 0px 4px 0px #eeeeee;
  opacity: 1;
  border: 1px solid #eeeeee;
  padding: 13px 0;
}
.ant-menu-vertical .ant-menu-item {
  line-height: 30px !important;
  height: 30px !important;
  margin: 0;
  padding: 0 26px 0 15px;
  color: #444444;
}
.ant-menu-item:hover {
  color: #444444;
  background-color: #f6f6f6 !important;
}
.ant-menu-item .anticon {
  color: #3747d6;
}
</style>
