<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="bottom" :overlay="false" zIndex="500" overlayOpacity="0.8">
                <view class="py-[32rpx] relative" v-if="goodsDetail.detail" @touchmove.prevent.stop>
                    <view class="flex px-[32rpx] mb-[20rpx]">
                        <view class="rounded-[var(--goods-rounded-big)] overflow-hidden w-[180rpx] h-[180rpx]">
                            <u--image width="180rpx" height="180rpx" :src="img(goodsDetail.detail.sku_image)" @click="imgListPreview(goodsDetail.detail.sku_image)" model="aspectFill">
                                <template #error>
                                    <image class="w-[180rpx] h-[180rpx]" :src="img('static/resource/images/diy/shop_default.jpg')" mode="aspectFill" />
                                </template>
                            </u--image>
                        </view>
                        <view class="flex flex-1 flex-col justify-between ml-[24rpx] py-[10rpx]">
                            <view class="w-[100%]">
                                <view class="text-[var(--price-text-color)] flex items-baseline">
                                    <text class="text-[32rpx] font-bold price-font">￥</text>
                                    <text class="text-[48rpx] price-font">{{ parseFloat(goodsPrice).toFixed(2).split('.')[0] }}</text>
                                    <text class="text-[32rpx] mr-[6rpx] price-font">.{{ parseFloat(goodsPrice).toFixed(2).split('.')[1] }}</text>

                                    <text class="text-[24rpx] text-[#aaa]" v-if="goodsPrice2 >0 && goodsDetail.leader_discount=='on'&& callback ==0">
                                        （团长价：￥{{ parseFloat(goodsPrice2).toFixed(2).split('.')[0] }}.{{ parseFloat(goodsPrice2).toFixed(2).split('.')[1] }}）
                                    </text>
                                </view>
                                <view class="text-[26rpx] leading-[32rpx] text-[var(--text-color-light6)] mt-[12rpx]">库存{{ goodsDetail.detail.stock }}{{ goodsDetail.unit }}</view>
                            </view>
                            <view class="text-[26rpx] leading-[30rpx] text-[var(--text-color-light6)] w-[100%] max-h-[60rpx] multi-hidden" v-if="goodsDetail.spec && goodsDetail.spec.length">已选规格：{{ goodsDetail.detail.sku_spec_format }}</view>
                        </view>
                    </view>
                    <scroll-view class="h-[500rpx] px-[32rpx] box-border mb-[60rpx]" scroll-y="true">
                         <!-- 阶梯类型选择 -->
                        <view class="mb-[20rpx]" v-if="goodsDetail.type=='ladder' && callback ==0">
                            <view class="text-[28rpx] leading-[36rpx] mb-[24rpx]">阶梯类型</view>
                            <view class="flex flex-wrap">
                                <view class="box-border bg-[var(--temp-bg)] text-[24rpx] px-[44rpx] text-center h-[56rpx] flex-center mr-[20rpx] mb-[20rpx] border-1 border-solid rounded-[50rpx] border-[var(--temp-bg)]"
                                    :class="{
                                        '!border-[var(--primary-color)] text-[var(--primary-color)] !bg-[var(--primary-color-light)]': (goodsDetail.join_type == 'join_group' && goodsDetail.check_ladder == item.ladder) || (goodsDetail.join_type != 'join_group' && selectedLadder === item.ladder),
                                        '!bg-[#f5f5f5] !text-[#ccc] !border-[#f5f5f5]': goodsDetail.check_ladder && goodsDetail.check_ladder !== item.ladder && goodsDetail.join_type == 'join_group'
                                    }"
                                    v-for="(item,index) in goodsDetail.member_num_config.ladder" :key="index"
                                    @click="changeLadder(item)">{{ item.member_num }}人团</view>
                            </view>
                        </view>

                        <view :class="{'mt-[20rpx]': 0 != index }" v-for="(item,index) in goodsDetail.goods.spec_list" :key="index">
                            <view class="text-[28rpx] leading-[36rpx] mb-[24rpx]">{{ item.spec_name }}</view>
                            <view class="flex flex-wrap">
                                <view class="box-border bg-[var(--temp-bg)] text-[24rpx] px-[44rpx] text-center h-[56rpx] flex-center mr-[20rpx] mb-[20rpx] border-1 border-solid rounded-[50rpx] border-[var(--temp-bg)]"
                                    :class="{'!border-[var(--primary-color)] text-[var(--primary-color)] !bg-[var(--primary-color-light)]': subItem.selected}"
                                    v-for="(subItem,subIndex) in item.values" :key="subIndex"
                                    @click="change(subItem, index)">{{ subItem.name }}</view>
                            </view>
                        </view>
                        <view class="flex justify-between items-center my-[20rpx]">
                            <view class="text-[28rpx]">购买数量</view>
                            <text v-if="goodsDetail.detail?.order_limit_buy>0 && goodsDetail.is_single_buy == 0" class="ml-[20rpx] text-[24rpx] text-[var(--primary-color)]">(每单限购{{ goodsDetail.detail.order_limit_buy }}{{ goodsDetail.goods.unit }})</text>
                            <text v-if="goodsDetail.detail?.member_limit_buy>0 && goodsDetail.is_single_buy == 0" class="ml-[10rpx] mr-[auto] text-[24rpx] text-[var(--primary-color)]">(每人限购{{ goodsDetail.detail.member_limit_buy }}{{ goodsDetail.goods.unit }})</text>
                            <u-number-box :min="minBuy" :max="maxBuy" integer :step="1" input-width="68rpx" v-model="buyNum" input-height="52rpx">
                                <template #minus>
                                    <view class="relative w-[30rpx] h-[30rpx]" @click="reduceNumChange">
                                        <text class="text-[30rpx] nc-iconfont nc-icon-jianV6xx font-500 absolute flex items-center justify-center -left-[8rpx] -bottom-[8rpx] -right-[8rpx] -top-[8rpx]"
                                            :class="{ '!text-[var(--text-color-light9)]': buyNum <= minBuy }"></text>
                                    </view>
                                </template>
                                <template #input>
                                    <input class="text-[#303133] text-[28rpx] mx-[10rpx] w-[80rpx] h-[44rpx] bg-[var(--temp-bg)] leading-[44rpx] text-center rounded-[6rpx]"
                                        type="number" @input="goodsSkuInputFn" @blur="goodsSkuBlurFn" v-model="buyNum" />
                                </template>
                                <template #plus>
                                    <view class="relative w-[30rpx] h-[30rpx]" @click="addNumChange">
                                        <text class="text-[30rpx] nc-iconfont nc-icon-jiahaoV6xx font-500 absolute flex items-center justify-center -left-[8rpx] -bottom-[8rpx] -right-[8rpx] -top-[8rpx]"
                                            :class="{ '!text-[var(--text-color-light9)]': buyNum >= maxBuy || buyNum == 0 }"></text>
                                    </view>
                                </template>
                            </u-number-box>
                        </view>
                        <view class="mt-[40rpx]">
                            <diy-form ref="diyFormRef" :form_id="goodsDetail.form_id" :storage_name="'diyFormStorageByGoodsDetail_' + goodsDetail.goods.default_sku.id" />
                        </view>
                    </scroll-view>
                    <view class="px-[20rpx]">

                        <!-- #ifndef MP -->
                        <button v-if="goodsDetail.detail.stock > 0" hover-class="none" class="!h-[80rpx] leading-[80rpx] text-[26rpx] font-500 rounded-[50rpx] primary-btn-bg" type="primary" @click="confirm">确定</button>
                        <!-- #endif -->

                        <!-- #ifdef MP -->
                        <template v-if="goodsDetail.detail.stock > 0">
                            <button hover-class="none" class="!h-[80rpx] leading-[80rpx] text-[26rpx] font-500 rounded-[50rpx] primary-btn-bg" type="primary" @click="confirm">确定</button>
                        </template>
                        <!-- #endif -->

                        <button v-else hover-class="none"  class="!h-[80rpx] leading-[80rpx] text-[26rpx] font-500 text-[#fff] bg-[#ccc] rounded-[50rpx]">已售罄</button>
                    </view>
                </view>
            </u-popup>
        </u-overlay>
        <!-- 强制绑定手机号 -->
        <bind-mobile ref="bindMobileRef" />
    </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { img, redirect } from '@/utils/common'
