<template>
  <view class="bg-[var(--page-bg-color)] min-h-screen overflow-hidden order-list" :style="themeColor()">
    <!-- #ifdef MP-WEIXIN -->
    <!-- <top-tabbar :data="topTabbarData" :scrollBool="topTabarObj.getScrollBool()" /> -->
    <!-- #endif -->
    <view class="fixed left-0 top-0 right-0 z-10" v-if="statusLoading">
        <scroll-view :scroll-x="true" class="tab-style-2">
            <view class="tab-content">
                <view class="tab-items" :class="{ 'class-select': orderState === item.status.toString() }" @click="orderStateFn(item.status)" v-for="(item, index) in orderStateList">{{ item.name }}</view>
            </view>
        </scroll-view>
    </view>
      <mescroll-body ref="mescrollRef" top="88rpx" @init="mescrollInit" :down="{ use: false }" @up="getPintuanOrderFn">
            <view class="sidebar-margin pt-[var(--top-m)]" v-if="list.length">
                <template v-for="(item, index) in list" :key="index">
                    <view class="mb-[var(--top-m)] card-template">
                        <view @click.stop="toLink(item)">
                            <view class="flex justify-between items-center">
                                <view class="text-[#303133] text-[24rpx] font-400 leading-[36rpx] flex items-center">
                                    <view v-if="item.source_name" class="text-primary text-[18rpx] border-primary border-[2rpx] border-solid rounded-[4rpx] leading-[24rpx] px-[3rpx]">{{ item.source_name }}</view>
                                    <view class="ml-[10rpx] text-[24rpx] font-400 text-[#303133]">{{ item.create_time }}</view> 
                                    <!-- <text>{{ t('orderNo') }}:</text>
                                    <text class="ml-[10rpx]">{{ item.order_no }}</text>
                                    <text class="text-[#303133] text-[26rpx] font-400 nc-iconfont nc-icon-fuzhiV6xx1 ml-[11rpx]" @click.stop="copy(item.order_no)"></text> -->
                                </view>
								<!-- <view v-if="item.status  == -1" class="text-[#303133] text-[26rpx] max-w-[85px] leading-[34rpx] truncate" :class="{'text-primary': item.status  == 1,'!text-[var(--text-color-light9)]' :item.status  == 5 || item.status  == -1}">{{ item.close_type_name }}</view> -->
                                <!-- <view class="text-[#303133] text-[26rpx] leading-[34rpx]" :class="{'text-primary': item.order_status  == 'payment','!text-[var(--text-color-light9)]' :item.order_status  == 'refund_ing' || item.order_status  == 'close'}">{{ item.order_status }}</view> -->
                                <view class="text-[26rpx] leading-[34rpx]" :class="{'text-primary': item.group_status=='success', '!text-[var(--text-color-light9)]' :item.order_refund_status=='refunded'}" >{{ item.order_refund_status=='refunded'?item.order_refund_status_name: item.group_status=='failed'?'拼团失败':item.group_status=='success'?'拼团成功':item.group_status=='process'?'拼团中':item.order_status_name }}</view>
                                <!-- text-primary -->
                                <!-- !text-[var(--text-color-light9)] -->
                            </view> 
                            <view>
                                <view class="flex box-border mt-[20rpx]">
                                    <u--image width="150rpx" height="150rpx" :radius="'var(--goods-rounded-big)'" :src="img(item.sku_snapshot?.goods?.cover_thumb_small ? item.sku_snapshot?.goods?.cover_thumb_small : '')" mode="aspectFill">
                                        <template #error>
                                            <image class="w-[150rpx] h-[150rpx] rounded-[var(--goods-rounded-big)] overflow-hidden" :src="img('static/resource/images/diy/shop_default.jpg')" mode="aspectFill" />
                                        </template>
                                    </u--image>
                                    <view class="ml-[20rpx] flex flex-1 flex-col box-border">
                                        <view class="flex justify-between items-baseline">
                                            <view class="max-w-[322rpx] text-[28rpx] leading-[40rpx] font-400 multi-hidden text-[#303133]">{{ item.sku_snapshot.goods.title }}</view>
                                            <template>
                                                <view class="text-right leading-[42rpx] ml-[10rpx]">
                                                    <text class="text-[22rpx] price-font">￥</text>
                                                    <text class="text-[36rpx] font-500 price-font">{{ parseFloat(item.goods_money).toFixed(2).split('.')[0] }}</text>
                                                    <text class="text-[22rpx] font-500 price-font">.{{ parseFloat(item.goods_money).toFixed(2).split('.')[1] }}</text>
                                                </view>
                                            </template>
                                        </view>
                                        <view class="flex justify-between items-baseline text-[#303133] mt-[14rpx]">
                                            <view>
                                                <view class="text-[24rpx] text-[var(--text-color-light6)] font-400 truncate leading-[34rpx] max-w-[369rpx] mb-[10rpx]" v-if="item.sku_snapshot.sku_name">{{ item.sku_snapshot.sku_name }}</view>
                                                <!-- <view class="text-[24rpx] font-400 leading-[34rpx] text-[var(--text-color-light6)]" v-else>{{ t('createTime') }} ：{{ item.create_time }}</view> -->
                                            </view>
                                            <text class="text-right text-[26rpx] font-400 w-[90rpx] leading-[36rpx]">x{{ item.num }}</text>
                                            
                                        </view>
                                        <view class="flex items-center justify-between">
                                            <!-- <view
                                                class=" h-[30rpx] border-[1px] border-[#FF000D] border-solid rounded-[6rpx] flex items-center">
                                                <view
                                                    class="w-[72rpx] bg-[#FFEAEA] text-[#FF000D] text-[22rpx] h-[34rpx] rounded-l-[6rpx] leading-[30rpx] text-center">
                                                    {{item.group_info.target_num}}人团
                                                </view>
                                                <view class="flex-1 text-[#FF000D] px-[10rpx] text-[22rpx] text-center leading-[normal]">已拼{{ item.success_group_num }}份</view>
                                            </view> -->
                                            <view
                                                class="self-start overflow-hidden h-[30rpx] border-[1px] border-[#FF9A9F] border-solid rounded-[4rpx] flex leading-[normal]">
                                                <view class="bg-[#FFF2F2] text-[#FF000D] text-[20rpx] h-[30rpx] leading-[30rpx] rounded-r-0 px-[8rpx] text-center">{{item.target_num}}人团</view>
                                                <view class="text-[#FF000D] text-[20rpx] text-center leading-[30rpx] px-[10rpx]">已拼{{item.success_group_num || '0'}}份</view>
                                            </view>
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </view>
                        <!-- <view class="flex justify-end items-center mt-[20rpx]">
                            <view class="flex items-baseline">
                                <view class="text-[22rpx] font-400 leading-[30rpx] text-[#303133]">{{ t('actualPayment') }}：</view>
                                <view class="leading-[1] text-[var(--price-text-color)]">
                                    <text class="text-[22rpx] leading-[26rpx] price-font">￥</text>
                                    <template v-if="item.pay_money>0">
                                        <text class="text-[36rpx] font-500 leading-[40rpx] price-font" >{{ parseFloat(item.pay_money).toFixed(2).split('.')[0] }}</text>
                                        <text class="text-[22rpx] font-500 leading-[28rpx] price-font">.{{ parseFloat(item.pay_money).toFixed(2).split('.')[1] }}</text>
                                    </template>
                                    <template v-else>
                                        <text class="text-[36rpx] font-500 leading-[40rpx] price-font" >{{ parseFloat(item.order_money).toFixed(2).split('.')[0] }}</text>
                                        <text class="text-[22rpx] font-500 leading-[28rpx] price-font">.{{ parseFloat(item.order_money).toFixed(2).split('.')[1] }}</text>
                                    </template>
                                  
                                     
                                </view>
                            </view>
                        </view> -->

                        

                        <view class="flex justify-between items-center mt-[20rpx]">
                            <view class="text-[24rpx] text-[#999999] flex items-center leading-[normal]" v-if="item.group_status=='process'">
                                <view>
                                    还需 <text class="text-[#FF000D]">{{item.group_info.diff_num}}人</text> ，
                                </view>
                                <view class="flex items-center">
                                    <view class="leading-[normal] mr-[10rpx]">剩余时间 </view>
                                    <!-- 自定义倒计时组件 -->
									<view class="flex items-center text-[#999]">
										<view v-if="getTimeData(item, index).days > 0" class="text-[24rpx] flex items-center justify-center h-[32rpx]">
											<text class="text-center">{{ getTimeData(item, index).days }}</text>
										</view>
										<text v-if="getTimeData(item, index).days > 0">天</text>
										<view class="text-[24rpx] flex items-center justify-center h-[32rpx]">
											<text class="text-center">{{ formatTime(getTimeData(item, index).hours) }}</text>
										</view>
										<text>:</text>
										<view class="text-[24rpx] flex items-center justify-center h-[32rpx]">
											<text class="text-center">{{ formatTime(getTimeData(item, index).minutes) }}</text>
										</view>
										<text>:</text>
										<view class="text-[24rpx] flex items-center justify-center h-[32rpx]">
											<text class="text-center">{{ formatTime(getTimeData(item, index).seconds) }}</text>
										</view>
									</view>
                                    <!-- <up-count-down class="text-[#999999] text-[24rpx] " :time="discountTimeFn(item)" format="DD:HH:mm:ss"
                                        autoStart @change="(e) => onChange(e, item)">
                                        <view class="flex gap-[3rpx] text-[#999999]">
                                            <view v-if="item.timeData.days > 0"
                                                class="text-[24rpx] flex items-center justify-center min-w-[30rpx] rounded-[6rpx] text-[#999999]">
                                                <text class="min-w-[30rpx] text-center">{{ item.timeData.days >= 10 ? item.timeData.days :
                                                    '0' + item.timeData.days }}</text>
                                            </view>
                                            <text v-if="item.timeData.days > 0" class="leading-[normal]">天</text>
                                            <view
                                                class="text-[24rpx] flex items-center justify-center min-w-[30rpx] rounded-[6rpx]  text-[#999999]">
                                                <text class="min-w-[30rpx] text-center" v-if="item.timeData.hours">{{ item.timeData.hours >= 10 ?
                                                    item.timeData.hours : '0' + item.timeData.hours }}</text>
                                                <text class="min-w-[30rpx] text-center" v-else>00</text>
                                            </view>
                                            <text class="leading-[normal]">:</text>
                                            <view
                                                class="text-[24rpx] flex items-center justify-center min-w-[30rpx] rounded-[6rpx]  text-[#999999] ">
                                                <text class="min-w-[30rpx] text-center">{{ item.timeData.minutes >= 10 ? item.timeData.minutes :
                                                    '0' + item.timeData.minutes }}</text>
                                            </view>
                                            <text class="leading-[normal]">:</text>
                                            <view
                                                class="text-[24rpx] flex items-center justify-center min-w-[30rpx] rounded-[6rpx] text-[#999999]">
                                                <text class="min-w-[30rpx] text-center">{{ item.timeData.seconds < 10 ? '0' +
                                                    item.timeData.seconds : item.timeData.seconds }}</text>
                                            </view>
                                        </view>
                                    </up-count-down> -->
                                </view>
                               
                            </view>
                            <view class="text-[24rpx] text-[#333] flex items-center leading-[normal]" v-else-if="item.group_status=='success'">
                                <view class="flex items-center" v-if="item.group_info.member_list.length > 0">
                                <!-- 循环头像数组 -->
                                <view  v-for="(avatar, index) in item.group_info.member_list" :key="index" :style="index > 0 ? 'margin-left: -20rpx;' : ''" >
                                    <u--image width="40rpx" height="40rpx" :radius="'var(--goods-rounded-big)'" :src="img(avatar.member.headimg)" mode="aspectFill" class="avatar">
                                        <template #error>
                                            <image class="rounded-[var(--goods-rounded-big)] overflow-hidden w-[40rpx] h-[40rpx]" :src="img('static/resource/images/default_headimg.png')" mode="aspectFill" />
                                        </template>
                                    </u--image>
                                </view>   
                            </view>
                            <view class="ml-[10rpx] text-[#333]">拼团成功 订单已生成</view>    
                            </view>
                            <view class="text-[24rpx] text-[#333] flex items-center leading-[normal]" v-else-if="item.group_status=='failed'">
                                <view class="flex items-center" v-if="item.group_info.member_list.length > 0">
                                <!-- 循环头像数组 -->
                                <u--image width="40rpx" height="40rpx" :radius="'var(--goods-rounded-big)'"    v-for="(avatar, index) in item.group_info.member_list"
                                :key="index"
                                :src="img(avatar.member.headimg)"
                                mode="aspectFill"
                                class="avatar"
                                :style="{
                                    marginLeft: index > 0 ? '-20rpx' : '0'
                                }" model="aspectFill">
                                    <template #error>
                                        <image class="rounded-[var(--goods-rounded-big)] overflow-hidden w-[40rpx] h-[40rpx]" :src="img('static/resource/images/default_headimg.png')" mode="aspectFill" />
                                    </template>
                                </u--image>
                            </view>
                                <view class="ml-[10rpx] text-[#999]">
                                    拼团失败 已退款
                                </view>
                            </view>
                            <view class="flex items-baseline">
                                <view class="text-[22rpx] font-400 leading-[30rpx] text-[#303133]">{{ t('actualPayment') }}：</view>
                                <view class="leading-[1] text-[var(--price-text-color)]">
                                    <text class="text-[22rpx] leading-[26rpx] price-font">￥</text>
                                    <text class="text-[36rpx] font-500 leading-[40rpx] price-font">{{ parseFloat(item.pay_money).toFixed(2).split('.')[0] }}</text>
                                    <text class="text-[22rpx] font-500 leading-[28rpx] price-font">.{{ parseFloat(item.pay_money).toFixed(2).split('.')[1] }}</text>
                                </view>
                            </view>
                        </view>
                        <view class="flex justify-end text-[28rpx] mt-[20rpx] items-center" v-if="(item.order_status == 'wait_pay')">
                            <view class="text-[24rpx] font-500 leading-[52rpx] h-[56rpx] min-w-[150rpx] text-center border-[2rpx] border-solid border-[#ccc] rounded-full text-[var(--text-color-light3)] box-border" v-if="item.order_status == 'wait_pay'" @click.stop="orderBtnFn(item, 'close')">{{ t('orderClose') }}</view>
                            <view class="text-[24rpx] font-500 flex-center h-[56rpx] min-w-[150rpx] text-center border-[0] text-[#fff] primary-btn-bg rounded-full ml-[20rpx] box-border" v-if="item.order_status == 'wait_pay'" @click.stop="orderBtnFn(item, 'pay')">{{ t('topay') }}</view>
                        </view>
                        <view class="flex justify-end text-[28rpx] mt-[20rpx] items-center" v-else>
                            <view class="text-[24rpx] font-500 leading-[52rpx] h-[56rpx] min-w-[150rpx] text-center border-[2rpx] border-solid border-primary rounded-full text-primary box-border" v-if="item.group_status == 'success'" @click.stop="orderBtnFn(item, 'buy')">再次拼团</view>
                            <view class="text-[24rpx] font-500 leading-[52rpx] h-[56rpx] min-w-[150rpx] text-center border-[2rpx] border-solid border-primary rounded-full text-primary box-border" v-else-if="item.group_status == 'failed'" @click.stop="orderBtnFn(item, 'buy')">再次开团</view>
                            <view class="text-[24rpx] font-500 flex-center h-[56rpx] min-w-[150rpx] text-center border-[0] text-[#fff] primary-btn-bg rounded-full ml-[20rpx] box-border" v-if="item.group_status == 'process' && (item.order_status =='payment' || item.order_status =='wait_use')" @click.stop="orderBtnFn(item, 'share')">邀请好友</view>
                              <view class="text-[24rpx] font-500 flex-center h-[56rpx] min-w-[150rpx] text-center border-[0] text-[#fff] primary-btn-bg rounded-full ml-[20rpx] box-border" v-if="item.delivery_type == 'verify' && (item.order_status == 'payment' || item.order_status == 'wait_use') && item.group_status == 'success'" @click.stop="orderBtnFn(item, 'gouse')">去使用</view>

                        </view>
                       
                    </view>
                </template>
            </view>
            <mescroll-empty v-if="!list.length && loading" :option="{tip : '暂无订单'}"></mescroll-empty>
        </mescroll-body>
      <pay ref="payRef" @close="payClose" :ignore-pay="['friendspay']"></pay>
      <!-- #ifdef MP-WEIXIN -->
      <!-- 小程序隐私协议 -->
      <wx-privacy-popup ref="wxPrivacyPopupRef"></wx-privacy-popup>
      <!-- #endif -->
      <share-poster ref="sharePosterRef" posterType="pintuan_goods" :posterId="posterId" :posterParam="posterParam" :copyUrl="copyUrl" :isPreload="false" :copyUrlParam="copyUrlParam" />
        <tabbar addon="pintuan" />
  </view>
