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

<script lang="ts" setup>
import { getConfigByCode } from '@/api/common'
import { orderCancel, orderDetail, orderPink, orderStatusEnum, 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 { formatNumber } from '@/utils'
import { toPage } from '@/utils/page'
import { toast } from '@/utils/toast'

defineOptions({
  name: 'OrderDetail', // 订单详情
})

// z-paging
const paging = ref(null)

const id = ref<any>()
const orderNo = ref<string>()
const isPayOrder = ref<boolean>(false)
const isPageLoading = ref(true) // 页面加载状态
const detail = ref<any>({})
const orderStatusEnumData = ref<any>([])
const openRedEnvelopeRate = ref<any>()
const joinRedEnvelopeRate = ref<any>()
const countdown = ref('00:00')
const timer = ref()
const hasCountdownEnded = ref(false) // 标记倒计时是否已结束并查询过

// DialogBox 函数式调用配置
const dialogConfig = ref<any>({})
const dialogType = ref<'cancel' | 'pay' | 'recharge' | ''>('')

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 {

  }
}
function startCountdown() {
  // 清除之前的定时器
  if (timer.value)
    clearInterval(timer.value)

  if (!detail.value?.createTime || detail.value?.status !== 1) {
    countdown.value = '00:00'
    return
  }

  // 重置倒计时结束标记
  hasCountdownEnded.value = false

  // 计算过期时间（创建时间 + 20分钟）
  const createTime = new Date(detail.value.createTime).getTime()
  const expireTime = createTime + 20 * 60 * 1000

  timer.value = setInterval(() => {
    const now = Date.now()
    const diff = expireTime - now

    if (diff <= 0) {
      clearInterval(timer.value)
      countdown.value = '00:00'
      // 只在第一次倒计时结束时查询一次
      if (!hasCountdownEnded.value) {
        hasCountdownEnded.value = true
        getDetail() // 刷新订单状态
      }
      return
    }

    const minutes = Math.floor(diff / 1000 / 60)
    const seconds = Math.floor((diff / 1000) % 60)
    countdown.value = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
  }, 1000)
}

// 用户主动刷新时调用此函数
async function handleRefresh() {
  // 重置倒计时结束标记，允许重新查询
  hasCountdownEnded.value = false
  await getDetail()
}

async function getDetail() {
  try {
    isPageLoading.value = true
    // 根据参数类型构建请求参数
    const params = orderNo.value ? { orderNo: orderNo.value } : { id: id.value }
    const res = await orderDetail(params)
    if (res.code === '200') {
      detail.value = res.data
      // 如果通过 orderNo 查询，更新 id 值用于其他接口调用
      if (orderNo.value && detail.value?.orderId) {
        id.value = detail.value.orderId
      }
      if (detail.value?.status === 1) {
        // 只有在倒计时未结束时才启动倒计时，防止倒计时结束后重复查询
        if (!hasCountdownEnded.value) {
          startCountdown() // 开始倒计时
        }
        // if (isPayOrder.value) {
        //   // 自动调用支付接口
        //   await goPay()
        // }
      }
      else {
        // 状态已变化，重置标记
        hasCountdownEnded.value = false
      }
      await getPink()
      paging.value.complete()
    }
  }
  finally {
    isPageLoading.value = false
  }
}
const pinkList = ref<any>([])
async function getPink() {
  try {
    const res = await orderPink({ orderNo: orderNo.value })
    if (res.code === '200') {
      pinkList.value = res.data
    }
  }
  catch {

  }
}

// 跳转到地址簿选择地址
function selectAddress() {
  toPage({ url: '/pages/mine/addressBook', params: {
    selectMode: '1',
    orderId: detail.value?.orderId,
  } })
}

// 显示取消订单确认对话框
function showCancelOrderDialog() {
  dialogType.value = 'cancel'
  Object.assign(dialogConfig.value, DialogUtils.info(
    t('orderDetail.dialog.cancel.title'),
    {
      showCancel: true,
      confirmText: t('orderDetail.dialog.cancel.confirm'),
      cancelText: t('orderDetail.dialog.cancel.keep'),
      confirmPlain: true,
    },
  ))
}

// 取消订单
async function cancelOrder() {
  try {
    uni.showLoading({
      title: t('orderDetail.cancel.loading'),
      mask: true,
    })

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

    if (res.code === '200') {
      // 显示成功提示
      toast.success(t('orderDetail.cancel.success'))

      // 刷新订单详情
      getDetail()
    }
    else {
      // 显示错误提示
      toast.error(res.message || t('orderDetail.cancel.error'))
    }
  }
  catch (error: any) {
    console.error('Cancel order error:', error)
    // 显示错误提示
    toast.error(t('orderDetail.cancel.error'))
  }
  finally {
    uni.hideLoading()
  }
}

