<script setup lang="ts">
import {ref, computed, inject, onMounted} from 'vue'
import ClickArea from "./ClickArea.vue";
import {InvitationInfo} from "../types"
import {getCdnUrl} from "../utils"
import {fetchInvitationInfo, invitationAssist} from "../api";
import GotPrizeModal from "./GotPrizeModal.vue";

const isAssist = ref(false)
const invitationInfo = ref<InvitationInfo>()
const gotPrizeModalRef = ref<InstanceType<typeof GotPrizeModal>>()

const updateShareData = inject('updateShareData')
const onGetPhoneNumber = inject('onGetPhoneNumber')

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

const isLogin = computed(() => {
  return !invitationInfo.value?.notLogin
})

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 inviteBtnProperties = computed(() => {
  return {
    area: {x: 220, y: 110, width: 165, height: 55},
    mdConfig: props.properties.mdConfig,
  }
})

async function updateInvitationInfo() {
  const resp = await fetchInvitationInfo()
  return invitationInfo.value = resp.data
}

async function tryAssist() {
  if (invitationInfo) {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const options = currentPage.options;
    const invitationCode = options.invitationCode;

    if (invitationCode && !isAssist.value && isLogin.value) {
      console.log('处理助力邀请码:', incomingCode)

      try {
        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 updateInvitationInfo();
          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();
      }
    }
  }
}

onMounted(async () => {
  await updateInvitationInfo()

  updateShareData({
    path: '/activities/1015/home/index?invitationCode=' + invitationInfo.value.invitationCode,
  })

  const {unclaimedPrizes} = invitationInfo.value
  if (unclaimedPrizes.value?.length > 0) {
    const totalQuantity = unclaimedPrizes.value.reduce((sum, prize) => sum + (prize.quantity || 1), 0)
    const firstPrize = unclaimedPrizes.value[0]
    gotPrizeModalRef.value.show({
      prizeName: `${firstPrize.prizeName} × ${totalQuantity}`,
      prizeImageUrl: firstPrize.prizeImageUrl,
    })
  }

  await tryAssist()
})

</script>

<template>
  <view class="invite-task" :class="{'debug-mode': debugMode}" :style="style">
    <view class="avatars">
      <template
        v-for="i in 2">
        <image
          v-if="i-1 < 2 - invitationInfo.nextRewardNeedCount"
          class="avatar"
          :src="getCdnUrl('home/icon-fill.png')"
        />
      </template>
    </view>
    <ClickArea
      :properties="inviteBtnProperties"
      :open-type="isLogin ? 'share' : 'getPhoneNumber'"
      @getphonenumber="onGetPhoneNumber"
      :debug-mode="debugMode"
    />
  </view>
  <GotPrizeModal ref="gotPrizeModalRef"/>
</template>

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

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

  .avatars{
    position: absolute;
    left: 24rpx;
    top: 108rpx;
    display: flex;
    gap: 25rpx;

    .avatar{
      width: 63rpx;
      height: 63rpx;
    }
  }
}
</style>