import { useLogin } from '@/hooks/useLogin'
import useMemberStore from '@/stores/member'
import bindMobile from '@/components/bind-mobile/bind-mobile.vue';
import { cloneDeep } from 'lodash-es'
import { t } from '@/locale'
import diyForm from '@/addon/components/diy-form/index.vue'
import usePintuanGoodsDetailStore from '@/addon/pintuan/stores/goodsDetail'

import {
    checkPintuanGroupApi,
} from "@/addon/pintuan/api/pintuan";
const props = defineProps(['goodsDetail']);
const goodsSkuPop = ref(false);
const callback: any = ref(null);
const currSpec = ref({
    skuId: "",
    name: []
})
const openType = ref("");
const buyNum = ref(1)

const maxBuy = ref(0); // 限购
const minBuy = ref(0); // 起售

// 阶梯类型数据
const selectedLadder = ref(1); // 默认选择第一个阶梯

// 商品价格
const goodsPrice = computed(() => {
    let price = 0;
    if(callback.value == 1){
        price = goodsDetail.value.detail.price_config.original;
    }else{
        price = goodsDetail.value.type=='ladder'?goodsDetail.value.detail.price_config.ladder[selectedLadder.value-1].price : goodsDetail.value.detail.price_config.pintuan;
    }
    return price;
})
const goodsPrice2 = computed(() => {
    return goodsDetail.value.detail.price_config.leader;
})
// 会员信息
const memberStore = useMemberStore()
const userInfo = computed(() => memberStore.info)

