<template>
  <div :id="id" class="over-click" @click="handleClick()">
    <div v-show="active" class="active-context">
      <slot name="active" />
    </div>
    <div v-show="!active" class="over-context">
      <slot name="overMouse" />
    </div>
  </div>
</template>
<script>
export default {
  props: {
    active: {
      type: Boolean,
      default: false,
      required: true
    },
    id: {
      type: String,
      default: 'click-parent',
      required: true
    }
  },
  data() {
    return {
      visible: this.active,
      listener: null
    }
  },
  watch: {
    active: {
      handler(newV) {
        this.visible = this.active
      },
      immediate: true
    }
  },
  mounted() {
    const parent = document.getElementById(this.id)
    this.listener = document.addEventListener('click', (event) => {
      const isInner = parent.contains(event.target)
      if (!isInner) {
        this.visible = false
        this.$emit('update:active', this.visible)
        this.$emit('overMouse')
      }
    })
  },
  destroyed() {
    document.removeEventListener(this.listener)
  },
  methods: {
    handleClick() {
      this.visible = true
      this.$emit('update:active', this.visible)
      this.$emit('click')
    }
  }
}
</script>
<style lang="scss" scoped>
.active-context,.over-context{
  cursor: pointer;
}
</style>
