<template>
	<view class="pd-b-px-55">
		<van-sticky>
			<view class="top-bar top_bar justify-center bg-white sh">
				<van-icon class="top-left" name="arrow-left" @tap="goBack" />
				<van-tabs class="top_tab" v-model:active="state.tab.active" @click-tab="scrollTo" animated>
					<van-tab v-for="item in state.tab.list" :title="item.name" />
				</van-tabs>
				<van-icon v-if="!isAPP" class="top-right" name="share-o" @tap="tapchange" />
			</view>
		</van-sticky>
		<van-swipe lazy-render id="good" class="banner_top"
			     :class="{ 'video': video, 'video_black': video && state.banner.activeTop == 0 }" ref="topBanner"
			     @change="onTopBannerChange">
			<van-swipe-item v-if="video">
				<video style="height: 100%;width: 100vw;" objet-fit="contain" :poster="skuData?.mainImg || ''"
					 :src="video"
					 controls :enable-progress-gesture="false" />
			</van-swipe-item>
			<van-swipe-item v-if="skuData?.mainImg" @tap="onImagePreview(skuData.mainImg)" class="good_img">
				<van-image height="100%" width="100vw" fit="contain"
					     loading-icon="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/default1.png"
					     icon-size="100vw"
					     :src="skuData.mainImg" />
				<!--详情页活动角标-->
				<div class="sign" v-if="skuData.subScriptImgUrl">
					<img :src="skuData.subScriptImgUrl" alt="" />
					<div class="discount" style="color: rgba(247, 103, 67, 1)">{{skuData.discount}}</div>
				</div>
				<van-image v-if="zoneIcon[0]" class="zone_icon" style="left: 10rpx" width="60rpx" :src="zoneIcon[0]" />
				<van-image v-if="zoneIcon[1]" class="zone_icon" style="left: 80rpx" width="60rpx"
					     :src="zoneIcon[1]" />
				<!--<span v-if="skuData.coTip==1" class="zone_icon host_tip" style="left: 90rpx;">热销</span>-->
			</van-swipe-item>
			<template v-if="video" #indicator="{ active, total }">
				<view class="justify-center">
					<view class="flex">
						<view class="indicator" :class="{ 'active': active == 0 }"
							@tap="onIndicatorClick(0)">
							<van-icon name="play" />
							视频
						</view>
						<view class="indicator" :class="{ 'active': active == 1 }"
							@tap="onIndicatorClick(1)">图片
						</view>
					</view>
				</view>
			</template>
		</van-swipe>
		<van-skeleton class="bg-white pd-v-20" title :row="2" :loading="!state.inited">
			<template v-if="state.switch.newView">
				<template v-if="skuData">
					<view class="bg-white pd-20">
						<template v-if="skuData.salePrice !== null">
							<view class="text-orange text-ss">优惠价￥
								<text class="text-bold text-xl">{{ skuData.salePrice }}</text>
							</view>
							<view class="text-gray text-ss">零售价￥{{ skuData.productPrice }}</view>
						</template>
						<template v-else>
							<view class="text-orange text-ss">零售价￥
								<text class="text-bold text-xl">{{ skuData.productPrice }}</text>
							</view>
						</template>
						<view class="flex justify-middle">
							<van-image v-if="zoneIcon" class="pd-v-10" width="60rpx" :src="zoneIcon[0]" />
							<text v-if="state.switch.stock" class="text-ss text-yellow pd-l-50">
								库存：{{ skuData.stock }}
							</text>
							<text v-if="state.switch.delivery" class="text-ss text-yellow pd-l-50">
								交货期：{{ Enum.get("delivery", state.data.deliveryTime) }}
							</text>
						</view>
						<view class="text-l text-bold text-black">{{ skuData.title }}</view>
					</view>
					<van-cell-group class="mg-v-25" inset>
						<van-cell v-if="state.switch.changeGood" is-link>
							<template #title>
								<text class="text-gray">已选</text>
								<text class="text-black pd-l-20">{{ skuData.model || "未选择" }}</text>
							</template>
							<template #right-icon>
								<van-icon class="justify-middle" name="ellipsis" />
							</template>
						</van-cell>
						<van-cell v-if="state.switch.size" is-link
							    @tap="goto(state.skuId ? `/pages/good/size?skuId=` + state.skuId : undefined)">
							<template #title>
								<text class="text-gray">规格</text>
								<text class="text-black pd-l-20">
									{{
									`W${skuData.specWidth}*H${skuData.specHeight}*D${skuData.specLength}`
									}}
								</text>
							</template>
							<template #right-icon>
								<van-icon class="justify-middle" name="ellipsis" />
							</template>
						</van-cell>
						<van-cell :is-link="!!state.skuId" @tap="onSkuInfo">
							<template #title>
								<view class="justify-middle">
									<view class="text-gray">参数</view>
									<view class="text-black pd-l-20 ellipsis block"
										style="width: 510rpx">{{ skuInfo }}
									</view>
								</view>
							</template>
							<template #right-icon>
								<van-icon class="justify-middle" name="ellipsis" />
							</template>
						</van-cell>
					</van-cell-group>
				</template>
				<van-cell-group v-if="state.brand" class="mg-v-25" inset>
					<van-cell is-link>
						<template #title>
							<view class="justify-middle">
								<van-image class="pd-r-15" width="100rpx" round fit="contain"
									     :src="state.brand.brandLogo" />
								<view>
									<view class="justify-middle text-m text-bold text-black">
										<van-image class="pd-r-10" width="14px" height="15px"
											     v-if="state.data.etaoProductVip"
											     src="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/vip_icon.png?time=1" />
										{{ state.brand.brandName }}
									</view>
									<view class="text-gray text-ss pd-t-10">在售商品{{
										state.brand.productCount }}件
									</view>
								</view>
							</view>
						</template>
						<template #right-icon>
							<view class="justify-middle text-orange text-ss">
								进入品牌
								<van-icon name="arrow" />
							</view>
						</template>
					</van-cell>
					<!-- 这个是旧版本的规格选择 -->
					<van-cell v-if="state.data.skuJson && state.data.skuJson.length > 1">
						<template #title>
							<view class="flex scrollx_container">
								<template v-for="item in state.data.skuJson">
									<view v-if="item.skuId != state.skuId" class="text-center pd-r-40"
										@tap="goto(`/pages/good/detail?skuId=${item.skuId}&spuId=${state.data.spuId}`)">
										<van-image height="18vw" width="18vw" fit="cover" lazy-load
											     loading-icon="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/default1.png"
											     icon-size="18vw"
											     :src="item.mainImg" />
										<view class="text-orange text-ss mg-l-10-m mg-t-10-m">
											￥{{ item.salePrice !== null ? item.salePrice :
											item.productPrice }}
										</view>
									</view>
								</template>
							</view>
						</template>
					</van-cell>
				</van-cell-group>
			</template>
			<template v-else-if="skuData">
				<view class="bg-white pd-px-10">
					<view class="text-l  text-black">{{ skuData.title }}</view>
					<view class="flex" v-if="skuData.salePrice">
						<view>
							<view class="text-blue">生产周期：{{ Enum.get("delivery", state.data.deliveryTime)
								}}
							</view>
							<view class="text-gray line-through" v-if="skuData.actPrice">优惠价：￥{{
								skuData.salePrice }}
							</view>
							<view class="text-orange" v-else>优惠价：￥{{ skuData.salePrice }}</view>
							<view class="text-orange" v-if="skuData.actPrice">活动价：￥{{ skuData.actPrice
								}}
							</view>
						</view>
						<view class="pd-l-30">
							<view class="pd-l-30">工厂库存：{{ skuData.stock }}件</view>
							<view class="pd-l-30 text-gray " v-if="skuData.actPrice">零售价：￥{{
								skuData.productPrice }}
							</view>
							<view class="pd-l-30 text-gray line-through" v-else>零售价：￥{{
								skuData.productPrice }}
							</view>
						</view>
					</view>
					<view class="flex" v-else>
						<view>
							<view>生产周期：{{ Enum.get("delivery", state.data.deliveryTime) }}</view>
							<view v-if="skuData.actPrice">
								<view class="text-gray line-through">零售价：￥{{ skuData.productPrice }}
								</view>
								<view class="text-orange">活动价：￥{{ skuData.actPrice }}</view>
							</view>
							<view v-else>
								<view class="text-orange">零售价：￥{{ skuData.productPrice }}</view>
							</view>
						</view>
						<view class="pd-l-30">
							<view class="pd-l-30">工厂库存：{{ state.data.stock }}件</view>
						</view>
					</view>
				</view>
				<van-cell-group v-if="state.brand" class="mg-v-px-10">
					<van-cell>
						<template #title>
							<view class="justify-middle">
								<van-image class="br" width="100px" height="70px" fit="cover"
									     :src="state.brand.brandLogo"
									     loading-icon="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/default1.png"
									     icon-size="70px" />
								<view class="pd-l-20">
									<view class="justify-middle text-m text-bold text-black">
										<van-image class="pd-r-10" width="14px" height="15px"
											     fit="contain" v-if="state.data.etaoProductVip"
											     src="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/vip_icon.png?time=1" />
										{{ state.brand.brandName }}
									</view>
									<view class="text-gray text-ss">商品数：{{ state.brand.productCount
										}}
									</view>
									<view class="flex">
										<van-button plain class="detail_btn" size="mini"
												@tap="goBrand(state.brand.brandId)">查看品牌
										</van-button>
										<van-button plain class="detail_btn" size="mini"
												:type="state.brand.isFav ? 'primary' : 'default'"
												style="margin-left: 20rpx"
												@tap="check(onCollectBrand)">
											{{ state.brand.isFav ? "已收藏品牌" : "收藏品牌" }}
										</van-button>
									</view>
								</view>
							</view>
						</template>
					</van-cell>
				</van-cell-group>
				<van-collapse class="no-padding mg-b-25" v-model="state.collapse.openList">
					<van-collapse-item name="1">
						<template #title>
							<view class="good_anchor">产品参数</view>
						</template>
						<van-cell-group>
							<van-cell v-if="skuData.lightSourceCount || skuData.lightSourceCount == 0">
								<template #title>
									<text class="inline-block skuInfo_label">光源：</text>
									<text class="text-gray">{{ skuData.lightSourceCount }}</text>
								</template>
							</van-cell>
							<van-cell v-for="item in sizeList" is-link
								    @tap="goto(state.skuId ? `/pages/good/size?skuId=` + state.skuId : undefined)">
								<template #title>
									<text class="inline-block skuInfo_label">{{ item.name }}度(mm)：
									</text>
									<text class="text-gray">{{ item.value }}</text>
								</template>
								<template #right-icon>
									<van-icon class="justify-middle" name="ellipsis" />
								</template>
							</van-cell>
							<template v-for="item in state.data.labelJson">
								<van-cell v-if="item.labelParams.length > 0">
									<template #title>
										<view class="flex">
											<view class="skuInfo_label">{{ item.name }}：</view>
											<view class="skuInfo_info text-gray">
												{{ item.labelParams.map((label: any) =>
												label.name).join(",") }}
											</view>
										</view>
									</template>
								</van-cell>
							</template>
						</van-cell-group>
					</van-collapse-item>
				</van-collapse>
			</template>
			<view id="detail">
				<van-divider v-if="state.switch.newView" :style="{ borderColor: '#8c8c8c', padding: '0 30vw' }">
					商品详情
				</van-divider>
				<view v-else class="good_anchor">产品详情</view>
			</view>
			<!-- 下面的图片不能用lazy，计算不出高度 -->
			<van-image v-for="item in detailImgs"
				     loading-icon="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/default1.png"
				     icon-size="100vw" width="100vw" :src="item" />
			<van-image v-if="skuData.salePrice" icon-size="100vw" width="100vw"
				     src="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/price_tip0.png" />
			<van-image v-else icon-size="100vw" width="100vw"
				     src="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/price_tip1.png" />
			<template v-if="!state.switch.newView">
				<view id="otherSku" class="good_anchor">同系列推荐</view>
				<van-list v-if="state.data.skuJson" class="mg-t-15" :finished="true" finished-text="已经到底了哦~">
					<van-grid :center="false" :column-num="2" :gutter="7">
						<template v-for="item in state.data.skuJson">
							<van-grid-item v-if="item.skuId != state.skuId" class="text-left"
									   @tap="goto(`/pages/good/detail?skuId=${item.skuId}&spuId=${state.data.spuId}`)">
								<van-image class="self_center" width="30vw" height="30vw" lazy-load
									     loading-icon="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/default1.png"
									     icon-size="30vw"
									     :src="item.mainImg" />
								<view class="mg-t-30-m">
									<van-image v-if="zoneIcon" width="60rpx" height="32rpx"
										     :src="zoneIcon[0]" />
									<van-image v-if="item.isVideoIcon" class="mg-l-5" width="32rpx"
										     height="32rpx"
										     src="/static/img/play.png" />
								</view>
								<text class="text-s ellipsis line_over2 pd-t-10"
									style="width: 320rpx;height: 32px;margin-bottom:6px">
									{{ item.title }}
								</text>
								<text class="text-ss"
									v-if="item.specHeight || item.specLength || item.specWidth">
									{{ `W(宽):${item.specWidth} H(高):${item.specHeight}
									D(深):${item.specLength}` }}
								</text>
								<text class="text-gray text-ss"></text>
								<template v-if="item.salePrice !== null">
									<view class="text-gray text-ss line-through">零售价￥{{
										item.productPrice }}
									</view>
									<view class="text-orange text-ss">优惠价￥
										<text class="text-bold text-l">{{ item.salePrice }}</text>
									</view>
								</template>
								<template v-else>
									<view class="text-orange text-ss">零售价￥
										<text class="text-bold text-l">{{ item.productPrice }}
										</text>
									</view>
								</template>
							</van-grid-item>
						</template>
					</van-grid>
				</van-list>
			</template>
		</van-skeleton>
		<van-action-bar class="sh-t">
			<van-action-bar-icon v-if="state.skuId" icon="down" text="下载"
						   @tap="goto(`/pages/good/download?skuId=` + state.skuId)" />
			<van-action-bar-icon v-if="state.brand" icon="chat-o" text="客服" @tap="goto(`/pages/good/contact`)" />
			<van-action-bar-icon :color="state.data.isFav ? '#f60' : ''"
						   :icon="state.data.isFav ? 'like' : 'like-o'"
						   :text="state.data.isFav ? '已收藏' : '收藏'" @tap="check(onCollect)" />
			<van-action-bar-icon icon="cart-o" text="购物车" @tap="goto('/?index=2')" :badge="state.badge || ''" />
			<van-action-bar-button :disabled="!skuData" type="warning" text="加入购物车" @tap="check(cartAdd)" />
		</van-action-bar>
		<van-popup v-model:show="state.popup.skuInfo.show" round position="bottom" teleport="#app" closeable>
			<view class="text-bold text-center pd-v-30">产品参数</view>
			<van-cell-group>
				<van-cell v-if="skuData.lightSourceCount || skuData.lightSourceCount == 0">
					<template #title>
						<text class="inline-block skuInfo_label">光源：</text>
						<text class="text-gray">{{ skuData.lightSourceCount }}</text>
					</template>
				</van-cell>
				<template v-for="item in state.data.labelJson">
					<van-cell v-if="item.labelParams.length > 0">
						<template #title>
							<view class="flex">
								<view class="skuInfo_label">{{ item.name }}：</view>
								<view class="skuInfo_info text-gray">
									{{ item.labelParams.map((label: any) => label.name).join(",") }}
								</view>
							</view>
						</template>
					</van-cell>
				</template>
			</van-cell-group>
		</van-popup>
		<to-top :showNav="true" />
		<van-overlay v-if="state.wx.isWX" :show="state.share.show" @tap="state.share.show = false"
				 style="z-index: 7">
			<van-image class="pd-40" style="float: right" width="120px" src="/static/img/share_tip.png" />
		</van-overlay>
		<van-share-sheet v-else v-model:show="state.share.show" title="立即分享" :options="state.share.options"
				     @select="onShareSelect" />
		<van-popup v-model:show="state.share.showQRCode">
			<view class="bg-white text-center pd-40" style="width: 300px">
				<view class="text-bold">{{ skuData.title }}</view>
				<van-image class="pd-v-20" width="250px" height="250px" :src="state.share.qrcode"
					     loading-icon="https://img.edsmall.com/ROOT/ETao/fenxiao/h5/default1.png"
					     icon-size="250px" />
				<view class="text-left mg-l-px-10">
					1.打开微信，点击扫一扫即可分享到朋友圈<br />
					2.长按进行保存<br />
					3.截屏保存该页面进行分享<br />
				</view>
			</view>
		</van-popup>
	</view>