const open = (type = "", fn = "") => {
    openType.value = type;
    goodsSkuPop.value = true;
    callback.value = fn;

    // 根据 check_ladder 设置默认选择
    if (props.goodsDetail.check_ladder && props.goodsDetail.member_num_config && props.goodsDetail.member_num_config.ladder) {
        selectedLadder.value = props.goodsDetail.check_ladder;
    }

    // 通知父级 SKU 弹窗已打开
    emits('open');
}

const goodsSkuInputFn = () => {
    setTimeout(() => {
        buyNum.value = parseInt(buyNum.value)
        if (!buyNum.value || buyNum.value <= minBuy.value) {
            buyNum.value = minBuy.value || 1;
        }
        if (buyNum.value >= maxBuy.value) {
            buyNum.value = maxBuy.value;
        }
        if (buyNum.value >= goodsDetail.value.goods.default_sku.stock) {
            buyNum.value = goodsDetail.value.goods.default_sku.stock;
        }
        // 起售大于库存，初始值也应该是零
        if (minBuy.value > goodsDetail.value.goods.default_sku.stock) {
            buyNum.value = 0;
        }
    }, 0)
}

const goodsSkuBlurFn = () => {
    setTimeout(() => {
        buyNum.value = parseInt(buyNum.value)
        if (!buyNum.value || buyNum.value <= minBuy.value) {
            buyNum.value = minBuy.value || 1;
        }
        if (buyNum.value >= maxBuy.value) {
            buyNum.value = maxBuy.value;
        }
        if (buyNum.value >= goodsDetail.value.goods.default_sku.stock) {
            buyNum.value = goodsDetail.value.goods.default_sku.stock;
        }
        // 起售大于库存，初始值也应该是零
        if (minBuy.value > goodsDetail.value.goods.default_sku.stock) {
            buyNum.value = 0;
            uni.showToast({
                title: '商品库存小于起购数量',
                icon: 'none'
            });
        }
    }, 0)
}

const closeFn = () => {
    goodsSkuPop.value = false
    // 通知父级 SKU 弹窗已关闭
    emits('close');
}

