<template>
    <view :style="warpCss" class="overflow-hidden relative" v-if="diyComponent && diyComponent.goods && Object.keys(diyComponent.goods).length">
		<view class="px-[24rpx] pt-[20rpx] pb-[10rpx]">
			<view class="flex items-center justify-between pb-[20rpx]" @click="navToPintuan">
				<view class="font-medium" :style="titleCss">
                    <text :style="{color: diyComponent.diyInfo.titleStyle.numberColor}">{{diyComponent.pintuan_current_num || 0}}</text>
                    <text class="ml-[2rpx] text-[30rpx] text-[#333]">人正在拼团，可直接参与</text>
				</view>
				<view :style="moreCss" class="flex items-center" @click="navToPintuan">
                    <text>更多</text>
                    <text class="pt-[4rpx] iconfont iconarrow-right text-[24rpx]"></text>
                </view>
			</view>

			<!-- 拼团列表 -->
			<view class="scroll-container" style="overflow: hidden; position: relative;">
				<swiper 
					:circular="swiperGroups?.length > 1" 
					vertical 
					:autoplay="swiperGroups?.length > 1"
					:interval="3000"
					:duration="500"
					easing-function="easeInOutCubic"
					class="swiper-container"
                    :class="pingtuanglist2.length == 1 ? '!h-[110rpx]' : pingtuanglist2.length == 2 ? '!h-[210rpx]' : '!h-[310rpx]'"
                    :style="pingtuanglist2.length == 1 ? 'height: 110rpx;' : pingtuanglist2.length == 2 ? 'height: 220rpx;' : 'height: 310rpx;'"
					disable-touch>
					<swiper-item :item-id="groupIndex + ''" v-for="(group, groupIndex) in swiperGroups" :key="groupIndex">
						<view v-for="(item, itemIndex) in group" :key="item.supplementKey || item.id || itemIndex"
							class="flex items-center justify-between h-[100rpx] border-[0] border-b-[2rpx] border-solid border-[#F5F5F5] scroll-item"
							:class="{ '!border-[0]': itemIndex === group.length - 1 }"
							@click="addpingtuan(item)">
							<view class="flex items-center flex-1">
								<!-- 头像组 -->
								<view class="relative flex items-center">
									<template v-for="(member, memberIndex) in item.member_list" :key="memberIndex">
										<template v-if="memberIndex<2">
											<image v-if="member.member.headimg" :src="img(member.member.headimg)" mode="scaleToFill" class="w-[60rpx] h-[60rpx] rounded-[50%] border-2 border-[red] relative" @error="member.member.headimg = 'static/resource/images/default_headimg.png'" :class="{'-ml-[20rpx]': memberIndex>0}" :style="{'z-index': 3 - memberIndex}" />
											<image v-else :src="img('static/resource/images/default_headimg.png')" mode="scaleToFill" class="w-[60rpx] h-[60rpx] rounded-[50%] border-2 border-[red] relative" :class="{'-ml-[20rpx]': memberIndex>0}" :style="{'z-index': 3 - memberIndex}"/>
										</template>
										<text v-if="memberIndex==2" class="w-[60rpx] h-[60rpx] rounded-[50%] relative z-1 -ml-[20rpx] box-border flex items-center justify-center border-[2rpx] border-dashed border-[#DDDDDD] bg-[#FFFFFF] text-[#DDDDDD] iconfont iconwenhao"></text>
									</template>
								</view>

								<!-- 拼团信息 -->
								<view class="flex-1 justify-end mr-[20rpx] text-[#999999] text-[24rpx] flex items-center">
									<text class="mr-[4rpx]">剩余时间</text>
									<view v-if="diyStore.mode != 'decorate'" class="mx-[6rpx] text-[24rpx]">
										<view class="flex items-center gap-[6rpx] text-[#fff]">
											<view class="text-[24rpx] flex items-center justify-center min-w-[30rpx] h-[32rpx] text-[#ff0000]">
												<text class="min-w-[30rpx] text-center">{{ formatTime(getTimeData(item, itemIndex).hours) }}</text>
											</view>
											<text class="text-[#ff0000]">:</text>
											<view class="text-[24rpx] flex items-center justify-center min-w-[30rpx] h-[32rpx] text-[#ff0000]">
												<text class="min-w-[30rpx] text-center">{{ formatTime(getTimeData(item, itemIndex).minutes) }}</text>
											</view>
											<text class="text-[#ff0000]">:</text>
											<view class="text-[24rpx] flex items-center justify-center min-w-[30rpx] h-[32rpx] text-[#ff0000]">
												<text class="min-w-[30rpx] text-center">{{ formatTime(getTimeData(item, itemIndex).seconds) }}</text>
											</view>
										</view>
									</view>
									<text class="text-[#ff0000] mx-[6rpx]" v-else>12 : 50 : 20</text>
									<text class="text-[#999999] text-[24rpx]">还差
										<text class="text-[#333]">{{
											item.target_num - item.current_num
										}}</text>
										人</text>
								</view>
							</view>

							<view class="w-[130rpx] h-[54rpx] flex items-center justify-center" :style="btnCss">
                                {{(item.is_me==1 || item.is_join==1)? '邀请好友' : (item.target_num - item.current_num) == 1 ? '直接拼成' : '参与拼团' }}
                            </view>
						</view>
					</swiper-item>
				</swiper>
			</view>
		</view>
        <!-- 装修时，防止点击 -->
        <view v-if="diyStore.mode == 'decorate'" class="absolute z-10 top-0 right-0 bottom-0 left-0"></view>
        <!-- 拼团SKU选择器 -->
        <ns-pintuan-sku ref="pintuanSkuRef" v-if="Object.keys(diyComponent).length && diyComponent.goods"
            :goods-detail="{...diyComponent, pintuan_id: (diyComponent as any)?.pintuan_id || (diyComponent as any)?.id}"
            @change="addpingtuan" />
        <!-- 分享 -->
        <share-poster ref="sharePosterRef"  :isPreload="false" v-if="Object.keys(pintuanGoodsData).length" posterType="pintuan_goods" :posterId="pintuanGoodsData.goods?.poster_id" :posterParam="posterParam" :copyUrlParam="copyUrlParam" :copyUrl="copyUrl"  @close="posterClose" />
    </view>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
