<script setup lang="ts">
import {ref, computed, watch, inject} from 'vue'
import ClickArea from "./ClickArea.vue";
import {ActivityInfo} from "../types"
import {invitationAssist} from "../api";

const isAssist = ref(false)

const isLogin = inject('isLogin')
const updateActivityInfo = inject('updateActivityInfo')
const onGetPhoneNumber = inject('onGetPhoneNumber')

const props = defineProps<{
  properties?: {
    area?: { x: number, y: number, width: number, height: number }
    mdConfig?: MdConfig
  }
  activityData?: ActivityInfo
  debugMode?: boolean
}>()

const inviteBtnProperties = computed(() => {
  return {
    area: {x: 220, y: 110, width: 165, height: 55},
    mdConfig: props.properties.mdConfig,
  }
})

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',
  }
})

watch(() => props.activityData, (activityData) => {
  if (activityData) {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const options = currentPage.options;
    const invitationCode = options.invitationCode;

    if (invitationCode && !isAssist.value && isLogin.value) {
      handleInvitationAssist(invitationCode);
    }
  }
})

// 处理邀请助力的通用函数
const handleInvitationAssist = async (incomingCode) => {
  try {
    console.log('处理助力邀请码:', incomingCode)
    const unionId = uni.getStorageSync('unionId');

    const res = await invitationAssist(incomingCode, unionId);
    if (res && res.success) {
      uni.showToast({
        title: '助力成功',
        icon: 'none',
        duration: 2000
      });
      isAssist.value = true;
      // 助力成功后重新获取数据
      await updateActivityInfo();
      return Promise.resolve();
    } else {
      uni.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      });
      return Promise.reject();
    }
  } catch (error) {
    console.error('助力请求失败:', error)
    uni.showToast({
      title: error.message,
      icon: 'none',
      duration: 2000
    });
    return Promise.reject();
  }
}

function clickInvite() {

}

</script>

<template>
  <view class="invite-task" :class="{'debug-mode': debugMode}" :style="style">
    <ClickArea
      :properties="inviteBtnProperties"
      :open-type="isLogin ? 'share' : 'getPhoneNumber'"
      @click="clickInvite"
      @getphonenumber="onGetPhoneNumber"
      debug-mode
    />
  </view>
</template>

<style scoped lang="less">
.invite-task {
  position: absolute;

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