const goodsDetail = computed(() => {
    let data = cloneDeep(props.goodsDetail);
    // 重组数据结构
    if (Object.keys(data).length) {

        if (!Object.keys(currSpec.value.name).length) currSpec.value.name = data.goods.default_sku.sku_spec_format.split(",");
        data.goods.spec_list.forEach((item: any, index: any) => {
            let specName = item.spec_values.split(",");
            item.values = [];

            // 根据 sku_list 的顺序来排序规格值
            if (data.goods.sku_list && data.goods.sku_list.length > 0) {
                // 收集当前规格位置的所有可能值，按 sku_list 中出现的顺序
                let orderedSpecValues: string[] = [];
                let addedValues = new Set<string>();

                data.goods.sku_list.forEach((skuItem: any) => {
                    if (skuItem.sku_spec_format) {
                        let skuSpecs = skuItem.sku_spec_format.split(",");
                        if (skuSpecs[index] && specName.includes(skuSpecs[index]) && !addedValues.has(skuSpecs[index])) {
                            orderedSpecValues.push(skuSpecs[index]);
                            addedValues.add(skuSpecs[index]);
                        }
                    }
                });

                // 添加剩余未在 sku_list 中出现的规格值
                specName.forEach((specItem: any) => {
                    if (!addedValues.has(specItem)) {
                        orderedSpecValues.push(specItem);
                    }
                });

                // 按新顺序创建 values 数组
                orderedSpecValues.forEach((specItem: any, specIndex: any) => {
                    item.values[specIndex] = {};
                    item.values[specIndex].name = specItem;
                    item.values[specIndex].selected = false;
                    item.values[specIndex].disabled = false;

                    // 选中规格
                    currSpec.value.name.forEach((currSpecItem, currSpecIndex) => {
                        if (currSpecIndex == index && currSpecItem == specItem) {
                            item.values[specIndex].selected = true;
                        }
                    })
                });
            } else {
                // 如果没有 sku_list，保持原有逻辑
                specName.forEach((specItem: any, specIndex: any) => {
                    item.values[specIndex] = {};
                    item.values[specIndex].name = specItem;
                    item.values[specIndex].selected = false;
                    item.values[specIndex].disabled = false;

                    // 选中规格
                    currSpec.value.name.forEach((currSpecItem, currSpecIndex) => {
                        if (currSpecIndex == index && currSpecItem == specItem) {
                            item.values[specIndex].selected = true;
                        }
                    })
                });
            }
        })
        getSkuId();

        // 当前详情内容
        if (data.goods.sku_list && Object.keys(data.goods.sku_list).length) {
            data.goods.sku_list.forEach((idItem: any, idIndex: any) => {
                if (idItem.id == currSpec.value.skuId) {
                    idItem.sku_image = idItem.sku_image ? idItem.sku_image : data.goods.cover
                    data.detail = idItem;
                }
            })
        }
    }
    if(data.goods.default_sku.order_limit_buy >0 && data.detail.stock >data.goods.default_sku.order_limit_buy && !data.isSingle){
        maxBuy.value =data.goods.default_sku.order_limit_buy
    }else{
        maxBuy.value = data.detail.stock
    }



    return data;
})

const change = (data: any, index: any) => {
    currSpec.value.name[index] = data.name;
    getSkuId(); // 刷新当前规格信息
}

// 阶梯类型选择
const changeLadder = (ladder: any) => {
    // 如果存在 check_ladder，则禁止所有阶梯选择
    if (goodsDetail.value.check_ladder && goodsDetail.value.join_type =='join_group') {
        return;
    }
    selectedLadder.value = ladder.ladder;
}

const emits = defineEmits(['change', 'open', 'close'])
const sulkey = ref({})
const getSkuId = () => {
    props.goodsDetail.goods.sku_list.forEach((skuItem: any, skuIndex: any) => {
        if (skuItem.sku_spec_format == currSpec.value.name.toString()) {
            currSpec.value.skuId = skuItem.id
            sulkey.value = skuItem
            emits('change', skuItem.id)
        }
    })
}

const addNumChange = () => {
    if (minBuy.value && minBuy.value > goodsDetail.value.goods.default_sku.stock) {
        uni.showToast({ title: '商品库存小于起购数量', icon: 'none' })
        return;
    }
}

const reduceNumChange = () => {
    if (minBuy.value > 1) {
        let tips = `该商品起购${ minBuy.value }件`;
        if (buyNum.value <= minBuy.value) {
            uni.showToast({ title: tips, icon: 'none' })
        }
    }
}

//强制绑定手机号
const bindMobileRef: any = ref(null)
const isBindMobile = ref(uni.getStorageSync('isBindMobile'))

const diyFormRef: any = ref(null)

