<script setup lang="ts">
import {computed, inject, watch, ref} from 'vue'
import {jump} from '@/utils'
import {MdConfig} from "../types";
import {useMD} from "../use-md";

const props = defineProps<{
  properties?: {
    area?: { x: number, y: number, width: number, height: number }
    link?: { type: number, url: string, extra: any }
    mdConfig?: MdConfig
    needLogin?: boolean
  }
  openType?: string
  isLogin?: boolean
  debugMode?: boolean
}>()

const pageName = inject('pageName', '')

const needRevoke = ref(false)

const style = computed(() => {
  const area = props.properties.area
  return {
    left: area.x + 'rpx',
    top: area.y + 'rpx',
    width: area.width + 'rpx',
    height: area.height + 'rpx',
  }
})

const {logClick} = useMD(props.properties.mdConfig || {})

const emit = defineEmits<{
  (e: 'click', e: any): void
  (e: 'getphonenumber', e: any): void
}>()

function onClick(e, revoke = false) {
  if (!revoke) {
    emit('click', e)
    logClick()
  }

  if ((!props.properties.needLogin || props.isLogin) && props.properties.link) {
    jump(props.properties.link)
  }
}

function onGetPhoneNumber(e) {
  needRevoke.value = true
  emit('getphonenumber', e)
}

watch(() => props.isLogin, async (newVal) => {
  if (newVal && needRevoke.value) {
    needRevoke.value = false
    onClick(null, true)
  }
})

</script>

<template>
  <button class="click-area" :class="{'debug-mode': debugMode}" :style="style"
          :open-type="openType ?? (properties.needLogin && !isLogin ? 'getPhoneNumber' : undefined)"
          @click="onClick"
          @getphonenumber="onGetPhoneNumber"
  />
</template>

<style scoped lang="less">
.click-area {
  position: absolute;
  border: none;
  border-radius: 0;
  background-color: transparent;

  &.debug-mode {
    background-color: rgba(255, 0, 0, 0.3);
  }

  &::after {
    border: none;
  }
}
</style>