<template>
    <view @touchmove.prevent.stop>
        <u-overlay :show="goodsSkuPop" @click="closeFn" zIndex="490" :opacity="0.8">
            <u-popup class="popup-type" :show="goodsSkuPop" @close="closeFn" mode="center" :overlay="false"  :round="10"  @open="onPopupOpen"
                zIndex="500" overlayOpacity="0.8">
                <view class="w-[570rpx] h-[720rpx] bg-[#fff] rounded-[24rpx] overflow-hidden">
                    <view class="head relative px-[30rpx] py-[20rpx] bg-[#fff]">
                        <view class="text-center">
                            <text class="text-[30rpx] font-medium text-[#333333]">可参与的拼团</text>
                        </view>
                        <view class="close-btn absolute right-[30rpx] top-1/2 transform -translate-y-1/2"
                            @click="closeFn">
                            <text class="iconfont iconguanbi text-[32rpx] text-[#999]"></text>
                        </view>
                    </view>
                    <view class="flex-1 px-[30rpx] py-[20rpx]">
                        <!-- 加载状态 -->
                        <view v-if="loading" class="h-[550rpx] flex items-center justify-center">
                            <view class="text-center">
                                <text class="iconfont iconloading text-[60rpx] text-[#999] animate-spin"></text>
                                <view class="text-[28rpx] text-[#999] mt-[20rpx]">加载中...</view>
                            </view>
                        </view>

                        <!-- 错误状态 -->
                        <view v-else-if="error" class="h-[550rpx] flex items-center justify-center">
                            <view class="text-center">
                                <text class="iconfont iconwarn text-[60rpx] text-[#ff4444]"></text>
                                <view class="text-[28rpx] text-[#999] mt-[20rpx] mb-[30rpx]">加载失败，请重试</view>
                                <view class="bg-[#ff4444] text-white text-[26rpx] px-[40rpx] py-[16rpx] rounded-[30rpx]"
                                    @click="loadPintuanList">
                                    重新加载
                                </view>
                            </view>
                        </view>

                        <!-- 空状态 -->
                        <view v-else-if="pintuanList.length === 0" class="h-[550rpx] flex items-center justify-center">
                            <view class="text-center">
                                <text class="iconfont iconempty text-[80rpx] text-[#ccc]"></text>
                                <view class="text-[28rpx] text-[#999] mt-[20rpx]">暂无拼团</view>
                                <view class="text-[24rpx] text-[#ccc] mt-[10rpx]">快去开启一个新的拼团吧~</view>
                            </view>
                        </view>

                        <!-- 拼团列表 -->
                        <scroll-view v-else scroll-y class="h-[550rpx] overflow-auto">
                            <view
                                class="pintuan-item flex items-center justify-between py-[25rpx] border-b border-[#f5f5f5]"
                                v-for="(item, index) in pintuanList" :key="item.id || index" @click="joinPintuan(item)">
                                <!-- 用户头像和信息 -->
                                <view class="flex items-center flex-1">
                                    <!-- 头像组（最多显示3个，重叠显示） -->
                                    <view class="relative flex items-center mr-[20rpx] max-w-[150rpx]" 
                                          :class="{'justify-center': item.member_list.length <= 2, 'justify-start': item.member_list.length > 2}">
                                        <template v-for="(member, memberIndex) in item.member_list" :key="`member-${memberIndex}`" v-if="item.member_list.length > 0">
                                            <template v-if="memberIndex < 3">
                                                <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 z-1" 
                                                    @error="member.member.headimg = 'static/resource/images/default_headimg.png'" 
                                                    :class="{'-ml-[25rpx]': memberIndex > 0 && item.member_list.length > 2}" />
                                                <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 z-1" 
                                                    :class="{'-ml-[25rpx]': memberIndex > 0 && item.member_list.length > 2}" />
                                            </template>
                                            <text v-if="memberIndex >= 3" 
                                                class="absolute right-[0] z-1 w-[60rpx] h-[60rpx] flex items-center justify-center rounded-[50%] bg-[#FFF1F1] text-[red] iconfont icona-gengduoV6xx-28"></text>
                                        </template>
                                        <template v-else>
                                            <image  
                                                    :src="img('static/resource/images/default_headimg.png')" 
                                                    mode="scaleToFill" 
                                                    class="w-[60rpx] h-[60rpx] rounded-[50%] border-2 border-[red] relative z-1"   />
                                        </template>
                                    </view>

                                    <!-- 拼团信息 -->
                                    <view class="flex-1">
                                        <view class="flex items-center mb-[8rpx]">
                                            <text class="text-[#333333] text-[26rpx] max-w-[90rpx] mr-[10rpx] using-hidden leading-[1.5]">
                                                {{
                                                    item.member_list
                                                        .slice(0, 3)
                                                        .map((member) => member.member.nickname)
                                                        .join("、")
                                                }}{{ item.member_list.length > 3 ? "..." : "" }}
                                            </text>
                                            <text class="text-[#999999] text-[24rpx]">还差
                                                <text class="text-[#FF000D]">{{
                                                    item.target_num - item.current_num
                                                }}</text>
                                                人</text>
                                        </view>
                                        <view class="text-[#999999] text-[24rpx]">
                                            <text v-if="formatRemainingTime(item.expire_time)!='已结束'">剩余时间</text>
                                            <text>{{ formatRemainingTime(item.expire_time) }}</text>
                                        </view>
                                    </view>
                                </view>

                                <!-- 参与拼团按钮 -->
                                <view
                                    class="bg-[#FF000D] text-[#fff] text-[24rpx] rounded-[30rpx] w-[130rpx] h-[54rpx] flex items-center justify-center ml-[10rpx]"
                                    >
                                    {{(item.is_me==1 || item.is_join==1) ? '邀请好友' : (item.target_num - item.current_num) == 1 ? '直接拼成' : '参与拼团' }}
                                    
                                </view>
                            </view>

                        </scroll-view>
                    </view>
                </view>
            </u-popup>
        </u-overlay>
        <!-- 分享 -->
        <share-poster ref="sharePosterRef" :isPreload="false" v-if="Object.keys(props.goodsDetail || {}).length" posterType="pintuan_goods" :posterId="props.goodsDetail?.goods?.poster_id" :posterParam="posterParam" :copyUrlParam="copyUrlParam" :copyUrl="copyUrl" @close="posterClose" />
    </view>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted,computed } from 'vue';