//提交
const confirm = async () => {
      if(goodsDetail.value.is_single_buy == '' || goodsDetail.value.is_single_buy == null || goodsDetail.value.is_single_buy == undefined || goodsDetail.value.is_single_buy == 'undefined'){
        goodsDetail.value.is_single_buy = 0
      }
       if(goodsDetail.value.is_single_buy == 0){
        try {
            let json={
                pintuan_id: goodsDetail.value.goods.pintuan_id,
                group_id: goodsDetail.value.group_id ? goodsDetail.value.group_id : '',
                join_type:goodsDetail.value.isbuy == 0?'open_group': goodsDetail.value.join_type
            }
            if(!goodsDetail.value.group_id){
                delete json.group_id
            }
            const res = await checkPintuanGroupApi({
               ...json
            })
            if(res.data.error == '会员不存在' || res.data.error == '账号不存在'){

            }else  if (res.data.error != '') {
                uni.showToast({ title: res.data.error, icon: 'none'   })
                usePintuanGoodsDetailStore().setGoodsDetail({
                    is_recalculate:Math.floor((Math.random()*10)+1)
                })
                return
            }
        } catch (error) {
            uni.showToast({ title: '网络错误，请重试', icon: 'none' })
            return
        }
         if( (sulkey.value.member_buy_num >=sulkey.value.member_limit_buy ) && sulkey.value.member_limit_buy>0){
            uni.showToast({ title: '超出限购数量', icon: 'none'  , width: 300})
            return
        }
    }
    // default_sku
    // return
    if (!diyFormRef.value.verify()) return;
    if (buyNum.value < 1) return;

    // #ifdef H5
    // 绑定手机号
    if (!userInfo.value && uni.getStorageSync('isBindMobile')) {
        uni.setStorage({
            key: 'loginBack', data: {
                url: '/addon/pintuan/pages/goods/detail',
                param: {
                    pintuan_id: goodsDetail.value.goods.pintuan_id,
                    group_id:goodsDetail.value.group_id?goodsDetail.value.group_id: goodsDetail.value.goods.id,
                }
            }
        })
        bindMobileRef.value.open()
        return false
    }
    // #endif

    // 检测是否登录
    if (!userInfo.value) {
         // return false
        useLogin().setLoginBack({
            url: '/addon/pintuan/pages/goods/detail',
            param: {
                pintuan_id: goodsDetail.value.goods.pintuan_id,
                group_id:goodsDetail.value.group_id?goodsDetail.value.group_id: '',
            }
        })
        return false
    }
    if(goodsDetail.value.is_single_buy == '' || goodsDetail.value.is_single_buy == null || goodsDetail.value.is_single_buy == undefined || goodsDetail.value.is_single_buy == 'undefined'){
        goodsDetail.value.is_single_buy = 0
      }
      if(goodsDetail.value.is_single_buy == 0){
        try {
            const res = await checkPintuanGroupApi({
                pintuan_id: goodsDetail.value.goods.pintuan_id,
                group_id: goodsDetail.value.group_id ? goodsDetail.value.group_id : goodsDetail.value.goods.id,
                join_type:goodsDetail.value.isbuy == 0?'open_group': goodsDetail.value.join_type
            })
            if(res.data.error == '会员不存在' || res.data.error == '账号不存在'){

            }else  if (res.data.error != '') {
                uni.showToast({ title: res.data.error, icon: 'none'   })
                usePintuanGoodsDetailStore().setGoodsDetail({
                    is_recalculate:Math.floor((Math.random()*10)+1)
                })
                return
            }
        } catch (error) {
            console.error('拼团检查失败:', error)
            uni.showToast({ title: '网络错误，请重试', icon: 'none' })
            return
        }
        //  return

         if( (sulkey.value.member_buy_num >=sulkey.value.member_limit_buy ) && sulkey.value.member_limit_buy>0){
            uni.showToast({ title: '超出限购数量', icon: 'none'  , width: 300})
            return
        }
    }


    // 立即购买
    if (openType.value == 'buy_now') {

        let obj = {

            sku_data:{
                id:goodsDetail.value.detail.id,
                num:buyNum.value
            },
            pintuan_id: goodsDetail.value.goods.pintuan_id,
               group_id:goodsDetail.value.group_id?goodsDetail.value.group_id:'',
            ladder: selectedLadder.value,
            join_type: goodsDetail.value.join_type,
            is_need_recalculate:  goodsDetail.value.is_need_recalculate,
             is_single_buy: goodsDetail.value.is_single_buy,

        }


        uni.setStorage({
            key: 'pintuan0rderCreateData',
            data: {
                ...obj
            },
            success: () => {
                redirect({ url: '/addon/pintuan/pages/order/payment' })
            }
        });
    }

    closeFn();
}

//预览图片
const imgListPreview = (item: any) => {
    if (item === '') return false
    const urlList = [];
    urlList.push(img(item))  //push中的参数为 :src="item.img_url" 中的图片地址
    uni.previewImage({
        indicator: "number",
        loop: true,
        urls: urlList
    })
}
defineExpose({
    open
})
</script>

<style lang="scss" scoped>
::v-deep .u-number-box .u-number-box__slot {
    display: flex;
    align-items: center;
}
::v-deep .uni-scroll-view{
    position:inherit;
}
</style>
