<template>
    <view :style="themeColor()">
        <!-- 自定义模板渲染 -->
        <view class="diy-template-wrap bg-index" :style="diy.pageStyle()">
            <diy-group ref="diyGroupRef" :data="diy.data" />
        </view>
        <ns-goods-sku ref="goodsSkuRef" v-if="Object.keys(pintuanGoodsData).length" :goods-detail="pintuanGoodsData" @change="specSelectFn" @open="onSkuOpen" @close="onSkuClose"></ns-goods-sku>
        <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" />

        <!-- 引入新組件 -->
        <!-- 被邀请 -->
        <invite-popup ref="invitePopupRef" @join="addpingtuan" v-if="invitePopupRefshow" :grouPinfo="grouPinfo"
            @close="closeInvitePopup"></invite-popup>
        <!-- 来晚了  -->
        <invite-success ref="inviteSuccessRef" @confirm="showInviteSuccess" v-if="inviteSuccessRefshow"  :grouPinfo="grouPinfo"  :pintuanInfo="pintuanGoodsData"
            @close="closeInviteSuccess"></invite-success>
        <!-- 强制展示的拼团 -->
         <force-pintuan ref="forcePintuanRef" @confirm="addpingtuan" v-if="forcePintuanRefshow"  :grouPinfo="grouPinfo" :pintuanInfo="pintuanGoodsData"
            @close="closeForcePintuan"></force-pintuan>
         <!-- 我的拼团 -->
        <!-- <my-pintuan ref="myPintuanRef" v-if="myPintuanRefshow" @confirm="openShareFn" :grouPinfo="grouPinfo" :pintuanInfo="pintuanGoodsData"	@close="closeMyPintuan"></my-pintuan> -->

        <!-- #ifdef MP-WEIXIN -->
        <!-- 小程序隐私协议 -->
        <wx-privacy-popup ref="wxPrivacyPopupRef"></wx-privacy-popup>
        <!-- #endif -->
    </view>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue';
import nsGoodsSku from '@/addon/pintuan/components/ns-goods-sku/ns-goods-sku.vue';
import useMemberStore from '@/stores/member'
import { useShare } from '@/hooks/useShare'
import sharePoster from '@/components/share-poster/share-poster.vue'
import { useDiyPintuanGoodsDetail } from '@/addon/pintuan/hooks/useDiyGoodsDetail'
import usePintuanGoodsDetailStore from '@/addon/pintuan/stores/goodsDetail'
import invitePopup from "@/addon/pintuan/components/invite-popup/invite-popup.vue";
import inviteSuccess from "@/addon/pintuan/components/invite-success/invite-success.vue";
import forcePintuan from "@/addon/pintuan/components/force-pintuan/force-pintuan.vue";
import myPintuan from "@/addon/pintuan/components/my-pintuan/my-pintuan.vue";
import {
    checkPintuanGroupApi,
    pintuanGroupProcessApi,
    getPintuanGroupListApi,
    getPintuanDetail
} from "@/addon/pintuan/api/pintuan";
import { onLoad } from '@dcloudio/uni-app'


const { setShare } = useShare()

const goodsSkuRef: any = ref(null);
const sharePosterRef: any = ref(null);
const posterParam = ref({});
const copyUrl = ref('/addon/pintuan/pages/goods/detail')
const copyUrlParam = ref('');

const diy = useDiyPintuanGoodsDetail({
    name: 'DIY_PINTUAN_GOODS_DETAIL'
})

const memberStore = useMemberStore()
const userInfo = computed(() => memberStore.info)
const pintuanGoodsData = computed(() => usePintuanGoodsDetailStore().goodsDetail)

// 弹窗相关状态
const forcePintuanRefshow = ref(false)
const invitePopupRefshow = ref(false)
const inviteSuccessRefshow = ref(false)
const grouPinfo = ref({})
const isSkuOpening = ref(false) // 标记 SKU 选择器是否正在打开
const pingtuanglist = ref<any[]>([]) // 拼团列表数据

// 弹窗引用
const invitePopupRef = ref(null)
const inviteSuccessRef = ref(null)
const forcePintuanRef = ref(null)
const myPintuanRef = ref(null)