</template>

<script setup lang="ts">
    import {Enum, PageUtils, WXUtils} from '@/utils/utils'
    import {computed, nextTick, onBeforeMount, reactive, ref, onUnmounted,onMounted} from 'vue';
    import {onPageScroll, onShow, onHide} from '@dcloudio/uni-app'
    import {SwipeInstance, Toast} from 'vant';
    import toTop from '@/components/tool/toTop.vue';
    import api from '@/api';
    import {ImagePreview} from 'vant';
    import {Dialog} from "vant";
    // @ts-ignore
    import QRCode from 'qrcode'

    const state = reactive({
        skuId: '',
        spuId: '',
        tab: {
            active: 0,
            list: [
                {name: '商品', target: '#good', top: 0},
                {name: '详情', target: '#detail', top: 0},
                {name: '推荐', target: '#otherSku', top: 0},
            ]
        },
        banner: {
            activeTop: 0
        },
        data: {} as any,
        brand: undefined as any,
        popup: {
            skuInfo: {
                show: false
            }
        },
        loading: {
            cartAdd: false,
            productFav: false,
            brandFav: false,
            qrcode: false
        },
        collapse: {
            openList: ['1']
        },
        share: {
            show: false,
            options: [{name: '微信', icon: 'wechat'}],
            showQRCode: false,
            qrcode: ''
        },
        wx: {
            isWX: false,
            inited: false
        },
        badge: 0,
        switch: {
            changeGood: false, // 修改规格
            // ----旧----
            stock: true, // 库存
            delivery: true, // 交货期
            size: true, // 规格
            // ----新UI----
            newView: false,
        },
        test: false, // jssdk-debug
        inited: false
    })
    const topBanner = ref<SwipeInstance>();
    const video = computed(() => {
        return state.data?.imgsJson?.video
    })
    const zoneIcon = computed(() => {
        if (!state.data?.dailyIcons || state.data.dailyIcons.length == 0) return ''
        return state.data?.dailyIcons
    })
    const detailImgs = computed(() => {
        if (!state.data?.imgsJson?.detailImgs) return []
        return state.data?.imgsJson?.detailImgs.split(',')
    })
    const skuData = computed(() => {
        if (!state.data?.skuJson) return ''
        const item = state.data.skuJson.find((item: any) => item.skuId == state.skuId)
        return item
    })
    const sizeList = computed(() => {
        if (!skuData.value) return []
        return [
            {name: '宽', value: skuData.value.specWidth},
            {name: '高', value: skuData.value.specHeight},
            {name: '深', value: skuData.value.specLength},
        ]
    })
    const skuInfo = computed(() => {
        let info = ''
        if (skuData.value) {
            const {lightSourceCount}: any = skuData.value
            if (lightSourceCount || lightSourceCount === 0) info += '光源:' + lightSourceCount + ';'
        }
        if (state.data.labelJson) {
            state.data.labelJson.forEach((item: any) => {
                if (item.labelParams.length > 0) {
                    info += item.name + ':'
                    info += item.labelParams.map((label: any) => label.name).join(',')
                    info += ';'
                }
            })
        }
        return info
    })

    onBeforeMount(() => {
        let subdomain = getUrl(window.location.href)
        if (subdomain.name) {
            uni.setStorageSync('subdomain', subdomain.name)
        }
        const query: any = PageUtils.getCurQuery()
        state.skuId = query.skuId
        state.spuId = query.spuId
        state.test = (query.test == 88888888)
        if (!state.skuId) {
            uni.navigateTo({
                url: '/pages/index'
            })
            return
        }
        getProduct()
        getIndexEtaomall()
        // initWX()
    })

    onShow(() => {
        const {token} = uni.getStorageSync("user") || {};
        if (token) {
            cartCount()
        }
        console.log();
        if (state.skuId) {
            getProduct()
        }
    })
    const isAPP = ref(false)
    onMounted(() => {
        window._wx.miniProgram.getEnv((res) => {
            if (res.miniprogram) {
                isAPP.value=true
            } else {
                isAPP.value=false
            }
        });
    });
    onUnmounted(() => {
        window._wx.miniProgram.postMessage({data: {}});
    })
    onHide(() => {
        window._wx.miniProgram.postMessage({data: {}});
    });
    onPageScroll(e => {
        let active = 0
        state.tab.list.forEach((item, index) => {
            if (item.top < e.scrollTop + 50) active = index
        })
        state.tab.active = active
    })

    function scrollTo(e: any) {
        uni.pageScrollTo({
            scrollTop: state.tab.list[e.name].top,
            complete: function () {
                setTimeout(() => {
                    state.tab.active = e.name
                }, 600)
            }
        });
    }

    function onTopBannerChange(acitve: number) {
        state.banner.activeTop = acitve
    }

    function onIndicatorClick(active: number) {
        topBanner.value?.swipeTo(active)
    }

    function getProduct() {
        api.getProduct(state.skuId, {domain: uni.getStorageSync('subdomain')}).then((data: any) => {
            console.log(data);
            state.data = data
            if (data) {
                window._wx.miniProgram.postMessage({data: {imgUrl: data.skuJson[0].mainImg, proName: data.labelTitle}});
            }
            brandInfo()
        })
    }

    function brandInfo() {
        api.brandInfo({brandId: state.data.brandId}).then((data: any) => {
            state.brand = data
            state.inited = true
            getAnchor()
        })
    }

    function goto(url: any) {
        url && uni.navigateTo({url})
    }

    function onSkuInfo() {
        state.popup.skuInfo.show = true
    }

    function onImagePreview(url: string) {
        ImagePreview({images: [url], closeable: true})
    }

    function cartAdd() {
        if (state.loading.cartAdd) return
        state.loading.cartAdd = true
        api.cartAdd({
            skuId: state.skuId,
            link: uni.getStorageSync('subdomain'),
            productQty: 1, // B端去除起订量限制 skuData.value.moq
        }).then(() => {
            cartCount(true)
        }).finally(() => {
            state.loading.cartAdd = false
        })
    }

    function onCollect() {
        if (!state.skuId) return
        if (state.data.isFav) {
            Dialog.confirm({
                message: '确认取消收藏',
                title: "提示",
                cancelButtonText: '取消'
            }).then(() => {
                productDel(state.skuId)
            });
        } else productFav(state.skuId)
    }

    function onCollectBrand() {
        if (state.brand.isFav) {
            Dialog.confirm({
                message: '确认取消收藏品牌',
                title: "提示",
                cancelButtonText: '取消'
            }).then(() => {
                brandDel(state.brand.brandId)
            });
        } else brandFav(state.brand.brandId)
    }

    function productFav(id: string) {
        if (state.loading.productFav) return
        state.loading.productFav = true
        api.productFav({
            link: uni.getStorageSync('subdomain'),
            skuIds: [id]
        }).then((data: any) => {
            state.data.isFav = true
        }).finally(() => {
            state.loading.productFav = false
        })
    }

    function productDel(id: string) {
        if (state.loading.productFav) return
        state.loading.productFav = true
        api.productDel({
            skuIds: [id]
        }).then((data: any) => {
            state.data.isFav = false
        }).finally(() => {
            state.loading.productFav = false
        })
    }

    function brandFav(id: string) {
        if (state.loading.brandFav) return
        state.loading.brandFav = true
        api.brandFav({
            link: uni.getStorageSync('subdomain'),
            brandId: id
        }).then((data: any) => {
            state.brand.isFav = true
        }).finally(() => {
            state.loading.brandFav = false
        })
    }

    function brandDel(id: string) {
        if (state.loading.brandFav) return
        state.loading.brandFav = true
        api.brandDel({
            brandIds: [id]
        }).then((data: any) => {
            state.brand.isFav = false
        }).finally(() => {
            state.loading.brandFav = false
        })
    }

    function goBrand(id: string) {
        uni.navigateTo({
            url: `/pages/good/brandShop?brandId=${id}`,
        })
    }

    function goBack() {
        PageUtils.goBack()
    }

    function onShare() {
        state.share.show = true
    }

    function getAnchor() {
        setTimeout(() => {
            state.tab.list.forEach(item => {
                uni.createSelectorQuery().select(item.target).boundingClientRect(data => {
                    item.top = data?.top || 0
                }).exec();
            })
            getAnchorCircle(10)
        }, 200)
    }

    // 获取高度直到，不变为止
    // -很奇葩对吧，我不知道其他方法。
    // -因为滚动的时候，也要跟着动态变，所以必须预先知道高度。
    //（如果监听滚动事件？可以，但是触发次数肯定比我多）
    // (如果监听容器高度？可以，ResizeObserver新特性，兼容性不行)
    function getAnchorCircle(heart: number) {
        if (heart == 0) return
        setTimeout(() => {
            var firstTop = 0;
            var rendering = true
            state.tab.list.forEach((item: any, index: number) => {
                uni.createSelectorQuery().select(item.target).boundingClientRect(data => {
                    if (index == 0) {
                        firstTop = data?.top || 0
                        return
                    }
                    const calcTop = (data?.top || 0) - firstTop
                    if (index == state.tab.list.length - 1 && calcTop == item.top) {
                        rendering = false
                    }
                    item.top = (data?.top || 0) - firstTop
                }).exec();
            })
            if (rendering) {
                getAnchorCircle(10)
            } else {
                getAnchorCircle(heart - 1)
            }
        }, 500)
    }

    function check(fn: Function) {
        const {token} = uni.getStorageSync("user") || {};
        if (token) {
            fn()
        } else {
            Dialog.confirm({
                message: '您尚未登录，请前往登录',
                title: "提示",
                cancelButtonText: '取消'
            }).then(() => {
                uni.reLaunch({
                    url: '/pages/login/login'
                })
            });
        }
    }

    function initWX() {
        // @ts-ignore
        const url = window.location.href;
        const wx = window._wx;
        const wxConfig = {
            debug: false, // 上生产，时设置成false
            appId: "wx6165c6cc754deeba",
            timestamp: '1690942632',
            nonceStr: '06904d46-440a-4e61-926b-b589bd9d1232',
            signature: 'dfc7b27e6b656e412b78b827a35633beeeb0cfef',
            jsApiList: ["updateAppMessageShareData"],
        };
        wx.config(wxConfig);
        wx.ready(function () {
            wx.updateAppMessageShareData({
                title: '商品详情', // 分享标题
                desc: '默认秒i书', // 分享描述
                link: url, // 分享链接
                imgUrl: 'https://img.edsmall.com/ROOT/ETao/gl/busiImage/feaa15f0-5066-47c7-8508-429fa5b80965.png', // 分享图标
                success: function (res) {
                    // console.log("分享成功返回的信息为:", res);;
                }
            })
        });
        wx.error(function (data: any) {
        });
        // if (uni.getStorageSync('isWX')) {
        //   state.wx.isWX = true
        //   WXUtils.initWXConfig(state.test).then((data: any) => {
        //     // 失败了也无所谓，就只是没分享信息而已
        //     state.wx.inited = true
        //     const wx = window._wx
        //     const mail = uni.getStorageSync('mail') || {}
        //     const shareConfig = {
        //       title: 'E淘商城-' + mail.mallName,
        //       desc: skuData.value?.title,
        //       link: url,
        //       imgUrl: skuData.value?.mainImg
        //     }
        //     wx.updateAppMessageShareData(shareConfig)
        //     wx.updateTimelineShareData(shareConfig)
        //   })
        // }
    }
    let temEtaomallId = null
    function getIndexEtaomall() {
        api.getIndexEtaomall({ domain: uni.getStorageSync("subdomain") }).then((data: any) => {
            temEtaomallId= data.etaomallId
        })
    }
    function tapchange() {
        let ua = navigator.userAgent.toLowerCase(); //判断是否是微信浏览器
        let isWeixin = ua.indexOf("micromessenger") != -1; //判断是否
        if (isWeixin) {
            window._wx.miniProgram.getEnv((res) => {
                if (res.miniprogram) {
                    onShare()
                } else {
                    let link = uni.getStorageSync('subdomain')
                    console.log(temEtaomallId,'temEtaomallIdtemEtaomallIdtemEtaomallId');
                    uni.navigateTo({
                        url: `/pages/good/share?etaomallId=${temEtaomallId}&link=${link}&title=${skuData.value.title}&skuId=${skuData.value.skuId}&brandName=${state.brand.brandName}&mainImg=${skuData.value.mainImg}`,
                    })
                }
            });
        } else {
            onShare()
        }
    }

    function onShareSelect(option: any) {
        if (option.name == '微信') {
            drawQR()
        }
    }

    function getUrl(url) {
        const q = {};
        url.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => q[k] = v);
        return q;
    }

    function drawQR() {
        if (state.share.qrcode) {
            state.share.showQRCode = true
            return
        }
        if (state.loading.qrcode) return
        state.loading.qrcode = true
        let temurl = null
        if (window.__wxjs_environment === 'miniprogram') {
            let a = window.location.href
            let huizui = a.substring(a.lastIndexOf("#"))
            temurl = `https://${uni.getStorageSync('subdomain')}.edstao.com/${huizui}`
        } else {
            temurl = window.location.href
        }
        QRCode.toDataURL(temurl, {
            width: 250,
            height: 250,
            margin: 1
        } as QRCode.QRCodeToDataURLOptions).then((url: any) => {
            state.share.qrcode = url
            state.share.showQRCode = true
        }).finally(() => {
            state.loading.qrcode = false
        })
    }

    function cartCount(afterAdd?: boolean) {
        api.cartCount().then((data: any) => {
            state.badge = data
            afterAdd && Toast.success('加入购物车')
        })
    }
