<route lang="json5" type="page">
{
  layout: 'default',
  needLogin: true,
  style: {
    navigationBarTitleText: '%checkout.title%',
    navigationBarBackgroundColor: '#fff',
  },
}
</route>

<script lang="ts" setup>
import { computedPrice, createOrder, loadPre, payOrder } from '@/api/order'
import { getWalletAccountInfo } from '@/api/wallet'
import DialogBox from '@/components/DialogBox/DialogBox.vue'
import { DialogUtils } from '@/components/DialogBox/utils'
import { t } from '@/locale'
import { useUserStore } from '@/store'
import { formatNumber } from '@/utils'
import { getPageParams, toPage } from '@/utils/page'

defineOptions({
  name: 'CheckOut', // 结账页面
})
const userStore = useUserStore()
const userInfo = computed(() => {
  return userStore.userInfo
})
const queryParams = ref<any>({})
onLoad((options) => {
  const params = getPageParams(options)
  queryParams.value = params
  getPrice()
})

// 商品详情
const orderDetail = ref<any>({})

// 订单摘要
const orderSummary = ref({
  SubTotal: 0,
  // Voucher: 0,
  Total: 0,
})
// 钱包余额
const walletBalance = ref(0)
async function getPrice() {
  // 预下单详情
  const preOrderRes = await loadPre({ preOrderNo: queryParams.value.preOrderId })
  console.log(preOrderRes)
  orderDetail.value = preOrderRes?.data?.orderInfoVo?.orderDetailList?.[0]
  // 计算价格
  const computedPriceRes = await computedPrice({ preOrderNo: queryParams.value.preOrderId, shippingType: 1 })
  console.log(computedPriceRes)
  orderSummary.value.SubTotal = computedPriceRes?.data?.proTotalFee
  orderSummary.value.Total = computedPriceRes?.data?.payFee
  // 获取钱包信息-查询余额
  const walletInfoRes = await getWalletAccountInfo()
  console.log(walletInfoRes)
  walletBalance.value = walletInfoRes?.data?.balance
}

// 支付方式
const paymentMethods = ref([
  {
    id: 'bandhubuy',
    name: 'BandhuBuy Wallet',
    balance: 2000.00,
    selected: true,
    icon: '/static/icons/wallet-icon.png',
  },
])

// 选中的支付方式
const selectedPayment = ref('bandhubuy')

// DialogBox 函数式调用配置
const dialogConfig = ref({})

// 处理支付方式选择
function selectPayment(methodId: string) {
  selectedPayment.value = methodId
  paymentMethods.value.forEach((method) => {
    method.selected = method.id === methodId
  })
}

// 显示余额不足对话框
function showInsufficientBalanceDialog() {
  Object.assign(dialogConfig.value, DialogUtils.info(
    t('checkout.dialog.insufficientBalance'),
    {
      tip: t('checkout.dialog.rechargeDiscount'),
      showTip: true,
      confirmText: t('checkout.dialog.rechargeNow'),
    },
  ))
}

// 下单处理
async function handlePlaceOrder() {
  const params = {
    preOrderNo: queryParams.value.preOrderId,
    type: queryParams.value.groupType,
    pinkId: queryParams.value.pinkId,
    cid: queryParams.value.cid,
    groupType: queryParams.value.groupType,
  }
  const orderRes = await createOrder(params)
  console.log(orderRes)
  if (orderRes.code === '200') {
    const payRes = await payOrder({
      orderId: orderRes?.data?.columns?.orderNo,
      type: queryParams.value.groupType,
    })
    console.log(payRes)
    if (payRes.code === '8000') {
      showInsufficientBalanceDialog()
    }
    else {
      toPage('/pages/myOrders/myOrders', {}, true)
    }
  }
}