</template>

<script setup lang="ts">
import { ref, nextTick ,computed,onMounted,onUnmounted} from 'vue';
import { t } from '@/locale'
import { img, redirect, copy, timeTurnTimeStampTwo } from '@/utils/common'
import {  getPintuanOrderList ,pintuanOrderClose ,getPintuanOrderStatus} from '@/addon/pintuan/api/order';
import { checkPintuanGroupApi ,getPintuanConfig} from '@/addon/pintuan/api/pintuan';
import MescrollBody from '@/components/mescroll/mescroll-body/mescroll-body.vue';
import MescrollEmpty from '@/components/mescroll/mescroll-empty/mescroll-empty.vue';
import useMescroll from '@/components/mescroll/hooks/useMescroll.js';
  import useMemberStore from '@/stores/member'

import { onLoad, onPageScroll, onReachBottom, onShow } from '@dcloudio/uni-app';
import useConfigStore from "@/stores/config";
import { topTabar } from '@/utils/topTabbar';
import useSystemStore from '@/stores/system';
const systemStore = useSystemStore()

/********* 自定义头部 - start ***********/
const topTabarObj = topTabar()
let topTabbarData = topTabarObj.setTopTabbarParam({ title: '拼团订单列表', topStatusBar: { textColor: "#333", bgColor: "#fff" } })
/********* 自定义头部 - end ***********/
  // 分享