import { getPintuanGroupListApi } from '@/addon/pintuan/api/pintuan';
import { img ,redirect} from '@/utils/common';
import usePintuanGoodsDetailStore from '@/addon/pintuan/stores/goodsDetail';
import sharePoster from '@/components/share-poster/share-poster.vue';
import useMemberStore from '@/stores/member'
const memberStore = useMemberStore()
const userInfo = computed(() => memberStore.info)
// 定义 props
const props = defineProps<{
    goodsDetail: any
}>();

// 定义 emits
const emit = defineEmits<{
    change: [id: any]
}>();

const goodsSkuPop = ref(false);
const loading = ref(false);
const error = ref(false);
const pintuanList = ref<any[]>([]);

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

// 倒计时相关
let countdownTimer: any = null;

// 动态倒计时显示
const currentTime = ref(Date.now());

// 格式化剩余时间 - 支持动态倒计时
const formatRemainingTime = (expireTime: string) => {
    if (!expireTime) return "已结束";

    const expire = new Date(expireTime.replace(/-/g, "/")).getTime();
    const diff = expire - currentTime.value;

    if (diff <= 0) return "已结束";

    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);

    if (days > 0) {
        return `${days}天${hours.toString().padStart(2, "0")}:${minutes
            .toString()
            .padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
    } else if (hours > 0) {
        return `${hours.toString().padStart(2, "0")}:${minutes
            .toString()
            .padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
    } else {
        return `${minutes.toString().padStart(2, "0")}:${seconds
            .toString()
            .padStart(2, "0")}`;
    }
};