// 处理对话框确认事件
function handleDialogConfirm() {
  const config = dialogConfig.value as any
  const { type, confirmText } = config

  // 根据确认按钮文本判断是哪种对话框
  if (confirmText === t('checkout.dialog.rechargeNow')) {
    // 余额不足，跳转到充值页面
    uni.navigateTo({ url: '/pages/wallet/recharge' })
  }
  else if (type === 'success') {
    // 支付成功，跳转到订单页面
    uni.showToast({ title: t('checkout.toast.redirecting'), icon: 'none' })
  }
  else if (type === 'error') {
    // 支付失败或网络错误，重新尝试
    uni.showToast({ title: t('checkout.toast.retrying'), icon: 'loading' })
  }

  // 关闭对话框
  dialogConfig.value = {}
}

// 处理对话框关闭事件
function handleDialogClose() {
  dialogConfig.value = {}
}
</script>

<template>
  <z-paging>
    <view class="pt-20rpx">
      <view class="mb-20rpx flex items-center gap-24rpx bg-white p-24rpx">
        <image
          :src="orderDetail.image"
          class="h-160rpx w-160rpx shrink-0"
          mode="aspectFit"
        />
        <view class="flex-1">
          <view class="line-clamp-2 text-28rpx">
            {{ orderDetail.productName }}
          </view>
          <view class="py-4rpx text-24rpx text-#3A444C">
            {{ $t('checkout.selected') }}: {{ orderDetail.sku }}
          </view>
          <view class="flex items-center justify-between text-24rpx">
            <view class="text-#FF0010">
              ৳ {{ formatNumber(orderDetail.price) }}
            </view>
            <view class="text-#3A444C">
              {{ $t('checkout.quantity') }}：{{ orderDetail.payNum }}
            </view>
          </view>
        </view>
      </view>
      <view class="mb-20rpx bg-white p-24rpx">
        <view class="mb-12rpx text-28rpx">
          {{ $t('checkout.orderSummary') }}
        </view>
        <view class="flex flex-col gap-16rpx text-#3A444C">
          <template v-for="(item, key) in orderSummary" :key="key">
            <view class="flex items-center justify-between text-24rpx">
              <text>{{ key }}</text>
              <text>৳ {{ formatNumber(item) }}</text>
            </view>
          </template>
        </view>
      </view>
      <view class="bg-white p-24rpx">
        <view class="mb-12rpx text-28rpx">
          {{ $t('checkout.selectPaymentMethod') }}
        </view>
        <view class="flex flex-col gap-16rpx text-#3A444C">
          <view class="flex items-center justify-between text-24rpx">
            <view class="flex items-center">
              <image
                src="/static/images/avatar.jpg"
                class="mr-32rpx h-68rpx w-68rpx rounded-full"
              />
              <view class="text-24rpx">
                <text>BandhuBuy Wallet(</text>
                <text class="text-[var(--wot-color-theme)]">
                  {{ $t('checkout.walletBalance') }}: ৳ {{ formatNumber(walletBalance) }}
                </text>
                <text>)</text>
              </view>
            </view>
            <view>
              <image
                src="/static/icons/circle-check.png"
                class="h-36rpx w-36rpx"
              />
            </view>
          </view>
        </view>
      </view>
    </view>
    <template #bottom>
      <view class="flex items-center justify-end bg-white/60 px-28rpx py-30rpx backdrop-blur-20">
        <view class="mr-16rpx text-24rpx">
          <text>{{ $t('checkout.total') }}:</text>
          <text class="text-[var(--wot-color-theme)]">
            ৳ {{ formatNumber(orderSummary.Total) }}
          </text>
        </view>
        <wd-button @click="handlePlaceOrder">
          {{ $t('checkout.placeOrder') }}
        </wd-button>
      </view>
    </template>

    <!-- DialogBox 函数式调用 -->
    <DialogBox
      v-bind="dialogConfig"
      @confirm="handleDialogConfirm"
      @close="handleDialogClose"
    />
  </z-paging>
</template>

<style lang="scss" scoped>
.space-y-24rpx > * + * {
  margin-top: 24rpx;
}
</style>
