<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.id" @touchmove.prevent.stop>
                    <view class="flex px-[32rpx]">
                        <view class="rounded-[var(--goods-rounded-big)] overflow-hidden w-[180rpx] h-[180rpx]">
                            <u--image width="180rpx" height="180rpx" :src="img(goodsDetail.productImage)"
                                @click="imgListPreview(goodsDetail.productImage)" 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>
                                </view>
                                <view class="text-[26rpx] leading-[32rpx] text-[var(--text-color-light6)] mt-[12rpx]">
                                    库存{{ goodsDetail.allStock
                                    }}{{ goodsDetail.goods.unit }}</view>
                            </view>
                        </view>
                    </view>

                    <scroll-view class="h-[500rpx] px-[32rpx] box-border mb-[60rpx]" scroll-y="true">
                        <view class="flex justify-between items-center my-[20rpx]">
                            <view class="text-[28rpx]">购买数量</view>
                            <text class="ml-[20rpx] mr-[auto] text-[24rpx] text-[var(--primary-color)]">({{
                                goodsDetail.minOrderQuantity
                                }}{{ goodsDetail.goods.unit }}起售)</text>
                            <u-number-box :min="goodsDetail.minOrderQuantity" :max="goodsDetail.allStock" 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 <= goodsDetail.minOrderQuantity,
                                            }"></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 >= goodsDetail.allStock || buyNum == 0,
                                            }"></text>
                                    </view>
                                </template>
                            </u-number-box>
                        </view>
                    </scroll-view>
                    <view class="px-[20rpx]">
                        <!-- #ifndef MP -->
                        <button v-if="goodsDetail.allStock > 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.allStock > 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 hover-class="none" v-else
                            class="!h-[80rpx] leading-[80rpx] text-[26rpx] font-500 text-[#fff] bg-[#ccc] rounded-[50rpx]">
                            已售罄
                        </button>
                    </view>
                </view>
            </u-popup>
        </u-overlay>
    </view>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { img, getToken } from "@/utils/common";
import { useLogin } from "@/hooks/useLogin";
import { cloneDeep } from "lodash-es";
import useGoodsDetailStore from "@/addon/shop/stores/goodsDetail";
import { addCart } from "@/addon/shop/api/cart";

const props = defineProps(["goodsDetail"]);
const goodsSkuPop = ref(false);
const callback: any = ref(null);
const openType = ref("");
const buyNum = ref<any>(1);

// 商品价格
const goodsPrice = computed(() => {
    let price = "0.00";
    price = goodsDetail.value.memberPrice || "0.00";
    return price;
});
const open = (type = "", fn = "") => {
    openType.value = type;
    goodsSkuPop.value = true;
    callback.value = fn;
};

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

const goodsSkuBlurFn = () => {
    setTimeout(() => {
        buyNum.value = parseInt(buyNum.value);
        if (!buyNum.value || buyNum.value <= goodsDetail.value.minOrderQuantity) {
            buyNum.value = goodsDetail.value.minOrderQuantity || 1;
        }
        if (buyNum.value >= goodsDetail.value.allStock) {
            buyNum.value = goodsDetail.value.allStock;
        }

        // 起售大于库存，初始值也应该是零
        if (goodsDetail.value.minOrderQuantity > goodsDetail.value.allStock) {
            buyNum.value = 0;
            uni.showToast({
                title: "商品库存小于起购数量",
                icon: "none",
            });
        }
    }, 0);
};

const closeFn = () => {
    goodsSkuPop.value = false;
    useGoodsDetailStore().setGoodsDetail({ isOpenSkuBuy: false });
};

const goodsDetail = computed(() => {
    let data = cloneDeep(props.goodsDetail);
    return data;
});

const emits = defineEmits(["change"]);

const addNumChange = () => {
    if (
        goodsDetail.value.minOrderQuantity &&
        goodsDetail.value.minOrderQuantity > goodsDetail.value.allStock
    ) {
        uni.showToast({ title: "商品库存小于起购数量", icon: "none" });
        return;
    }
    if (goodsDetail.value.goods.is_limit) {
        let tips = `该商品单次限购${goodsDetail.value.goods.max_buy}件`;
        if (goodsDetail.value.goods.limit_type != 1) {
            //单次限购
            tips = `该商品每人限购${goodsDetail.value.goods.max_buy}件`;
            if (
                goodsDetail.value.goods.max_buy -
                goodsDetail.value.allStockgoodsDetail.value.allStock
            ) {
                tips += `,已购${goodsDetail.value.goods.max_buy -
                    goodsDetail.value.allStockgoodsDetail.value.allStock
                    }件`;
            }
        }
        if (buyNum.value >= goodsDetail.value.allStockgoodsDetail.value.allStock) {
            uni.showToast({ title: tips, icon: "none" });
        }
    }
};

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

//提交
const confirm = () => {
    if (buyNum.value < 1) return;

    // 检测是否登录
    if (!getToken()) {
        useLogin().setLoginBack({
            url: "/addon/shop/pages/goods/detail",
            param: {
                goodsId: goodsDetail.value.id,
            },
        });
        return false;
    }

    // 加入购物车
    addCart({
        productId: goodsDetail.value.id,
        productNum: buyNum.value
    }).then((res) => {
        uni.showToast({
            title: "加入购物车成功",
            icon: "none",
        });
        closeFn();
    }).catch((res) => {});
};

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