<template>
    <view @touchmove.prevent.stop>
        <u-overlay :show="goodsSkuPop" @click="closeFn" zIndex="490">
            <u-popup class="popup-type" :show="goodsSkuPop" @close="closeFn" mode="bottom" :overlay="false" zIndex="500">
                <view class="py-[32rpx] relative" v-if="goodsDetail.detail" @touchmove.prevent.stop>
<!--                    mb-[58rpx]-->
                    <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   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>
                                </view>
                                <view class="text-[26rpx] leading-[32rpx] text-[var(--text-color-light6)] mt-[12rpx]">库存{{ goodsDetail.detail.seckill_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="{'mt-[20rpx]': 0 != index }" v-for="(item,index) in goodsDetail.spec" :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>
                            <block v-if="openType != 'buy_now_single'">
                                <text v-if="goodsDetail.detail.once_num >0" class="ml-[20rpx] text-[24rpx] text-[var(--primary-color)]">(每单限购{{ goodsDetail.detail.once_num }}{{ goodsDetail.unit }})</text>
                                <text v-if="goodsDetail.detail.sum_num >0" class="ml-[10rpx] mr-[auto] text-[24rpx] text-[var(--primary-color)]">(每人限购{{ goodsDetail.detail.sum_num }}{{ goodsDetail.unit }})</text>
                            </block>
                            <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" @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.defaultSku.sku_id" />
                        </view>
                    </scroll-view>
                    <view class="px-[20rpx]">
                        <button v-if="!isSeckill" hover-class="none" class="!h-[80rpx] leading-[80rpx] text-[26rpx] font-500 text-[#fff] bg-[#999] rounded-[50rpx]">
                            已售罄
                        </button>
                        <!-- #ifndef MP -->
                        <button v-else-if="goodsDetail.detail.seckill_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-else-if="goodsDetail.detail.seckill_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 useSeckillGoodsDetailStore from '@/addon/seckill/stores/goodsDetail'
import { getSeckillGoodsCheckTime } from '@/addon/seckill/api/goods'

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 goodsPrice = computed(() => {
    let price = 0;
    if(openType.value == 'buy_now_single'){
        price = goodsDetail.value.detail.price;
    }else{
        price = goodsDetail.value.detail.seckill_show_price;
    }
    return price;
})

// 会员信息
const memberStore = useMemberStore()
const userInfo = computed(() => memberStore.info)

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

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.defaultSku.seckill_stock) {
            buyNum.value = goodsDetail.value.defaultSku.seckill_stock;
        }
        // 起售大于库存，初始值也应该是零
        if (minBuy.value > goodsDetail.value.defaultSku.seckill_stock) {
            buyNum.value = 0;
            uni.showToast({
                title: '商品库存小于起购数量',
                icon: 'none'
            });
        }
    }, 0)
}

const closeFn = () => {
    useSeckillGoodsDetailStore().setGoodsDetail({isOpenSkuBuy: false});
    goodsSkuPop.value = false
}
const sku_id =ref('')
const goodsDetail = computed(() => {
    let data = cloneDeep(props.goodsDetail);
    // 重组数据结构
    if (Object.keys(data).length) {

        if (!Object.keys(currSpec.value.name).length) currSpec.value.name = data.defaultSku.sku_spec_format.split(",");

        data.spec.forEach((item: any, index: any) => {
            let specName = item.spec_values.split(",");
            item.values = [];
            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.skuList && Object.keys(data.skuList).length) {
            data.skuList.forEach((idItem: any, idIndex: any) => {
                if (idItem.sku_id == currSpec.value.skuId) {
                    idItem.sku_image = idItem.sku_image ? idItem.sku_image : data.goods_cover
                    data.detail = idItem;
                }
            })
        }
        sku_id.value = data.detail.sku_id

    }
    let perPersonLimit = data.detail.sum_num; // 每人限购
    if(data.detail.member_order_num){
        perPersonLimit = perPersonLimit - data.detail.member_order_num; // 每人限购
    }
    if(data.detail.once_num >0 && data.detail.seckill_stock >data.detail.once_num && openType.value != 'buy_now_single'){
        maxBuy.value = perPersonLimit > data.detail.once_num ? data.detail.once_num : perPersonLimit; // 限购
    }else{
        maxBuy.value = data.detail.seckill_stock
    }
    return data;
})

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

// 新增：标识当前规格是否参与秒杀
const isSeckill = ref(true);
const emits = defineEmits(['change'])
const getSkuId = () => {
    let oneSkuId = currSpec.value.skuId
    props.goodsDetail.skuList.forEach((skuItem: any) => {
        if (skuItem.sku_spec_format === currSpec.value.name.toString()) {
            currSpec.value.skuId = skuItem.sku_id;
            // 如果第一次为空，就不触发上级回调，因为数据一致
            if(oneSkuId){
                emits('change', skuItem.sku_id);
            }
            if(skuItem.is_join==1){
                isSeckill.value = true;
            }else{
                isSeckill.value = false;
            }

        }
    });
}


const addNumChange = () => {
    if (minBuy.value && minBuy.value > goodsDetail.value.defaultSku.seckill_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)

//提交
let isPreventConfirm = false
const confirm = () => {
    if (!isSeckill.value) {
        uni.showToast({
            title: '当前规格不参与秒杀',
            icon: 'none'
        });
        return;
    }

    if (!diyFormRef.value.verify()) return;


    if(buyNum.value > maxBuy.value){
        uni.showToast({
            title: '超出最大限购数量',
            icon: 'none'
        });
        return false
    }
    if (buyNum.value < 1){
        uni.showToast({
            title: '购买数量不能小于等于零',
            icon: 'none'
        });
        return;
    }

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

    // 检测是否登录
    if (!userInfo.value) {
        useLogin().setLoginBack({
            url: '/addon/seckill/pages/goods/detail',
            param: {
                sku_id: goodsDetail.value.defaultSku.sku_id,
                time_id: goodsDetail.value.seckill_time.id,
                seckill_id: goodsDetail.value.seckill_id,
            }
        })
        return false
    }

    if(isPreventConfirm) return false;
    isPreventConfirm = true;

    getSeckillGoodsCheckTime({
        goods_id: goodsDetail.value.goods_id,
        num: buyNum.value
    }).then(res => {
        isPreventConfirm = false;
        // 立即购买
        if (openType.value == 'buy_now' || openType.value == 'buy_now_single') {
            let obj = {
                sku_id: goodsDetail.value.defaultSku.sku_id,
                num: buyNum.value,
                seckill_id: '',
                is_seckill: openType.value == 'buy_now' ? 1 : 0,
                time_id: ''
            }
            if(goodsDetail.value.seckill_id){
                obj.seckill_id = goodsDetail.value.seckill_id
                obj.time_id = goodsDetail.value.seckill_time.id
            }
            uni.setStorage({
                key: 'seckill0rderCreateData',
                data: {
                    ...obj,
                    sku_id: sku_id.value
                },
                success: () => {
                    redirect({ url: '/addon/seckill/pages/order/payment' })
                }
            });
        }

        closeFn();
    }).catch(err => {
        isPreventConfirm = false;
    })
}

//预览图片
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>