import { useShare }from '@/hooks/useShare'
const{setShare,disableShare} = useShare()
const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom);
const list = ref<Array<Object>>([]);
const loading = ref<boolean>(false);
const statusLoading = ref<boolean>(false);
const orderState = ref('')
const orderStateList: any = ref([]);
const evaluateConfig = ref("")

const mch_id = ref('')
const isTradeManaged = ref(false)

const wxPrivacyPopupRef: any = ref(null)
  // 会员信息
const memberStore = useMemberStore()
const userInfo = computed(() => memberStore.info)
onLoad((option: any) => {
  disableShare()
  orderState.value = option.status || "all";
  getOrderStatusFn();
  // #ifdef MP
  nextTick(() => {
      if (wxPrivacyPopupRef.value) wxPrivacyPopupRef.value.proactive();
  })
  // #endif
});
const config = ref<any>({})
const getPintuanConfigFn = () => {
    getPintuanConfig().then((res: any) => {
        config.value = res.data
    })
}
getPintuanConfigFn()

onShow(() => {
    // #ifdef MP-WEIXIN
    if (wx && wx.hideHomeButton) wx.hideHomeButton()
    // #endif
  nextTick(() => {
      // 评价完成之后，会返回到订单列表，需要请求最新数据
      if (getMescroll()) {
          getMescroll().resetUpScroll();
      }
  })
})

