<template>
    <BasePage>
        <div class="GoodsDetail">

            <!-- 海报 -->
            <div
                style="position: fixed;left: 0;top: 0; z-index: 0;width: 0px;height: 0px;opacity: 0; overflow: hidden;">
                <div id="bsCard"
                    style="width: 260px; margin: 0 auto; overflow: hidden; border-radius: 10px;height: 450px;">
                    <div class="b_l_w"
                        style="background-color: #f2f1f7;height: max-content;padding-bottom: 15px;font-family: 'PingFang SC';">
                        <div class="b_l_w" style="padding: 10px 20px">
                            <img :src="$file(data.img)" style="width: 100%;height: 220px;" />
                        </div>
                        <div class="b_l"
                            style="background: #daa366;margin-left: 10px;width: 240px;padding: 5px 10px;border-radius: 10px;">
                            <div class="b_l">
                                <img :src="$file($ls.get('member_avatar'))" width="40" height="40"
                                    style="border-radius: 100%; vertical-align: top" />
                            </div>
                            <div class="b_l"
                                style=" line-height: 40px;padding-left: 5px;font-size: 14px;font-weight: bold;color: #fff;">
                                {{ $ls.get('member_nickName')?.length > 8 ? $ls.get('member_nickName').substring(0, 6)
                                    + "..." : $ls.get('member_nickName') }}
                                友情推荐
                            </div>
                        </div>
                        <div class="b_l_w" style="padding: 5px 10px">
                            <div class="b_l"
                                style="width: 120px;font-size: 12px;overflow: hidden;text-overflow: ellipsis;display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 2;line-clamp: 2;">
                                {{ data.name }}
                            </div>
                            <div class="b_l" style="height: 30px;width: 1px;background: #d3d3d3;margin: 5px 7px;"></div>
                            <div class="b_r" style="width: 95px; line-height: 40px; font-size: 12px">
                                价格 <span style="color: #fd3c2b">￥{{ data.saleprice }}</span>
                            </div>
                        </div>
                        <div class="b_l_w" style="padding: 0 10px">
                            <div class="b_r" style="margin-top: 0px; margin-right: 10px">
                                <img :src="$file($ls.get('shareLogo'))" width="100" />
                            </div>
                            <div class="b_l"
                                style="width: 78px;text-align: center;padding-top: 5px;height: 95px;font-size: 12px;">
                                <vue-qr :text="shareLink" backgroundColor="rgb(255,255,255,0)" style="width: 100%;"
                                    colorLight="rgb(255,255,255,0)"></vue-qr>
                                长按扫码购买
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <van-popup v-model:show="showShareImg" style="width: 66.667vw;border-radius: 3.333vw;">
                <img class="w" :src="ShareImg">
            </van-popup>

            <van-swipe class="banner" :autoplay="3000" indicator-color="white">
                <van-swipe-item v-for="item in bannerImages"><img class="w" :src="$file(item)"></van-swipe-item>
                <template #indicator="{ active, total }">
                    <div class="custom-indicator">{{ active + 1 }}/{{ total }}</div>
                </template>
            </van-swipe>

            <div class="mx-auto">
                <div class="top">
                    <div class="c">
                        <div class="name">
                            {{ data.name }}
                        </div>
                        <div class="remark">
                            {{ data.description }}
                        </div>
                        <div class="price" v-if="data.saleprice">
                            <b><span>￥</span>{{ data.saleprice?.toFixed(2) }}</b>
                            <s>￥{{ data.originalprice?.toFixed(2) }}</s>
                            <p>已售 {{ data.salenums }}</p>
                        </div>
                        <!-- <div class="give">
                            <div>
                                <img src="/img/coin.png">
                                果实可抵￥{{ $trunc(data.saleprice * data.FruitRate / 100, 2).toFixed(2) }}
                            </div>
                        </div> -->
                        <div class="label">
                            <span><img src="/img/GroupShopDetail-i2.png">品质保障</span>
                            <span><img src="/img/GroupShopDetail-i2.png">正品包邮</span>
                            <span><img src="/img/GroupShopDetail-i2.png">售后无忧</span>
                        </div>
                    </div>
                </div>

                <div class="_sku" v-if="data.ForbiddenRule && data.ForbiddenRule.length > 0">
                    <van-cell icon="/img/notShip-i1.png" is-link @click="showNotShip = true">
                        <template #title>
                            不支持发货区域：
                            <span class="span" v-for="list in data.ForbiddenRule">
                                <span v-for="(item, index) in list.Region">
                                    {{ item.RegionName }}<font v-if="index < list.Region.length - 1">；</font>
                                </span>
                            </span>
                        </template>
                    </van-cell>
                </div>

                <div class="_sku">
                    <van-cell icon="bars" @click="showSpecs = true" :title="selectedSku" is-link />
                </div>

                <div class="_video" v-if="videoList.length > 0" @click="showVideoList = true">
                    <img src="/img/GoodsDetail-video.png">
                    <p>视频介绍</p>
                </div>

                <div class="html">
                    <div class="title">
                        <div class="t">
                            <img src="/img/GroupShopDetail-tit-i3.png">
                            <b>产品详情</b>
                        </div>
                    </div>
                    <div class="w100" v-html="data.contents"></div>
                </div>

            </div>

            <van-share-sheet v-model:show="showShare" title="立即分享给好友" v-bind:options="options" @select="onSelect">
            </van-share-sheet>

            <van-popup v-model:show="showTip" style="background: transparent;">
                <img src="/img/fenxiangtishi2.png" class="w" @click="showTip = false" style="height: 100vh;">
            </van-popup>

            <van-action-bar class="b_l_w" safe-area-inset-bottom placeholder>
                <van-action-bar-icon @click="$goService()" icon="/img/GroupShopDetail-footer-i1.png" text="客服" />
                <van-action-bar-icon @click="beforeShare" icon="/img/GroupShopDetail-footer-i2.png" text="分享" />
                <van-action-bar-button @click="showSpecs = true" color="#d0241c" text="立即购买" />
            </van-action-bar>

            <van-popup v-model:show="showSpecs" position="bottom" closeable round>
                <div class="showSpecs">
                    <div class="_product">
                        <img :src="$file(tempSku.img || data.img)">
                        <div class="_c">
                            <div class="price">
                                <span>￥</span>{{ (tempSku.saleprice * tempSku.Qty).toFixed(2) }}
                            </div>

                            <div class="d">
                                <div class="selected box box-pack-between">
                                    已选:{{ tempSku.skuname }}
                                    <span>库存:{{ tempSku.saleleft }}</Span>
                                </div>
                            </div>

                        </div>
                    </div>


                    <div v-for="(spec, index) in specSelect">
                        <div class="specs">
                            {{ spec.name }}
                        </div>

                        <div class="label">
                            <a v-for="(child, childIndex) in spec.children"
                                :class="selectedSpecs[spec.name] === child.name ? 'a' : ''"
                                @click="selectSpec(spec.name, child.name)">
                                {{ child.name }}
                            </a>
                        </div>
                    </div>

                    <div class="number" v-if="data.SpuArea != 'gift'">
                        购买数量
                        <van-stepper v-model="tempSku.Qty" min="1" max="99" input-width="8vw" allow-empty="true"
                            theme="round" button-size="5vw" disable-input />
                    </div>

                    <van-action-bar class="b_l_w" safe-area-inset-bottom placeholder>
                        <van-action-bar-button @click="submit" color="linear-gradient(to right, #ff6034, #ee0a24)"
                            text="立即购买" />
                    </van-action-bar>
                </div>
            </van-popup>

            <van-popup v-model:show="showNotShip" class="showNotShip">
                <img src="/img/notShip-i2.png">
                <div class="c">
                    <div class="text">
                        不支持发货区域：
                        <span class="span" v-for="list in data.ForbiddenRule">
                            <span v-for="(item, index) in list.Region">
                                {{ item.RegionName }}<font v-if="index < list.Region.length - 1">;</font>
                            </span>
                        </span>
                    </div>
                    <a class="btn" @click="showNotShip = false">
                        好的，知道了
                    </a>
                </div>
            </van-popup>

            <van-action-sheet v-model:show="showVideoList" class="popup-GoodsDetail-videoList" safe-area-inset-bottom
                title="视频介绍列表" closeable style="padding: 0 0 0; min-height: 60%">
                <van-cell v-for="item in videoList" :icon="$file(item.Poster)" center :title="item.Name"
                    :label="formatTime(item.Duration)" @click="video = item; showVideo = true" />
            </van-action-sheet>

            <van-popup v-model:show="showVideo" closeable @click-overlay="video = {}" @click-close-icon="video = {}">
                <video v-if="video.Video" :poster="$file(video.Poster)" controls="" style="width: 100%;height: auto;">
                    <source :src="$file(video.Video)" type="video/mp4" />
                </video>
            </van-popup>

        </div>
    </BasePage>