// 弹窗优先级控制函数
const checkPopupPriority = () => {
    // 按照 force-pintuan > my-pintuan > invite-popup > invite-success 的优先级显示弹窗
    if (forcePintuanRefshow.value) {
        invitePopupRefshow.value = false
        inviteSuccessRefshow.value = false
    } else if (invitePopupRefshow.value) {
        inviteSuccessRefshow.value = false
    }
}

// 监听各弹窗状态变化，自动调整优先级
watch([forcePintuanRefshow, 
// myPintuanRefshow, 
invitePopupRefshow, inviteSuccessRefshow], () => {
    checkPopupPriority()
})

// 弹窗关闭函数
const closeForcePintuan = () => {
    forcePintuanRefshow.value = false

    // listeningAndSharingFunction()
    
    // 如果 SKU 正在打开，不显示其他弹窗
    if (isSkuOpening.value) {
        return
    }
}



const closeInvitePopup = () => {
    invitePopupRefshow.value = false;
};

const closeInviteSuccess = () => {
    inviteSuccessRefshow.value = false;
};


const showInviteSuccess = () => {
    // 延迟显示，确保其他弹窗已关闭
    nextTick(() => {
        inviteSuccessRefshow.value = true;
        checkPopupPriority();
    });
};

// 参与拼团
const addpingtuan = (item: any) => {
    if (goodsSkuRef.value) {
        usePintuanGoodsDetailStore().setGoodsDetail({
            join_type: "join_group",
            group_id: item.id,
            is_need_recalculate: 1,
            isOpenSkuBuy: true,
            skuBuyType: "buy_now",
            is_single_buy: 0,
            isSingle:0,
            check_ladder: item.check_ladder
        });
    }
};

// 获取拼团列表
const getPintuanGroupListfu = () => {
    const pintuanId = pintuanGoodsData.value?.pintuan_id || pintuanGoodsData.value?.id;

    if (!pintuanId) {
        pingtuanglist.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;
            } else if (
                res.data &&
                res.data.data &&
                res.data.data.data &&
                Array.isArray(res.data.data.data)
            ) {
                 pingtuanglist.value = res.data.data.data;
            } else {
                pingtuanglist.value = [];
            }
        })
        .catch((err: any) => {
             pingtuanglist.value = [];
        });
};


// 打开分享
const openShareFn = () => {
    posterParam.value.group_id = grouPinfo.value.id
    copyUrlParam.value += '&group_id=' + pintuanGoodsData.value.group_id
    usePintuanGoodsDetailStore().setGoodsDetail({ isOpenSharePoster: true })
    // group_id
};

watch(
    () => pintuanGoodsData.value.isOpenSkuBuy,
    (newValue, oldValue) => {
        if (newValue && goodsSkuRef.value) {
            goodsSkuRef.value.open(pintuanGoodsData.value.skuBuyType, pintuanGoodsData.value.isSingle);
            if(pintuanGoodsData.value.join_type === 'join_group'){
                pintuanGoodsData.value.join_type = "join_group";
                pintuanGoodsData.value.group_id = pintuanGoodsData.value.group_id;
                pintuanGoodsData.value.is_need_recalculate = 1;

            }else{
                pintuanGoodsData.value.join_type = "open_group";
                pintuanGoodsData.value.is_need_recalculate = 0;
                pintuanGoodsData.value.is_single_buy = pintuanGoodsData.value.isSingle;
            }
        } else if (!newValue && oldValue) {
            // SKU 关闭时，重置标记
            isSkuOpening.value = false;
            pintuanGoodsData.value.isOpenSkuBuy = false
        }
    }
)

