<script setup lang="ts">
import {ref, computed, inject, onMounted, watch, getCurrentInstance} 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 {proxy} = getCurrentInstance()
const $baseUrl = proxy.$baseUrl

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

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()
  console.log('invitationInfo:', resp.data)
  return invitationInfo.value = resp.data
}

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

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

    try {
      const unionId = uni.getStorageSync('unionId');

      const res = await invitationAssist(invitationCode, 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();
    }
  }
}

async function initComponent() {
  await tryAssist().catch(console.log)  // catch是为了不阻断逻辑

  await updateInvitationInfo()

  updateShareData({
    pathWithCode: '/pages/activity/1015/home?invitationCode=' + invitationInfo.value.invitationCode,
  })

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

watch(() => props.isLogin, async (newVal) => {
  if (newVal) {
    initComponent().catch(console.log)
  }
})

onMounted(async () => {
  initComponent().catch(console.log)
})

</script>

<template>
  <view class="invite-task" :class="{'debug-mode': debugMode}" :style="style">
    <view class="avatars" v-if="invitationInfo">
      <template
        v-for="i in 2">
        <image
          v-if="isLogin ? i-1 < 2 - invitationInfo.nextRewardNeedCount : false"
          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>