import { img, timeTurnTimeStamp ,redirect} from '@/utils/common';
import useDiyStore from '@/app/stores/diy';
import usePintuanGoodsDetailStore from '@/addon/pintuan/stores/goodsDetail';
import { getPintuanGroupListApi } from '@/addon/pintuan/api/pintuan';
import nsPintuanSku from '@/addon/pintuan/components/ns-pintuan-sku/ns-pintuan-sku.vue';
import sharePoster from '@/components/share-poster/share-poster.vue';
const props = defineProps(['component', 'index', 'value', 'global']);
const diyStore = useDiyStore();
const emits = defineEmits(['loadingFn', 'update:componentIsShow']); //商品数据加载完成之后
import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
import useMemberStore from '@/stores/member'
const memberStore = useMemberStore()
const userInfo = computed(() => memberStore.info)
// 拼团SKU相关
const pintuanSkuRef: any = ref(null);

const diyComponent = computed(() => {
    if (diyStore.mode == 'decorate') {
        const obj = {
            goods:{
                pintuan_price: '100.00'
            },
            success_group_num: 100,
        }
        return Object.assign({}, {diyInfo:  diyStore.value[props.index]}, obj);
    } else {
        if(props.component.isShow && Object.keys(pingtuanglist.value).length){
            emits('update:componentIsShow', true)
        }
        return Object.assign({}, {diyInfo: props.component}, usePintuanGoodsDetailStore().goodsDetail);
    }
})

const currentTime = ref(Date.now());
// 缓存时间戳转换结果，避免重复计算
const timeStampCache = new Map<string, number | null>();
let countdownTimer: any = null;

const formatTime = (num: number) => (num < 10 ? '0' + num : '' + num);

// 计算某一项的剩余时间
const getTimeData = (item: any, index: number) => {
    const expireTimeStr = item?.expire_time;
    if (!expireTimeStr) return { days: 0, hours: 0, minutes: 0, seconds: 0 };

    let expireTimestamp = 0;
    if (timeStampCache.has(expireTimeStr)) {
        const cached = timeStampCache.get(expireTimeStr);
        if (cached) expireTimestamp = cached;
    } else {
        if (typeof expireTimeStr === 'string' && expireTimeStr.trim()) {
            const ts = timeTurnTimeStamp(expireTimeStr);
            timeStampCache.set(expireTimeStr, ts);
            if (ts && !isNaN(ts)) expireTimestamp = ts;
        } else {
            timeStampCache.set(expireTimeStr, null);
        }
    }

    if (!expireTimestamp) return { days: 0, hours: 0, minutes: 0, seconds: 0 };
    const diff = Math.max(0, expireTimestamp * 1000 - currentTime.value);
    const days = Math.floor(diff / (24 * 3600 * 1000));
    const hours = Math.floor((diff % (24 * 3600 * 1000)) / (3600 * 1000));
    const minutes = Math.floor((diff % (3600 * 1000)) / (60 * 1000));
    const seconds = Math.floor((diff % (60 * 1000)) / 1000);
    return { days, hours, minutes, seconds };
};