watch(
    () => pintuanGoodsData.value.isOpenSharePoster,
    (newValue, oldValue) => {
        if (newValue && sharePosterRef.value) {
   
            posterParam.value.pintuan_id = pintuanGoodsData.value.pintuan_id;
             if(userInfo.value && userInfo.value.member_id){
                posterParam.value.member_id =  userInfo.value.member_id;
            }
          

            // posterParam.value.group_id = pintuanGoodsData.value.group_id;

            copyUrlParam.value = '?pintuan_id='+ pintuanGoodsData.value.pintuan_id;
            if(grouPinfo.value.id){
                copyUrlParam.value += '&group_id=' + grouPinfo.value.id
            }
            console.log(grouPinfo.value,'。。。')
            sharePosterRef.value.openShare()
        }
    }
)
watch(
    () => pintuanGoodsData.value.pintuan_id,
    (newValue, oldValue) => {
 

         if (newValue) {
             // 如果有 pintuan_id，获取拼团列表（但不一定显示弹窗）
           

             // 检查用户的拼团状态（显示 my-pintuan）
             // 如果您希望 my-pintuan 也需要 group_id 才显示，请取消下面的注释
             // if (pintuanGoodsData.value.group_id && pintuanGoodsData.value.group_id !== '') {
             if (true) { // 暂时允许显示 my-pintuan，如果需要限制请修改这个条件
                 getPintuanGroupListfu();
                 pintuanGroupProcessApi({
                     pintuan_id: newValue
                 }).then((res: any) => {
                     //  if (res.data.length > 0) {
                         if (res.data.status == "process") {
                             
                             grouPinfo.value = res.data;
                              // 如果 SKU 正在打开，不显示 my-pintuan 弹窗
                             if (!isSkuOpening.value) {
                                //  myPintuanRefshow.value = true;
                                 checkPopupPriority();
                             }
                         }
                    //  }
                 })
             } 
         }
    }
)
const canIShareIt = ref(false)
watch(
    () => pintuanGoodsData.value.group_id_two,
    (newValue, oldValue) => {
          // 只有当有 group_id 且不为空时，才检查拼团状态
         if (newValue && newValue !== '') {
            //    if(pintuanGoodsData.value.channel=='index'){
                 
            //     setTimeout(() => {
            //         addpingtuan({id:newValue})
            //     }, 1000);
            //   }else{
            //     setTimeout(() => {
            //         listeningAndSharingFunction();
            //     }, 1000);
            //  }
             setTimeout(() => {
                    listeningAndSharingFunction();
                }, 1000);
         } else {
          }
    }
)
watch(
    () => pintuanGoodsData.value.isbuy,
    (newValue, oldValue) => {
        if (newValue && newValue !== '') {
               setTimeout(() => {
                    usePintuanGoodsDetailStore().setGoodsDetail({
                        is_single_buy: newValue,
                        isSingle: newValue,
                        isOpenSkuBuy: true,
                        skuBuyType: 'buy_now',
                        // join_type: "open_group",
                        is_need_recalculate: 1,
                        isbuy: newValue
                    });
               }, 2000);
        } else {
        }
    }
)
 
const listeningAndSharingFunction = ()=>{
    checkPintuanGroupApi({
                        join_type: 'join_group',
                        pintuan_id: pintuanGoodsData.value.pintuan_id,
                        group_id:  pintuanGoodsData.value.group_id
                    }).then((res: any) => {
                        if (res.data.error == '' || res.data.error == '会员不存在') {
                             // 检查拼团是否已过期
                             if (pintuanGoodsData.value.group_info.expire_time) {
                                const now = new Date().getTime()
                                const expireTime = new Date(pintuanGoodsData.value.group_info.expire_time.replace(/-/g, '/')).getTime()
                                if (now > expireTime) {
                                    inviteSuccessRefshow.value = true
                                    return
                                }
                            }
                             
                              if(pintuanGoodsData.value.group_info.target_num == pintuanGoodsData.value.group_info.current_num){
                                    inviteSuccessRefshow.value = true
                                    canIShareIt.value = false
                                    return
                              }
                            if( canIShareIt.value == false){
                                
                                 forcePintuanRefshow.value = true
                            }
                          
                            canIShareIt.value = true
                            // 获取拼团组详细信息，用于 invite-popup 显示
                            // 从 pingtuanglist 中找到对应的拼团组信息
                            // const targetGroup = pingtuanglist.value.find((group: any) =>
                            //     group.id == pintuanGoodsData.value.group_id
                            // )
                           
                            // if (targetGroup) {
                            //     grouPinfo.value = targetGroup
                            // }
                            grouPinfo.value = pintuanGoodsData.value.group_info

                           
                            
                            // 确保其他弹窗都关闭后再显示 invite-popup
                            // nextTick(() => {
                            //   if( canIShareIt.value ==true){
                            //     invitePopupRefshow.value = true
                            //     checkPopupPriority()
                            //   }
                          
                            // });
                             

                        }else if(res.data.error == '您已参与当前拼团' ){
                            
                        } else if (res.data.error == "抱歉，当前团人数已满"  || res.data.error == "抱歉，当前团组已拼团失败") {
                            inviteSuccessRefshow.value = true
                            canIShareIt.value = false

                        } else {
                            canIShareIt.value = false

                            uni.showToast({
                                title: res.data.error,
                                icon: 'none'
                            })
                        }
                    })
}

