<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: 'My Orders',
    navigationBarBackgroundColor: '#fff',
  },
}
</route>

<script lang="ts" setup>
import { getConfigByCode } from '@/api/common'
import { bindingAddress, orderCancel, orderDetail, orderPink, orderStatusEnum } from '@/api/order'
import DialogBox from '@/components/DialogBox/DialogBox.vue'
import { DialogUtils } from '@/components/DialogBox/utils'
import { t } from '@/locale'
import { formatNumber } from '@/utils'
import { getPageParams, toPage } from '@/utils/page'
import { toast } from '@/utils/toast'

defineOptions({
  name: 'OrderDetail', // 订单详情
})
// z-paging
const paging = ref(null)

const id = ref<any>()
const detail = ref<any>({})
const orderStatusEnumData = ref<any>([])
const openRedEnvelopeRate = ref<any>()
const joinRedEnvelopeRate = ref<any>()

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

async function getConfig(code: string) {
  try {
    const res = await getConfigByCode({ code })
    if (res.code === '200') {
      switch (code) {
        case 'open_red_envelope_rate':
          openRedEnvelopeRate.value = res.data.valueInfo
          break
        case 'join_red_envelope_rate':
          joinRedEnvelopeRate.value = res.data.valueInfo
          break
        default:
          break
      }
    }
  }
  catch {

  }
}

async function getOrderStatus() {
  try {
    const res = await orderStatusEnum({ id: 1 })
    if (res.code === '200') {
      orderStatusEnumData.value = res.data
    }
  }
  catch {

  }
}
async function getDetail() {
  getPink()
  try {
    const res = await orderDetail({ id: id.value })
    if (res.code === '200') {
      detail.value = res.data
      paging.value.complete()
    }
  }
  catch {}
}
const pinkList = ref<any>([])
async function getPink() {
  try {
    const res = await orderPink({ id: id.value })
    if (res.code === '200') {
      pinkList.value = res.data
    }
  }
  catch {

  }
}
onLoad(async (options) => {
  getConfig('open_red_envelope_rate')
  getConfig('join_red_envelope_rate')
  const params = getPageParams(options)
  id.value = params.id
  await getOrderStatus()
})
onShow(() => {
  getDetail()
})

// 跳转到地址簿选择地址
function selectAddress() {
  toPage('/pages/mine/addressBook', {
    selectMode: true,
    orderId: id.value,
  })
}

// 绑定地址到订单
async function bindAddressToOrder(addressId: number) {
  try {
    uni.showLoading({
      title: t('addressBook.select.binding'),
    })

    const res = await bindingAddress({
      orderId: id.value,
      addressId,
    })

    if (res.code === '200') {
      toast.success(t('addressBook.select.success'))
      // 刷新订单详情
      getDetail()
    }
    else {
      toast.error(res.message || t('addressBook.select.failed'))
    }
  }
  catch (error: any) {
    console.error('Bind address error:', error)
    toast.error(t('addressBook.select.networkError'))
  }
  finally {
    uni.hideLoading()
  }
}

// 显示取消订单确认对话框
function showCancelOrderDialog() {
  Object.assign(dialogConfig.value, DialogUtils.info(
    'Are you sure you want to cancel this order?',
    {
      showCancel: true,
      confirmText: 'Yes, Cancel',
      cancelText: 'Keep Order',
    },
  ))
}

// 取消订单
async function cancelOrder() {
  try {
    uni.showLoading({
      title: 'Cancelling order...',
    })

    const res = await orderCancel({ id: id.value })

    if (res.code === '200') {
      // 显示成功提示
      toast.success('Order cancelled successfully!')

      // 刷新订单详情
      getDetail()
    }
    else {
      // 显示错误提示
      toast.error(res.message || 'Failed to cancel order. Please try again.')
    }
  }
  catch (error: any) {
    console.error('Cancel order error:', error)
    // 显示错误提示
    toast.error('Network error. Please check your connection and try again.')
  }
  finally {
    uni.hideLoading()
  }
}

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

  if (confirmText === 'Yes, Cancel') {
    // 确认取消订单
    cancelOrder()
  }

  // 关闭对话框
  handleDialogCancel()
}

// 处理对话框取消事件
function handleDialogCancel() {
  // 关闭对话框
  dialogConfig.value.show = false
}

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

