<script setup lang="ts">
import router from '@/router'
import { StaticUrl } from '@/config'

const { userInfo } = storeToRefs(useUserStore())
definePage({
  name: 'charge-voucher',
  islogin: true,
  style: {
    navigationBarTitleText: '',
    navigationStyle: 'custom',
  },
})
const { statusBarHeight, MenuButtonHeight, opcity } = storeToRefs(useSysStore())
const couponBalance = ref()
onLoad((options: any) => {
  console.log(options, '路由参数')
  couponBalance.value = options.couponBalance
})
onMounted(() => {
  opcity.value = 0
  getRechargeLevels()
})
onPageScroll((e) => {
  const calculatedOpacity = e.scrollTop / 100
  opcity.value = Math.min(1, Math.max(0.1, calculatedOpacity))
})

const selectIndex = ref<number>()

/**
 * 获取充值挡位
 */
const rechargeLevels = ref<Api.RechargeLevel[]>([])
async function getRechargeLevels() {
  const res = await Apis.charge.getReChargeLevel({})
  rechargeLevels.value = res.data
}
function selectVoucher(index: number) {
  selectIndex.value = index
  console.log('Selected voucher index:', index)
}

// 安全获取充值档位
function getSelectedLevel(): Api.RechargeLevel | undefined {
  if (selectIndex.value === undefined || !rechargeLevels.value)
    return undefined
  return rechargeLevels.value[selectIndex.value]
}

async function handleH5PayResult(orderNumber: string) {
  const isPaySuccess = await useUserStore().pollOrderPaySuccess(orderNumber)
  if (isPaySuccess) {
    router.replace({ name: 'charge-buy-a-ticket-list' })
    return
  }

  useGlobalToast().show({ msg: '暂未查询到支付成功，请稍后在订单列表查看' })
}

/**
 * 提交支付
 */
async function submitPay() {
  if (selectIndex.value === undefined) {
    return useGlobalMessage().alert('请选择充值金额')
  }
  const selectedLevel = getSelectedLevel()
  if (!selectedLevel) {
    return
  }
  try {
    await uni.showLoading({ title: '下单中...', mask: true })
    const orderRes = await Apis.charge.addPurchaseRecord({
      data: {
        couponAmount: selectedLevel.money,
        consigneeName: userInfo.value?.nickName || '',
        consigneeMobile: userInfo.value?.mobile || '',
      },
    })
    const orderNumber = orderRes.data
    if (!orderNumber) {
      uni.hideLoading()
      await uni.showToast({ title: '下单失败', icon: 'none' })
      return
    }
    // #ifdef MP-WEIXIN
    const payRes = await Apis.charge.wxJsApiPay({
      data: {
        orderNumber,
      },
    })
    uni.hideLoading()
    await useUserStore().getWxCommonPayment(payRes.data)
    await useUserStore().paySuccess('charge-buy-a-ticket-list', 'subPack-charge/chargeBuyaTicketList/chargeBuyaTicketList')
    // #endif
    // #ifdef H5
    uni.hideLoading()
    useUserStore().handleCommonWechatPay(orderNumber, 'wx')
    await handleH5PayResult(orderNumber)
    // #endif
  }
  catch (error) {
    uni.hideLoading()
    console.error('支付失败:', error)
    await useUserStore().payError('charge-buy-a-ticket-list', 'subPack-charge/chargeBuyaTicketList/chargeBuyaTicketList')
  }
}

/**
 * 申请退款
 */
function refund() {
  useGlobalMessage().confirm({
    title: '提示',
    msg: '退款按照购券记录进行逐笔退款，可能产生多笔退款到账记录，请注意查收。',
    success: async () => {
      const res = await Apis.charge.userCouponRefund({})
      if (res.code === '00000') {
        useGlobalMessage().confirm({
          title: '提示',
          msg: '申请退款成功,预计3个工作日内分一笔或多笔退还，到期如未到账请联系客服!',
          success: () => {
            router.back()
          },
          fail: () => {
          },
        })
      }
    },
  })
}
</script>