const posterClose = () => {
    usePintuanGoodsDetailStore().setGoodsDetail({ isOpenSharePoster: false })
}

const specSelectFn = (id: any) => {
    const skuList = JSON.parse(JSON.stringify(usePintuanGoodsDetailStore().goodsDetail.goods.sku_list))


    skuList.forEach((item: any, index: any) => {
        if (item.sku_id == id) {
            let obj = {
                defaultSku: {
                    ...item
                }
            }
            usePintuanGoodsDetailStore()?.setGoodsDetail(obj);
        }
    })
}

// SKU 打开事件处理
const onSkuOpen = () => {
    // 设置 SKU 正在打开的标记
    isSkuOpening.value = true;

    // 关闭所有拼团相关弹窗，避免冲突
    forcePintuanRefshow.value = false;
    invitePopupRefshow.value = false;
    inviteSuccessRefshow.value = false;
}

// SKU 关闭事件处理
const onSkuClose = () => {
    // 重置 SKU 打开标记
    isSkuOpening.value = false;

    // 重置 store 中的 SKU 打开状态
    usePintuanGoodsDetailStore().setGoodsDetail({
        isOpenSkuBuy: false
    });

    // 按照之前的要求：不要在关闭 ns-goods-sku 的时候弹窗
    // 所以这里只重置状态，不显示其他弹窗
}

const diyGroupRef = ref(null)

const wxPrivacyPopupRef: any = ref(null)

// 监听页面显示
import { onShow } from '@dcloudio/uni-app'

// 监听页面加载
diy.onLoad();

// 监听页面显示
diy.onShow((data: any) => {
    // 触发组件刷新
    uni.$emit('pageShow');
    
    let share: any = {
        title: '',
        desc: '',
        url: pintuanGoodsData.value.goods?.cover || ""
    }
    if (pintuanGoodsData.value.group_id && pintuanGoodsData.value.group_id !== '' && pintuanGoodsData.value.group_id_two !== '') {
        share.title = pintuanGoodsData.value.share_config?.group?.title || pintuanGoodsData.value.goods?.title;
        share.desc = pintuanGoodsData.value.share_config?.group?.desc;
    }else{
        share.title = pintuanGoodsData.value.share_config?.normal?.title || pintuanGoodsData.value.goods?.title;
        share.desc = pintuanGoodsData.value.share_config?.normal?.desc;

    }
    setShare({
        wechat: {
            ...share
        },
        weapp: {
            ...share
        }
    });
        nextTick(() => {
        setTimeout(() => {
            if(pintuanGoodsData.value.pintuan_id){
                posterParam.value.pintuan_id = pintuanGoodsData.value.pintuan_id;
                if(userInfo.value && userInfo.value.member_id){
                    posterParam.value.member_id =  userInfo.value.member_id;
                }
                if(pintuanGoodsData.value.group_id){
                    posterParam.value.group_id = pintuanGoodsData.value.group_id;
                }

                // posterParam.value.group_id = pintuanGoodsData.value.group_id;

                copyUrlParam.value = '?pintuan_id='+ pintuanGoodsData.value.pintuan_id;
                if(grouPinfo.value.id){
                    copyUrlParam.value += '&group_id=' + grouPinfo.value.id
                }
            
                // sharePosterRef.value.openShare()
            }
            
         
        }, 500);
    })

});

// 添加标准 onShow 确保返回时触发
onShow(() => {
    // 触发组件刷新
    uni.$emit('pageShow');
    
    // 重新获取拼团列表
    getPintuanGroupListfu();
});
 
 
// 监听页面隐藏
diy.onHide();

// 监听页面卸载
diy.onUnload();

// 监听滚动事件
diy.onPageScroll()

// #ifdef MP
wx.onAppRoute((res) => {
    if(res.path !== 'addon/pintuan/pages/goods/detail'){
        usePintuanGoodsDetailStore().removeGoodsDetail()
    }
})
// #endif

</script>
 