const warpCss = computed(() => {
    let style = '';
    style += 'position:relative;';
    if (diyComponent.value.diyInfo.componentStartBgColor && diyComponent.value.diyInfo.componentEndBgColor) style += `background:linear-gradient(${diyComponent.value.diyInfo.componentGradientAngle},${diyComponent.value.diyInfo.componentStartBgColor},${diyComponent.value.diyInfo.componentEndBgColor});`;
    else style += 'background-color:' + (diyComponent.value.diyInfo.componentStartBgColor || diyComponent.value.diyInfo.componentEndBgColor) + ';';

    if (diyComponent.value.diyInfo.componentBgUrl) {
        style += `background-image:url('${img(diyComponent.value.diyInfo.componentBgUrl)}');`;
        style += 'background-size: cover;background-repeat: no-repeat;';
    }

    if (diyComponent.value.diyInfo.topRounded) style += 'border-top-left-radius:' + diyComponent.value.diyInfo.topRounded * 2 + 'rpx;';
    if (diyComponent.value.diyInfo.topRounded) style += 'border-top-right-radius:' + diyComponent.value.diyInfo.topRounded * 2 + 'rpx;';
    if (diyComponent.value.diyInfo.bottomRounded) style += 'border-bottom-left-radius:' + diyComponent.value.diyInfo.bottomRounded * 2 + 'rpx;';
    if (diyComponent.value.diyInfo.bottomRounded) style += 'border-bottom-right-radius:' + diyComponent.value.diyInfo.bottomRounded * 2 + 'rpx;';
    return style;
})

const titleCss = computed(() => {
    let style = '';
    style += `color:${diyComponent.value.diyInfo.titleStyle.textColor};`;
    style += 'font-size:' + diyComponent.value.diyInfo.titleStyle.fontSize * 2 + 'rpx;';
    return style;
})

const moreCss = computed(() => {
    let style = '';
    style += `color:${diyComponent.value.diyInfo.moreStyle.textColor};`;
    style += 'font-size:' + diyComponent.value.diyInfo.moreStyle.fontSize * 2 + 'rpx;';
    return style;
})

const btnCss = computed(() => {
    let style = '';
    style += `color:${diyComponent.value.diyInfo.btnStyle.textColor};`;
    style += `background-color:${diyComponent.value.diyInfo.btnStyle.bgColor};`;
    style += 'font-size:' + diyComponent.value.diyInfo.btnStyle.fontSize * 2 + 'rpx;';
    style += 'border-radius:' + diyComponent.value.diyInfo.btnStyle.rounded * 2 + 'rpx;';
    return style;
})

const pingtuanglist = ref<any[]>([]);
const pingtuanglist2 = ref<any[]>([]);

// 分享相关变量
const pintuanGoodsData = ref<any>({});
const posterParam = ref<any>({});
const copyUrlParam = ref<any>({});
const copyUrl = ref<any>("");
const sharePosterRef = ref(null);

// 将数据按每3条分组，每个组作为一个 swiper-item
const swiperGroups = computed(() => {
    if (!pingtuanglist2.value || pingtuanglist2.value.length === 0) {
        return [];
    }
    
    const originalList = pingtuanglist2.value;
    const groups = [];
    
    // 如果数据不足3条，只创建一个组
    if (originalList.length <= 3) {
        return [originalList];
    }
    
    // 按每3条分组
    for (let i = 0; i < originalList.length; i += 3) {
        const group = originalList.slice(i, i + 3);
        
        // 如果最后一组不足3条，从头部补齐
        while (group.length < 3) {
            const supplementIndex = (group.length + i) % originalList.length;
            group.push({
                ...originalList[supplementIndex],
                supplementKey: `supplement-${i}-${group.length}` // 标记补充的数据
            });
        }
        
        groups.push(group);
    }
    
    return groups;
});

// 获取拼团列表
const getPintuanGroupListfu = () => {
    // 从 diyComponent.value 中获取 pintuan_id
    const pintuanId = (diyComponent.value as any)?.pintuan_id || (diyComponent.value as any)?.id;

    if (!pintuanId) {
        pingtuanglist.value = [];
        pingtuanglist2.value = [];
        return;
    }

    getPintuanGroupListApi({ pintuan_id: pintuanId })
        .then((res: any) => {
            // 处理分页数据结构
            if (res.data && res.data.data && Array.isArray(res.data.data)) {
                pingtuanglist.value = res.data.data;
                pingtuanglist2.value = res.data.data;
            } else if (
                res.data &&
                res.data.data &&
                res.data.data.data &&
                Array.isArray(res.data.data.data)
            ) {
                // 处理分页格式：{data: {data: [...], current_page: 1, last_page: 1, total: 0}}
                pingtuanglist.value = res.data.data.data;
                pingtuanglist2.value = res.data.data.data;
            } else {
                pingtuanglist.value = [];
                pingtuanglist2.value = [];
            }
        })
        .catch((err: any) => {
             pingtuanglist.value = [];
            pingtuanglist2.value = [];
        });
};

