<script setup lang="ts">
import router from '@/router'

definePage({
  name: 'smqjh-giveaways-vip',
  islogin: true,
  style: {
    navigationBarTitleText: '选择赠品',
  },
})
onMounted(() => {
  getGiftsList()
})
const { selectedAddress } = storeToRefs(useUserStore())
const giveawaysList = ref<Api.giftsListModel[]>([])
const isPicking = ref(false)
async function getGiftsList() {
  const res = await Apis.sys.giftsList({})
  giveawaysList.value = res.data || []
}
function handleChange(value: any) {
  console.log(value)
}

async function pickUp() {
  const addressId = selectedAddress.value?.id
  if (!addressId) {
    useGlobalToast().show({ msg: '请选择收货地址' })
    return
  }
  if (!giveawaysList.value.length) {
    useGlobalToast().show({ msg: '暂无可领取赠品' })
    return
  }

  const firstGift = giveawaysList.value[0]
  const hasInvalidGift = giveawaysList.value.some(item => !item.skuId || !item.shopId || !item.channelId)
  if (hasInvalidGift) {
    useGlobalToast().show({ msg: '赠品数据异常' })
    return
  }

  const hasDifferentShopOrChannel = giveawaysList.value.some((item) => {
    return item.shopId !== firstGift.shopId || item.channelId !== firstGift.channelId
  })
  if (hasDifferentShopOrChannel) {
    useGlobalToast().show({ msg: '赠品需来自同一门店和渠道' })
    return
  }

  if (isPicking.value) {
    return
  }
  isPicking.value = true
  try {
    const items = giveawaysList.value.map((item) => {
      return {
        skuId: item.skuId!,
        quantity: Number(item.quantity || 1),
        shopId: item.shopId!,
        channelId: item.channelId!,
      }
    })
    const totalGoodsPrice = giveawaysList.value.reduce((sum, item) => {
      return sum + Number(item.price || 0) * Number(item.quantity || 1)
    }, 0)
    const orderInfo = {
      totalPrice: 0,
      transfee: 0,
      offsetPoints: 0,
      shopName: firstGift.shopName || '',
      price: totalGoodsPrice,
      amount: 0,
      coupon: 0,
      couponName: '',
      orderCouponItemDTOS: [],
      memberGiftAddressId: addressId,
      memberGiftItems: items,
      skuList: giveawaysList.value.map((item) => {
        return {
          prodId: item.spuId || 0,
          num: Number(item.quantity || 1),
          pic: item.picUrl,
          price: item.price ?? '0',
          shopId: item.shopId!,
          shopSkuStocks: String(item.stock ?? ''),
          skuId: item.skuId!,
          skuName: item.spuName || item.skuName,
          spec: item.skuName,
        }
      }),
    }
    router.push({
      name: 'xsb-confirmOrder',
      params: { data: JSON.stringify(orderInfo) },
    })
  }
  finally {
    isPicking.value = false
  }
}
</script>

<template>
  <view class="px24rpx">
    <view class="h-20rpx" />
    <view v-for="item in giveawaysList" :key="item.channelId" class="mb-20rpx flex items-center gap-20rpx rounded-16rpx bg-#FFF p-24rpx">
      <view class="w-32rpx">
        <wd-icon name="check-circle-filled" size="20px" color="#9ED605" />
      </view>
      <view class="flex items-center gap-20rpx">
        <image
          :src="item.picUrl"
          class="h-200rpx w-200rpx rounded-16rpx"
        />
        <view>
          <view class="text-32rpx font-bold line-height-40rpx">
            <text class="mr-8rpx rounded-8rpx bg-#FF4D3A px-12rpx py-4rpx text-22rpx text-#FFF">
              赠品
            </text>
            {{ item.spuName }}
          </view>
          <view class="mt-14rpx text-24rpx text-#AAA">
            规格：{{ item.skuName }}
          </view>
          <view class="mt-14rpx flex items-center justify-between">
            <view class="text-36rpx text-#FF4D3A font-800">
              ￥{{ item.price }}
            </view>
            <wd-input-number :model-value="Number(item.quantity) || 1" disabled @change="handleChange" />
          </view>
        </view>
      </view>
    </view>
    <StatusTip v-if="giveawaysList?.length === 0" tip="暂无内容" />
    <view class="h-180rpx" />
  </view>
  <view class="fixed bottom-0 left-0 right-0 z-9999 h-140rpx w-702rpx rounded-16rpx bg-#FFF p-24rpx shadow-[0rpx_-6rpx_12rpx_2rpx_rgba(0,0,0,0.05)]">
    <wd-button custom-class="h-80rpx w-full" :loading="isPicking" @click="pickUp">
      免费领取
    </wd-button>
  </view>
</template>

<style lang="scss" scoped></style>