</script>

<style lang="scss" scoped>

	.sign {
		position: absolute;
		right: 1.8vw;
		top: 2vw;
		width: 40px;
		text-align: center;

		img {
			width: 40px;
			margin-bottom: -18px;
		}

		.discount {
			font-family: MiSans-Semibold;
			text-shadow: 0.5px 0.5px #ddd;
			color: #A532E0;
			font-weight: 1000;
			font-size: 12px;
		}
	}

	.top_bar {
		margin-bottom: 3 rpx;

		.top_tab {
			width: 50vw;
		}
	}

	.banner_top {
		height: 60vw;
		position: relative;
		text-align: center;

		&.video {
			padding-bottom: 60 rpx;
		}

		&.video_black {
			background: #000;
		}

		.indicator {
			transition: all ease-in-out .2s;
			padding: 8 rpx 20 rpx;
			border-radius: 30 rpx;
			margin: 10 rpx;
			font-size: 20 rpx;
			color: #333333;
			background: #aaaaaa80;
			min-width: 70 rpx;

			&.active {
				background: var(--orange);
				color: #fff;
			}
		}
	}

	.scrollx_container {
		overflow-x: scroll;
		width: 85vw;

		&::-webkit-scrollbar {
			display: none;
		}
	}

	.skuInfo_label {
		width: 220 rpx;
	}

	.skuInfo_info {
		width: 480 rpx;
	}

	.good_anchor {
		background: #fff;
		color: #333333;
		font-size: 18px;
		padding: 15 rpx 30 rpx;
		border-left: 3px solid #FE521F;
	}

	.good_img {
		position: relative;

		.zone_icon {
			position: absolute;
			left: 20 rpx;
			bottom: 20 rpx;
		}
	}

	.detail_btn {
		font-size: 14px;
		padding: 10px;
		height: 25px;
	}
</style>