<template>
  <view class="min-h-screen" :style="{ backgroundImage: `url(${StaticUrl}/buy-center-bg.png)`, backgroundSize: 'cover', backgroundPosition: 'center' }">
    <wd-navbar
      title="购券中心" :custom-style="`background-color: rgba(226, 255, 145, ${opcity})`" :bordered="false"
      :z-index="99" safe-area-inset-top left-arrow fixed @click-left="router.back()"
    />
    <view :style="{ paddingTop: `${(Number(statusBarHeight) || 44) + MenuButtonHeight + 12}px` }" class="px24rpx">
      <view class="h-342rpx" />
      <view class="relative rounded-16rpx from-[#E1FF90] via-[#FAFFEE] to-[#FFFFFF] bg-gradient-to-b p-12rpx">
        <image
          class="absolute right-12rpx top-12rpx h-144rpx w-144rpx"
          :src="`${StaticUrl}/buy-center-cardIcon.png`"
          mode="scaleToFill"
        />
        <view class="mt-16rpx text-center">
          <view class="text-28rpx">
            平台券金额
          </view>
          <view class="mt-16rpx text-28rpx font-800">
            {{ couponBalance }}
            <text class="text-24rpx">
              元
            </text>
          </view>
        </view>
        <view class="mb-16rpx mt-28rpx flex items-center justify-around text-28rpx">
          <view @click="router.push({ name: 'charge-buy-a-ticket-list' })">
            充值记录
          </view>
          <view class="h-40rpx w-2rpx bg-#E6E6E6" />
          <view @click="refund">
            退款
          </view>
        </view>
      </view>
      <view class="mt-20rpx">
        <view class="text-32rpx font-bold">
          本次充值
        </view>
        <view class="mt-24rpx flex flex-wrap items-center justify-start gap-20rpx">
          <view v-for="(item, index) in rechargeLevels" :key="index" class="h-136rpx w-220rpx text-center" :class="selectIndex === index ? 'text-[#9ED605]' : 'text-#2B303Ac'" :style="{ backgroundImage: `url(${StaticUrl}/${selectIndex === index ? 'buy-center-rechargesel' : 'buy-center-recharge'}.png)`, backgroundSize: 'cover', backgroundPosition: 'center' }" @click="selectVoucher(index)">
            <view class="h-80rpx text-28rpx font-bold line-height-[80rpx]">
              {{ item?.money }}<text class="text-24rpx">
                元
              </text>
            </view>
            <view class="h-46rpx text-28rpx font-bold line-height-[46rpx] font-italic">
              {{ item?.name }}
            </view>
          </view>
        </view>
      </view>
      <view class="mt-24rpx">
        <view class="font-bold">
          温馨提示
        </view>
        <view class="mt-24rpx text-24rpx text-#AAAAAA">
          <view>1.平台券仅限本平台使用，不可转赠和出售。</view>
          <view class="mt-20rpx">
            2.平台券仅可用于本平台充电服务，若订单金额超过平台券余额，
            需补足差价；若余额有剩余，可留存下次使用；剩余平台券余额支
            持手动退款。
          </view>
          <view class="mt-20rpx">
            3.平台保留调整平台券使用规则的权利，调整前将提前公告。
            如有疑问，请联系客服。
          </view>
        </view>
      </view>
      <view
        class="fixed bottom-66rpx left-24rpx h-100rpx w-702rpx rounded-16rpx text-center text-28rpx font-800 line-height-[100rpx]"
        :class="selectIndex === undefined ? 'bg-[#CCCCCC] text-white' : 'bg-[linear-gradient(90deg,#DBFC81_0%,#9ED605_100%)] text-black shadow-[inset_0rpx_6rpx_20rpx_2rpx_#FFFFFF]'"
        @click="submitPay"
      >
        立即支付
      </view>
    </view>
  </view>
</template>

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