const getPintuanOrderFn = (mescroll: any) => {
  loading.value = false;
  let data: object = {
      page: mescroll.num,
      limit: mescroll.size,
      status: orderState.value
  };

  getPintuanOrderList(data).then((res: any) => {
        let newArr = (res.data.data as Array<Object>);
        //设置列表数据
        if (mescroll.num == 1) {
            list.value = []; //如果是第一页需手动制空列表
        }

        list.value = list.value.concat(newArr);
        mescroll.endSuccess(newArr.length);

        mch_id.value = res.data.mch_id;
        isTradeManaged.value = res.data.is_trade_managed;
        loading.value = true;
  }).catch(() => {
      loading.value = true;
      mescroll.endErr(); // 请求失败, 结束加载
  })
}

const getOrderStatusFn = () => {
  statusLoading.value = false;
  orderStateList.value = [];
  let obj = { name: '全部', status: 'all' };
  orderStateList.value.push(obj);
  statusLoading.value = true;
 
    getPintuanOrderStatus().then((res: any) => {
        
        Object.entries(res.data).forEach(([key, value]) => {
            orderStateList.value.push({
                name: value,  
                status: key   
            });
        });
        statusLoading.value = true;
    }).catch(() => {
        statusLoading.value = true;
    })
}

const orderStateFn = (status: any) => {
  orderState.value = status.toString();
  list.value = [];
  getMescroll().resetUpScroll();
};