// 处理对话框确认事件
function handleDialogConfirm() {
  if (dialogType.value === 'cancel') {
    cancelOrder()
  }
  else if (dialogType.value === 'pay') {
    goPay()
  }
  else if (dialogType.value === 'recharge') {
    toPage({ url: '/pages/wallet/recharge', params: { price: detail.value?.payPrice }, isRedirect: true })
  }
  // 关闭对话框
  handleDialogClose()
}

// 处理对话框关闭事件
function handleDialogClose() {
  dialogConfig.value.show = false
}
// 支付
// 显示支付余额去充值提示
function showRechargeDialog() {
  dialogType.value = 'recharge'
  Object.assign(dialogConfig.value, DialogUtils.info(
    t('orderDetail.rechargeDialog.title'),
    {
      showCancel: false,
      confirmText: t('orderDetail.rechargeDialog.confirm'),
      cancelText: '',
      confirmPlain: true,
    },
  ))
}
// 显示支付确认对话框
function showPayOrderDialog() {
  dialogType.value = 'pay'
  Object.assign(dialogConfig.value, DialogUtils.info(
    t('orderDetail.payDialog.title'),
    {
      showCancel: false,
      cancelText: '',
      confirmText: t('orderDetail.payDialog.confirm'),
      confirmPlain: false,
    },
  ))
}
async function goPay() {
  uni.showLoading({
    title: t('orderDetail.payment.loading'),
    mask: true,
  })
  try {
    const payRes = await payOrder({
      orderId: detail.value?.orderId,
      type: detail.value?.storePink?.kId ? 'join' : 'open',
    })
    console.log(payRes)
    if (payRes.code === '200') {
      toast.success(t('orderDetail.payment.success'))
      getDetail()
    }
  }
  finally {
    uni.hideLoading()
  }
}

function handleClick() {
  if (detail.value?.status === 1) {
    // 去支付
    showPayOrderDialog()
  }
  else {
    // 去分享
  }
}
const timeMap = {
  create_order: t('orderDetail.time.placed'),
  pay_success: t('orderDetail.time.paid'),
  delivery: t('orderDetail.time.shipped'),
  receive: t('orderDetail.time.completed'),
}

function copyDelivery() {
  uni.setClipboardData({
    data: `${detail.value.deliveryName}: ${detail.value.deliveryId}`,
  })
}

onLoad(async (options) => {
  getConfig('open_red_envelope_rate')
  getConfig('join_red_envelope_rate')
  const params = options
  orderNo.value = params.orderNo
  isPayOrder.value = params.isPayOrder
  await getOrderStatus()
})
const balance = ref<number>(0)
onShow(async () => {
  // 重置倒计时结束标记，允许重新查询
  hasCountdownEnded.value = false
  await getDetail()
  if (isPayOrder.value && detail.value?.status === 1) {
    const res = await getWalletAccountInfo()
    console.log(res)
    balance.value = res?.data?.balance
    if (balance.value < detail.value?.payPrice) {
      // 余额不足，提示去充值
      showRechargeDialog()
    }
    else {
      // 余额充足，显示支付对话框
      showPayOrderDialog()
    }
  }
})

onUnmounted(() => {
  if (timer.value)
    clearInterval(timer.value)
})
</script>