</template>

<script>
export default {
    name: 'GoodsDetail',
    emits: ['updateShare'],
    mounted() {
        this.init();
    },
    data() {
        return {
            data: {
                id: 'static_goods_001',
                name: '有机红富士苹果',
                description: '源自新疆阿克苏，天然有机种植，皮薄肉脆，汁多味甜',
                originalprice: 98.00,
                saleprice: 68.00,
                salenums: 1520,
                img: '/img/goods-1.png',
                imgs: '/img/goods-1.png;/img/goods-2.png',
                contents: '<p style="text-align:center;"><img src="/img/goods-1.png" width="100%"/></p><p style="text-align:center;"><img src="/img/goods-2.png" width="100%"/></p><p style="text-align:center;color:#666;">有机红富士苹果产自新疆阿克苏地区，采用天然有机种植方式，不使用化学农药和化肥。</p><p style="text-align:center;color:#666;">特点：皮薄肉脆、汁多味甜、营养丰富</p>',
                specSelect: [
                    {
                        id: 1,
                        name: '规格',
                        specids: '3',
                        children: [
                            { id: 3, name: '1kg', specids: null, children: [] },
                            { id: 4, name: '2kg', specids: null, children: [] },
                            { id: 5, name: '5kg', specids: null, children: [] }
                        ]
                    }
                ],
                specCombinations: [
                    { skuid: '3', skuname: '1kg', img: '/img/goods-1.png', originalprice: 68.00, saleprice: 68.00, saleleft: 100, ismain: true },
                    { skuid: '4', skuname: '2kg', img: '/img/goods-1.png', originalprice: 128.00, saleprice: 128.00, saleleft: 80, ismain: false },
                    { skuid: '5', skuname: '5kg', img: '/img/goods-1.png', originalprice: 298.00, saleprice: 298.00, saleleft: 50, ismain: false }
                ],
                ForbiddenRule: []
            },
            specSelect: [],
            specCombinations: [],
            tempSku: {},
            showSpecs: false,
            selectedSku: '请选择规格分类',
            selectedSpecs: {},
            showNotShip: false,
            videoList: [],
            video: {},
            showVideoList: false,
            showVideo: false,
            showShare: false,
            showTip: false,
            showShareImg: false,
            ShareImg: '',
            options: [
                { name: "分享海报", icon: "/img/ff3.png" }
            ],
            shareLink: location.origin,
            cartLoading: false
        }
    },
    computed: {
        bannerImages() {
            if (!this.data.imgs) return [this.data.img];
            const imgs = this.data.imgs.split(';').filter(Boolean);
            return imgs.length > 0 ? imgs : [this.data.img];
        }
    },
    methods: {
        init() {
            this.$get(`/v1/client/EProsClient/${this.$route.query.id}`).then(res => {
                this.data = res.data;
                this.specSelect = this.data.specSelect || [];
                this.specCombinations = this.data.specCombinations || [];
                this.shareLink = `${location.origin}/GoodsDetail?id=${this.data.id}`;
                this.$emit('updateShare', { title: this.data.name, imageUrl: this.data.img, link: this.shareLink });
                this.initDefaultSku();
            });
        },
        initDefaultSku() {
            const mainSku = this.specCombinations.find(s => s.ismain) || this.specCombinations[0];
            if (mainSku) {
                this.tempSku = { ...mainSku, Qty: 1 };
                this.selectedSku = "已选:" + mainSku.skuname;
            }
        },
        selectSpec(specName, specValue) {
            this.selectedSpecs[specName] = specValue;
            this.refreshSku();
        },
        refreshSku() {
            const specKeys = Object.keys(this.selectedSpecs);
            if (specKeys.length === 0) return;

            let matchedSku = this.specCombinations.find(combo => {
                return specKeys.every(key => {
                    const spec = this.specSelect.find(s => s.name === key);
                    if (!spec) return false;
                    const specValue = this.selectedSpecs[key];
                    return combo.skuname === specValue;
                });
            });

            if (matchedSku) {
                this.tempSku = { ...matchedSku, Qty: this.tempSku.Qty || 1 };
                this.selectedSku = "已选:" + matchedSku.skuname;
            }
        },
        onSelect(option, index) {
            this.showShare = false;
            if (option.name === "分享海报") {
                this.showShareImg = true;
            } else if (option.name == "复制链接") {
                this.$copyText(location.href);
                this.$showToast({ type: "success", message: "复制成功" });
            } else if (option.name == "分享好友") {
                this.showTip = true;
            }
        },
        submit() {
            if (this.tempSku.saleleft < 1) {
                this.$showFailToast("该规格库存不足，无法购买");
                return;
            }
            this.$navigate(`/TradeConfirm?id=${this.data.id}&skuid=${this.tempSku.skuid}`);
        },
        beforeShare() {
            this.showShare = true;
        },
        formatTime(seconds) {
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = seconds % 60;
            return `${this.pad(hours)}:${this.pad(minutes)}:${this.pad(secs)}`;
        },
        pad(num) {
            return num.toString().padStart(2, '0');
        }
    }
}
</script>