// 分享海报关闭回调
const posterClose = () => {
    usePintuanGoodsDetailStore().setGoodsDetail({ isOpenSharePoster: false })
}

// 参与拼团 - 处理来自滚动列表的点击和SKU组件的事件
const addpingtuan = (item: any) => {
    // 如果是来自滚动列表的点击（有id属性）
    if (item && item.id) {
        if(item.is_me == 1 || item.is_join==1){
             // 打开分享海报
            posterParam.value.pintuan_id = pintuanGoodsData.value.pintuan_id;
            posterParam.value.group_id = item.id;
            // if (pintuanGoodsData.value.userInfo && pintuanGoodsData.value.userInfo.member_id) {
            //     posterParam.value.member_id = pintuanGoodsData.value.userInfo.member_id;
            // }
            if(userInfo.value && userInfo.value.member_id){
                 posterParam.value.member_id =  userInfo.value.member_id;
            }
            copyUrl.value = '/addon/pintuan/pages/goods/detail';
            copyUrlParam.value = `?pintuan_id=${pintuanGoodsData.value.pintuan_id}&group_id=${item.id}`;
            // usePintuanGoodsDetailStore().setGoodsDetail({ isOpenSharePoster: true });
            sharePosterRef.value.openShare()

            return
        }
        // 设置拼团信息到store
        usePintuanGoodsDetailStore().setGoodsDetail({
            // isOpenSkuBuy: true,
            // skuBuyType: 'buy_now',
            // isSingle: 0,
            // join_type: 'join_group',
            // group_id: item.id,
            // is_need_recalculate: 1,
            // check_ladder: item.check_ladder

            is_single_buy: 0,
            skuBuyType: 'buy_now',
            isSingle: 0,
            join_type: 'join_group',
            group_id: item.id,
            is_need_recalculate: 1,
            check_ladder: item.check_ladder,
            isOpenSkuBuy: true
        });
    }  
};

onMounted(() => {
    // 初始化拼团商品数据
    pintuanGoodsData.value = usePintuanGoodsDetailStore().goodsDetail;
    
    // 装修模式下刷新
    if (diyStore.mode == 'decorate') {
        pingtuanglist2.value = [
            {
                member_list:[
                    {
                        member: {
                            headimg: 'static/resource/images/default_headimg.png',
                            nickname: '小红'
                        }
                    },
                ],
                target_num:5,
                current_num: 2
            },{
                member_list:[
                    {
                        member: {
                            headimg: 'static/resource/images/default_headimg.png',
                            nickname: '小红'
                        }
                    }
                ],
                expire_time: '2025-09-17 17:22:48',
                target_num:5,
                current_num: 2
            },{
                member_list:[
                    {
                        member: {
                            headimg: 'static/resource/images/default_headimg.png',
                            nickname: '小王'
                        }
                    }
                ],
                expire_time: '2025-09-17 18:22:48',
                target_num:5,
                current_num: 2
            }
        ];
    } else {
        // 当组件数据更新时，重新获取拼团列表
        getPintuanGroupListfu();
    }
    // 启动倒计时刷新
    countdownTimer = setInterval(() => {
        currentTime.value = Date.now();
    }, 1000);
    
    // 监听应用从后台返回前台
    uni.onAppShow(() => {
        getPintuanGroupListfu();
    });
    
    // 监听页面显示事件（包括返回时）
    uni.$on('pageShow', () => {
        getPintuanGroupListfu();
    });
    
    // 监听页面返回事件
    uni.$on('pageReturn', () => {
        getPintuanGroupListfu();
    });
});

watch(()=>(diyComponent.value as any).is_recalculate,(newVal,oldVal)=>{
    getPintuanGroupListfu()
})

onShow(()=>{
    getPintuanGroupListfu()
})

const navToPintuan = () => {
    // 调用拼团SKU选择器
    if (pintuanSkuRef.value) {
        pintuanSkuRef.value.open('open_group');
    }
}

// 组件卸载时清理定时器和缓存
onUnmounted(() => {
    // 清理时间戳缓存，释放内存
    timeStampCache.clear();
    if (countdownTimer) {
        clearInterval(countdownTimer);
        countdownTimer = null;
    }
    
    // 移除事件监听
    uni.$off('pageShow');
    uni.$off('pageReturn');
});
</script>
<style lang="scss" scoped>
.arrow-left {
    background: rgba(153, 153, 153, 0.1);
    border: 1rpx solid rgba(221, 221, 221, 0.3);
}

.scroll-container {
    position: relative;
    overflow: hidden;
}

.scroll-item {
    height: 100rpx;
    display: flex;
    align-items: center;
    box-sizing: border-box;
}
</style>