<template>
  <z-paging ref="paging" refresher-only @refresh="getDetail">
    <view class="pt-20rpx">
      <!-- 状态显示 -->
      <template v-if="detail.status !== 4">
        <!-- 已中奖 -->
        <view v-if="detail?.storePink?.status === 2 && detail?.storePink?.lId === 1" class="mb-20rpx bg-#17AA68/80 py-20rpx text-center text-28rpx text-white">
          Congrats，You won the prize in this group！已中奖
          <br>
          You have received
          <text class="text-[var(--wot-color-theme)]">
            ৳{{ 10 }}
          </text>
          group opening reward
        </view>
        <!-- 未中奖 -->
        <view v-else-if="detail?.storePink?.status === 2 && detail?.storePink?.lId === 0" class="mb-20rpx bg-#E61B28/80 py-20rpx text-center text-28rpx text-white">
          So sorry, You didn't win in this group
          <br>
          You have received
          <text class="text-#66C59B">
            ৳8
          </text>
          group opening reward
        </view>
        <!-- 未开奖||未支付 -->
        <view v-else-if="detail?.storePink?.status === 1 || detail?.status === 1" class="mb-20rpx bg-#fff py-20rpx text-center text-28rpx text-white">
          <text v-if="detail?.storePink?.status === 1" class="text-[var(--wot-color-theme)]">
            Please wait for the draw of this group
          </text>
          <text v-else class="text-[var(--wot-color-theme)]">
            Please make payment within：29:59
          </text>
        </view>
        <!-- 拼团头像 -->
        <view class="mb-20rpx bg-white px-20rpx py-20rpx text-center">
          <image v-for="i in 10" :key="i" class="mx-4rpx mb-8rpx h-80rpx w-80rpx rounded-full" src="/static/images/avatar.jpg" />
        </view>
      </template>
      <!-- 地址 -->
      <view v-if="detail?.storePink?.status === 2 && detail?.storePink?.lId === 1" class="mb-20rpx bg-white px-24rpx py-20rpx">
        <!-- 无地址 -->
        <template v-if="!detail.orderAddressVO">
          <view class="flex items-center justify-between" @click="selectAddress">
            <view class="text-28rpx text-[var(--wot-color-theme)]">
              Please provide your shipping address
            </view>
            <wd-icon name="arrow-right" color="#7D7D7D" size="28rpx" />
          </view>
        </template>
        <!-- 有地址 -->
        <template v-else>
          <view class="mb-18rpx flex justify-between border-b-1 border-b-#E1E1E1 border-b-solid pb-18rpx text-24rpx">
            <!-- 物流信息 -->
            <view>{{ detail.deliveryName }}</view>
            <view> DHL：{{ detail.deliveryCode || '-' }}</view>
          </view>
          <view class="mb-20rpx text-24rpx">
            <text class="mr-20rpx">
              {{ detail?.orderAddressVO?.realName }}
            </text>
            <text>{{ detail?.orderAddressVO?.phone }}</text>
          </view>
          <view class="text-22rpx text-#3A444C">
            {{ detail?.orderAddressVO?.province }} {{ detail?.orderAddressVO?.city }} {{ detail?.orderAddressVO?.district }} {{ detail?.orderAddressVO?.detail }} {{ detail?.orderAddressVO?.postCode }}
          </view>
        </template>
      </view>
      <!-- 商品信息 -->
      <wd-card type="rectangle" custom-class="px-24rpx! py-6rpx!" custom-content-class="py-18rpx!" custom-title-class="py-18rpx!" @click="toPage('/pages/productDetail/productDetail', { productId: detail?.orderInfoVO?.[0].productId })">
        <template #title>
          <view class="flex items-center justify-between">
            <view class="text-28rpx text-#000">
              Order ID：{{ detail?.orderInfoVO?.[0].orderNo }}
            </view>
            <wd-text size="26rpx" type="primary" :text="orderStatusEnumData.find((i:any) => i.code === detail?.status)?.name" />
          </view>
        </template>
        <view class="flex items-center gap-24rpx">
          <view class="h-140rpx w-140rpx shrink-0">
            <image
              :src="detail?.orderInfoVO?.[0]?.image"
              class="h-full w-full"
              mode="aspectFit"
            />
          </view>
          <view class="flex-1">
            <view class="line-clamp-2 text-28rpx text-#000">
              {{ detail?.orderInfoVO?.[0].productName }}
            </view>
            <view class="py-4rpx text-24rpx text-#3A444C">
              Color：{{ detail?.orderInfoVO?.[0].sku }}
            </view>
            <view class="flex items-center justify-between text-24rpx">
              <view class="text-[var(--wot-color-theme)]">
                ৳ {{ formatNumber(detail?.orderInfoVO?.[0].price) }}
              </view>
              <view class="text-#3A444C">
                Quantity：{{ detail?.orderInfoVO?.[0].payNum }}
              </view>
            </view>
          </view>
        </view>
      </wd-card>
      <!-- 订单信息 -->
      <view class="bg-white px-24rpx">
        <view class="border-b-1 border-b-#E1E1E1 border-b-solid py-24rpx">
          <view class="mb-12rpx text-28rpx">
            Oder Summary
          </view>
          <view class="flex flex-col gap-16rpx text-#3A444C">
            <view class="flex items-center justify-between text-24rpx">
              <text>SubTotal</text>
              <text>৳{{ formatNumber(detail.totalPrice) }}</text>
            </view>
          </view>
        </view>
        <view class="border-b-1 border-b-#E1E1E1 border-b-solid py-24rpx">
          <view class="mb-12rpx text-28rpx">
            Paid by
          </view>
          <view class="flex flex-col gap-16rpx text-#3A444C">
            <view class="flex items-center justify-between text-24rpx">
              <text>SubTotal</text>
              <text>৳{{ formatNumber(detail.payPrice) }}</text>
            </view>
          </view>
        </view>
        <view class="py-24rpx">
          <view class="flex flex-col gap-16rpx text-#3A444C">
            <view class="flex items-center justify-between text-24rpx">
              <text>Placed on</text>
              <text>{{ detail.createTime }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <template #bottom>
      <view class="flex items-center justify-end bg-white/60 px-28rpx py-30rpx backdrop-blur-20">
        <!-- 取消订单按钮 -->
        <wd-button
          v-if="detail?.status === 1"
          custom-class="mr-16rpx!"
          plain
          @click="showCancelOrderDialog"
        >
          Cancel
        </wd-button>
        <wd-button>Share Now</wd-button>
      </view>
    </template>

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

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