<template>
  <z-paging ref="paging" refresher-only @refresh="handleRefresh">
    <!-- 页面加载时显示骨架屏 -->
    <template v-if="isPageLoading">
      <view class="pt-20rpx">
        <!-- 状态卡片骨架屏（模拟状态显示区域） -->
        <view class="mb-20rpx bg-white py-20rpx text-center">
          <wd-skeleton
            :row-col="[{ width: '180rpx', height: '28rpx', marginLeft: 'auto', marginRight: 'auto' }]"
            animation="gradient"
          />
        </view>

        <!-- 地址信息骨架屏（模拟地址选择区域） -->
        <view class="mb-20rpx bg-white px-24rpx py-20rpx">
          <wd-skeleton
            :row-col="[
              { width: '150rpx', height: '28rpx' }, // 地址标题或添加地址
              { width: '200rpx', height: '24rpx', marginTop: '12rpx' }, // 收货人信息
              { width: '100%', height: '22rpx', marginTop: '8rpx' }, // 详细地址
            ]"
            animation="gradient"
          />
        </view>

        <!-- 商品信息骨架屏（使用实际的 wd-card 结构） -->
        <wd-card type="rectangle" custom-class="px-24rpx! py-6rpx!" custom-content-class="py-18rpx!" custom-title-class="py-18rpx!">
          <template #title>
            <!-- 订单头部：订单号 + 状态 -->
            <wd-skeleton
              :row-col="[
                [{ width: '250rpx', height: '28rpx' }, { width: '60rpx', height: '26rpx', marginLeft: 'auto' }],
              ]"
              animation="gradient"
            />
          </template>
          <!-- 商品区域：图片 + 信息 -->
          <wd-skeleton
            :row-col="[
              [
                { width: '140rpx', height: '140rpx', type: 'rect' },
                [
                  { width: '100%', height: '40rpx' }, // 商品标题第一行
                  { width: '80%', height: '40rpx', marginTop: '8rpx' }, // 商品标题第二行
                  { width: '120rpx', height: '24rpx', marginTop: '4rpx' }, // 颜色规格
                  [{ width: '100rpx', height: '24rpx' }, { width: '80rpx', height: '24rpx', marginLeft: 'auto' }], // 价格和数量
                ],
              ],
            ]"
            animation="gradient"
          />
        </wd-card>

        <!-- 订单信息骨架屏 -->
        <view class="bg-white px-24rpx">
          <!-- 订单摘要 -->
          <view class="border-b-1 border-b-#e8e8e8 border-b-solid py-24rpx">
            <wd-skeleton
              :row-col="[
                { width: '120rpx', height: '28rpx' }, // 摘要标题
                [{ width: '80rpx', height: '24rpx' }, { width: '100rpx', height: '24rpx', marginLeft: 'auto' }], // SubTotal 行
              ]"
              animation="gradient"
            />
          </view>

          <!-- 支付方式 -->
          <view class="border-b-1 border-b-#e8e8e8 border-b-solid py-24rpx">
            <wd-skeleton
              :row-col="[
                [{ width: '100rpx', height: '28rpx' }, { width: '140rpx', height: '24rpx', marginLeft: 'auto' }],
              ]"
              animation="gradient"
            />
          </view>

          <!-- 订单状态记录 -->
          <view class="py-24rpx">
            <wd-skeleton
              :row-col="[
                [{ width: '90rpx', height: '24rpx' }, { width: '150rpx', height: '24rpx', marginLeft: 'auto' }],
                [{ width: '80rpx', height: '24rpx' }, { width: '150rpx', height: '24rpx', marginLeft: 'auto' }],
              ]"
              animation="gradient"
            />
          </view>
        </view>
      </view>
    </template>

    <!-- 实际内容 -->
    <template v-else>
      <view class="pt-20rpx">
        <!-- 状态显示 lId=1是中奖0是未中奖。storePink?.status是拼团状态 detail?.status是订单状态 -->
        <template v-if="detail.status !== 4 && detail?.status !== 2">
          <view v-if="detail?.status === 9" class="mb-20rpx bg-#17AA68/80 py-20rpx text-center text-28rpx text-white">
            {{ t('orderDetail.status9.sellBackPrefix') }}
            <text class="text-[var(--wot-color-theme)]">
              ৳{{ formatNumber(detail?.recycleAmount) }}
            </text>
            <br>
            {{ t('orderDetail.status9.receivePrefix') }}
            <text class="text-[var(--wot-color-theme)]">
              ৳{{ formatNumber(detail?.brokerage) }}
            </text>
            {{ t('orderDetail.status9.rewardSuffix') }}
          </view>
          <!-- 已中奖 -->
          <view v-else-if="detail?.storePink?.status === 2 && detail?.storePink?.lId === 1" class="mb-20rpx bg-#17AA68/80 py-20rpx text-center text-28rpx text-white">
            {{ t('orderDetail.congrats') }}
            <br>
            {{ t('orderDetail.receiveReward') }}
            <text class="text-[var(--wot-color-theme)]">
              ৳{{ detail.brokerage }}
            </text>
          </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">
            {{ t('orderDetail.sorry') }}
            <br>
            {{ t('orderDetail.receiveReward') }}
            <text class="text-#66C59B">
              ৳{{ detail.brokerage }}
            </text>
          </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 && detail?.status !== 1" class="text-[var(--wot-color-theme)]">
              {{ t('orderDetail.waiting') }}
            </text>
            <text v-else class="text-[var(--wot-color-theme)]">
              {{ t('orderDetail.paymentCountdown') }} {{ countdown }}
            </text>
          </view>
          <!-- 拼团头像 -->
          <view v-if="pinkList && pinkList.length" class="mb-20rpx bg-white px-20rpx py-20rpx text-center">
            <image v-for="i in pinkList" :key="i" class="mx-4rpx mb-8rpx h-80rpx w-80rpx border-1 border-transparent rounded-full border-solid" :style="{ borderColor: i.lId ? 'var(--wot-color-theme)' : 'transparent' }" :src="i.avatar" />
          </view>
        </template>
        <!-- 地址 -->
        <view v-if="detail?.storePink?.status === 2 && detail?.storePink?.lId === 1 && detail?.status !== 9" 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)]">
                {{ t('orderDetail.address.add') }}
              </view>
              <wd-icon name="arrow-right" color="#7D7D7D" size="28rpx" />
            </view>
          </template>
          <!-- 有地址 -->
          <template v-else>
            <view v-if="detail.deliveryId" class="mb-18rpx flex justify-between border-b-1 border-b-#e8e8e8 border-b-solid pb-18rpx text-24rpx">
              <!-- 物流信息 -->
              <view>{{ $t('orderDetail.deliveryPartner') }}</view>
              <view class="flex items-center gap-8rpx" @click="copyDelivery">
                <text>{{ detail.deliveryName }}: {{ detail.deliveryId || '-' }}</text>
                <wd-icon name="file-copy" size="28rpx" />
              </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({ url: '/pages/productDetail/productDetail', params: { productId: detail?.orderInfoVO?.[0].productId } })">
          <template #title>
            <view class="flex items-center justify-between">
              <view class="text-28rpx text-#000">
                {{ t('orderDetail.address.orderNo') }}：{{ 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 h-80rpx break-all text-28rpx text-#000">
                {{ detail?.orderInfoVO?.[0].productName }}
              </view>
              <view class="py-4rpx text-24rpx text-#3A444C">
                {{ t('orderDetail.address.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">
                  {{ t('orderDetail.address.quantity') }}：{{ detail?.orderInfoVO?.[0].payNum }}
                </view>
              </view>
            </view>
          </view>
        </wd-card>
        <!-- 订单信息 -->
        <view class="bg-white px-24rpx">
          <view class="border-b-1 border-b-#e8e8e8 border-b-solid py-24rpx">
            <view class="mb-12rpx text-28rpx">
              {{ t('orderDetail.summary.title') }}
            </view>
            <view class="flex flex-col gap-16rpx text-#3A444C">
              <view class="flex items-center justify-between text-24rpx">
                <text>{{ $t('orderDetail.subTotal') }}</text>
                <text>৳{{ formatNumber(detail.totalPrice) }}</text>
              </view>
            </view>
          </view>
          <view v-if="detail?.status !== 1" class="border-b-1 border-b-#e8e8e8 border-b-solid py-24rpx">
            <view class="mb-12rpx text-28rpx">
              {{ t('orderDetail.payment.title') }}
            </view>
            <view class="flex flex-col gap-16rpx text-#3A444C">
              <view class="flex items-center justify-between text-24rpx">
                <text>{{ detail.payType }}</text>
                <text>৳{{ formatNumber(detail.payPrice) }}</text>
              </view>
            </view>
          </view>
          <view v-if="detail?.orderStatusVO?.length" class="py-24rpx">
            <template v-for="i in detail?.orderStatusVO" :key="i.id">
              <view v-if="timeMap[i.changeType]" class="mb-16rpx flex flex-col text-#3A444C">
                <view class="flex items-center justify-between text-24rpx">
                  <text>{{ timeMap[i.changeType] }}</text>
                  <text>{{ i.createTime }}</text>
                </view>
              </view>
            </template>
          </view>
        </view>
      </view>
    </template>

    <template #bottom>
      <view v-if="detail?.status === 1" 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"
        >
          {{ t('orderDetail.button.cancel') }}
        </wd-button>
        <wd-button @click="handleClick">
          {{ t('orderDetail.button.pay') }}
        </wd-button>
      </view>
    </template>

    <!-- DialogBox 函数式调用 -->
    <DialogBox
      v-bind="dialogConfig"
      @confirm="handleDialogConfirm"
      @cancel="handleDialogClose"
      @close="handleDialogClose"
    >
      <view v-if="dialogType === 'pay'">
        <view class="font-blod relative text-32rpx">
          <text> {{ $t('orderDetail.paymentMethod') }}</text>
          <wd-icon name="close-normal" custom-class="absolute right-0 top-1/2 -translate-y-1/2" size="40rpx" @click="handleDialogClose" />
        </view>
        <view class="py-60rpx">
          <text class="text-40rpx">
            ৳
          </text>
          <text class="text-60rpx">
            {{ formatNumber(detail.payPrice) }}
          </text>
        </view>
        <view class="pb-28rpx text-left">
          <view class="text-24rpx font-bold">
            {{ $t('orderDetail.paymentMethod') }}
          </view>
          <view class="my-14rpx border-b-1px border-b-#EBEBEB border-b-solid" />
          <view class="flex items-center justify-between text-24rpx">
            <view class="flex items-center">
              <view class="text-24rpx">
                <text>{{ $t('orderDetail.bandhuBuyWallet') }} (</text>
                <text class="text-[var(--wot-color-theme)]">
                  {{ $t('orderDetail.walletBalanceText') }}: ৳{{ formatNumber(balance) }}
                </text>
                <text>)</text>
              </view>
            </view>
            <view>
              <image
                src="/static/icons/circle-check.png"
                class="h-36rpx w-36rpx"
              />
            </view>
          </view>
        </view>
      </view>
    </DialogBox>
  </z-paging>
</template>

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