const toLink = (data: any) => {
  redirect({ url: '/addon/pintuan/pages/order/detail', param: { order_no: data.order_no } })
}
/************* 分享海报-start **************/
const sharePosterRef: any = ref(null);
const copyUrl = ref('/addon/pintuan/pages/goods/detail')
const copyUrlParam = ref('');
let posterParam: any = {};
let posterId = 0; // 海报id
/************* 分享海报-end **************/
// 支付
const payRef = ref(null)
const orderBtnFn = (data: any, type = '') => {
  if (type == 'pay'){
    data.id = data.order_id
    payFn(data);
  }else if (type == 'close') {
      close(data);
  }else if (type == 'share'){
        // 分享 - start
        let share: any = {
            title: '',
            desc: '',
            url: data.order_info?.sku_snapshot.goods?.cover || "",
            // 新增：动态生成跳转地址（根据环境拼接完整路径）
            link: '', // H5 跳转链接（带域名）
            path: ''  // 小程序跳转路径（路由格式）
        };
        let basePath  = ''
        if(data.group_status == 'process'){
            share.title = data.share_config.group.title || config.value.share_config.common.common_title || data.order_info?.sku_snapshot.goods?.title;
            share.desc = data.share_config.group.desc || config.value.share_config.common.common_desc ||'';
            // 生成基础路径（目标页面 + 参数）
            basePath = `addon/pintuan/pages/goods/detail?pintuan_id=${data.pintuan_id}&group_id=${data.group_id}`;
        }else{
            share.title = data.share_config.normal.title || config.value.share_config.common.common_title || data.order_info?.sku_snapshot.goods?.title;
            share.desc = data.share_config.normal.desc || config.value.share_config.common.common_desc ||'';
            basePath = `addon/pintuan/pages/goods/detail?pintuan_id=${data.pintuan_id}`;
        }

        // 区分环境拼接完整地址
        // #ifdef H5
        let pathName = location.pathname;
        let packageArr: any = ['/app/', '/addon/'];
        for (let i = 0; i < packageArr.length; i++) {
            if (pathName.indexOf(packageArr[i]) != -1) {
                pathName = pathName.substr(0, pathName.indexOf(packageArr[i]));
            }
        }
        // H5 需拼接域名和当前路由前缀
        share.link = `${location.origin}${pathName}/${basePath}`;
        // #endif

       //  #ifdef MP-WEIXIN
        // 小程序需用路由格式（以 / 开头）
        share.path = `/${basePath}`;
        // #endif

        // 传递分享信息（包含地址）
        setShare({
            wechat: {
                ...share
                // H5 会使用 share 中的 link 字段
            },
            weapp: {
                ...share
                // 小程序会使用 share 中的 path 字段
            }
        });
     
        // 分享 - end
        copyUrlParam.value = '?pintuan_id='+ data.pintuan_id;
        copyUrlParam.value += '&group_id=' + data.group_id;
        posterParam.pintuan_id = data.pintuan_id;
        posterParam.group_id = data.group_id;
         posterId = data.pintuan_snapshot?.poster_id;
        if (userInfo.value && userInfo.value.member_id) posterParam.member_id = userInfo.value.member_id;
        sharePosterRef.value.openShare();
    }else if (type == 'buy') {
        redirect({ url: '/addon/pintuan/pages/goods/detail', param: { pintuan_id: data.pintuan_id } })
    }else if(type == 'gouse') {
        // redirect({ url: '/addon/pintuan/pages/goods/detail', param: { pintuan_id: data.pintuan_id } })
        redirect({ url: '/addon/pintuan/pages/order/detail', param: { order_no: data.order_no } })
    }
}