// 启动倒计时
const startCountdown = () => {
    if (countdownTimer) {
        clearInterval(countdownTimer);
    }

    countdownTimer = setInterval(() => {
        currentTime.value = Date.now();

        // 检查是否有拼团已过期，如果有则重新加载列表
        const hasExpired = pintuanList.value.some(item => {
            if (!item.expire_time) return false;
            const expire = new Date(item.expire_time.replace(/-/g, "/")).getTime();
            return expire <= currentTime.value;
        });

        if (hasExpired) {
            // loadPintuanList();
        }
    }, 1000);
};

// 停止倒计时
const stopCountdown = () => {
    if (countdownTimer) {
        clearInterval(countdownTimer);
        countdownTimer = null;
    }
};

const open = (type?: any) => {
    goodsSkuPop.value = true;
    // 加载拼团列表数据
    loadPintuanList();
    // 启动倒计时
    startCountdown();
}

const closeFn = () => {
    goodsSkuPop.value = false;
    // 停止倒计时
    stopCountdown();
    // #ifdef H5
    document.body.style.overflow = ''
    // #endif
}

const loadPintuanList = async () => {
    loading.value = true;
    error.value = false;

    try {
        // 调用真实的API - 与 goods detail 页面相同的实现
        const response: any = await getPintuanGroupListApi({
            pintuan_id: props.goodsDetail?.pintuan_id || ""
        });

 
        // 处理分页数据结构 - 与 goods detail 页面相同的逻辑
        if (response.data && response.data.data && Array.isArray(response.data.data)) {
            pintuanList.value = response.data.data;
        } else if (
            response.data &&
            response.data.data &&
            response.data.data.data &&
            Array.isArray(response.data.data.data)
        ) {
            // 处理分页格式：{data: {data: [...], current_page: 1, last_page: 1, total: 0}}
            pintuanList.value = response.data.data.data;
        } else {
            pintuanList.value = [];
        }

        // 如果有数据且弹窗是打开状态，启动倒计时
        if (pintuanList.value.length > 0 && goodsSkuPop.value) {
            startCountdown();
        }

    } catch (err) {
         error.value = true;
        pintuanList.value = [];
    } finally {
        loading.value = false;
    }
}
// 参与拼团 - 与 goods detail 页面相同的实现
const joinPintuan = (item: any) => {
    if (item.status !== 'process') {
        uni.showToast({
            title: '该拼团已结束',
            icon: 'none'
        });
        return;
    }
     if(item.is_me == 1 || item.is_join==1){
        // 打开分享海报
        posterParam.value.pintuan_id = props.goodsDetail?.pintuan_id;
        posterParam.value.group_id = item.id;
        // if (props.goodsDetail?.userInfo && props.goodsDetail?.userInfo.member_id) {
        //     posterParam.value.member_id = props.goodsDetail?.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=${props.goodsDetail?.pintuan_id}&group_id=${item.id}`;
        // 使用 store 来打开分享海报
        // const pintuanStore = usePintuanGoodsDetailStore();
        // pintuanStore.setGoodsDetail({ isOpenSharePoster: true });
        sharePosterRef.value.openShare({isPreload:false})
        return
        
    }
    // 触发 change 事件，传递拼团信息给父组件
    // 这样父组件可以设置相应的参数并打开 SKU 选择器
     emit('change', {
        id: item.id,
        check_ladder: item.check_ladder
    });

    // 关闭当前弹窗
    closeFn();
}

// 分享海报关闭回调
const posterClose = () => {
    const pintuanStore = usePintuanGoodsDetailStore();
    pintuanStore.setGoodsDetail({ isOpenSharePoster: false });
}
 
const onPopupOpen = () => {
    // H5 禁止滚动
    // #ifdef H5
    document.body.style.overflow = 'hidden'
    // #endif
}
// 组件卸载时清理定时器
onUnmounted(() => {
    stopCountdown();
});

defineExpose({
    open
})
</script>

<style scoped>
/* 加载动画 */
.animate-spin {
    animation: spin 1s linear infinite;
}

@keyframes spin {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

/* 拼团项目悬停效果 */
.pintuan-item {
    transition: background-color 0.2s ease;
}

.pintuan-item:active {
    background-color: #f8f8f8;
}

/* 按钮点击效果 */
.pintuan-item view[class*="bg-[#ff4444]"]:active {
    opacity: 0.8;
    transform: scale(0.98);
}

 
</style>