const payFn = (data: any) => {
     checkPintuanGroupApi({
        group_id: data.group_id,
        pintuan_id: data.pintuan_id,
        join_type: data.pintuan_snapshot.join_type,
        order_no: data.order_no
    }).then((res: any) => {
        if(res.data.error){
            uni.showToast({
                icon: 'none',
                title: res.data.error,
            })
        }else{
            payRef.value?.open(data.order_type, data.id, `/addon/pintuan/pages/order/detail?order_no=${ data.order_no }`);
        }
    })
}

//关闭订单
const close = (item: any) => {
  uni.showModal({
      title: '提示',
      content: '您确定要关闭该订单吗？',
      confirmColor: useConfigStore().themeColor['--primary-color'],
      success: res => {
          if (res.confirm) {
              pintuanOrderClose(item.order_no).then((data) => {
                  getMescroll().resetUpScroll();
              })
          }
      }
  })
}
const currentTime = ref(Date.now()); // 当前时间戳，用于触发响应式更新
const isAnimating = ref(false); // 添加动画状态标识
let countdownTimer: any = null; // 倒计时定时器
// 启动倒计时
const startCountdown = () => {
    if (countdownTimer) {
        clearInterval(countdownTimer);
    }
    
    countdownTimer = setInterval(() => {
        // 更新当前时间戳，触发响应式更新
        if (!isAnimating.value) {
            currentTime.value = Date.now();
        }
    }, 1000);
};
// 格式化时间显示（补零）
const formatTime = (time: number): string => {
    return time < 10 ? `0${time}` : `${time}`;
};
// 获取倒计时数据
const getTimeData = (item: any, index: number) => {
    if (!item?.group_info?.expire_time) {
        return { days: 0, hours: 0, minutes: 0, seconds: 0 };
    }
    
    try {
        // alert(1)
        // 使用响应式的当前时间
        const now = currentTime.value;
        
        // 安全地处理时间转换，避免警告
        let expireTime = 0;
        if (typeof item.group_info?.expire_time === 'string' && item.group_info?.expire_time.trim()) {
            const iosCompatibleDateStr = item.group_info?.expire_time.replace(/-/g, '/'); 
            const timestamp = timeTurnTimeStampTwo(iosCompatibleDateStr);
            if (timestamp && !isNaN(timestamp)) {
                expireTime = timestamp * 1000;
            }
        }
        
        if (!expireTime) {
            return { days: 0, hours: 0, minutes: 0, seconds: 0 };
        }
        
        const remainingTime = expireTime - now;
        
        if (remainingTime <= 0) {
            return { days: 0, hours: 0, minutes: 0, seconds: 0 };
        }
        
        const days = Math.floor(remainingTime / (1000 * 60 * 60 * 24));
        const hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
        
        return { days, hours, minutes, seconds };
    } catch (error) {
        // 如果出现任何错误，返回默认值
        return { days: 0, hours: 0, minutes: 0, seconds: 0 };
    }
};
onMounted(() => {
    // 启动倒计时
    startCountdown();
})

// 组件卸载时清理定时器
onUnmounted(() => {
    if (countdownTimer) {
        clearInterval(countdownTimer);
        countdownTimer = null;
    }
});
</script>
<style>
.order-list .mescroll-body {
  padding-bottom: constant(safe-area-inset-bottom) !important;
  padding-bottom: env(safe-area-inset-bottom) !important;
}

.order-list :deep(.u-count-down__text) {
  font-size: 24rpx !important;
  color: #EF000C !important;
}
</style>
<style lang="scss" scoped>
.text-color {
  color: var(--primary-color);
}

.bg-color {
  background-color: var(--primary-color);
}
</style>
