<template>
    <view class="product-detail">
        <tui-skeleton v-if="isRequest" :loadingType="3" :isLoading="true"></tui-skeleton>
        <template v-else>
            <!-- 顶部导航 -->
            <goods-top-tabs @change="onTabChange" :current="currentTab" v-show="scrollTop > 100"></goods-top-tabs>
            
            <simple-safe-view>
                <!-- 锚点0 -->
                <view id="anchor-0" class="anchor"></view>
            
                <!-- 轮播 -->
                <goods-image-swiper
                    :list="imageList"
                    @click="onSwiperClick"
                    @change="onSwiperChange"
                    :current="current"
                    :autoplay="autoplay"
                ></goods-image-swiper>
                <!-- 价格 -->
                <goods-price :productData="productInfo"></goods-price>
            
                <!-- 活动优惠券 -->
                <goods-coupon-list
                    @click="couponVisiable = true"
                    :couponList="couponList"
                    v-if="couponList.length > 0"
                ></goods-coupon-list>
            
                <!-- 商品基本信息：商品名称 && 分享 && 标签 && 备注 && 服务-->
                <goods-info @share="onShare" :productData="productInfo"></goods-info>
            
                <view class="section" v-if="productInfo.skus.length > 0">
                    <goods-unit-section :skuList="productInfo.skus" @click="onUnitClick"></goods-unit-section>
                </view>
            
                <!-- 参数 -->
                <view class="section" v-if="productInfo.parametersList.length > 0">
                    <goods-params-section :paramList="productInfo.parametersList"></goods-params-section>
                </view>
            
                <!-- 优惠券 -->
                <view class="section" v-if="couponList.length > 0">
                    <goods-coupon-section @click="couponVisiable = true" :couponList="couponList"></goods-coupon-section>
                </view>
            
                <!-- 特殊商品退货须知 -->
                <view class="section" v-if="returnGoodsStutas">
                    <goods-return-instructions :content="helpContent"></goods-return-instructions>
                </view>
            
                <!-- 锚点1 -->
                <view id="anchor-1" class="anchor"></view>
            
                <!-- 商品详情 -->
                <view class="section detail">
                    <view class="title">商品详情</view>
                    <template v-if="productDetail && productDetail.detailInfo">
                        <uParse :content="productDetail.detailInfo" />
                    </template>
                    <!-- 空 -->
                    <view class="section-empty" v-else>暂无商品详情</view>
                </view>
            
                <!-- 锚点2 -->
                <view id="anchor-2" class="anchor"></view>
            
                <!-- 服务项目 -->
                <view class="section service-items">
                    <view class="title">服务项目</view>
                    <view v-if="productDetail && productDetail.serviceInfo" v-html="productDetail.serviceInfo"></view>
                    <!-- 空 -->
                    <view class="section-empty">暂无服务项目</view>
                </view>
            </simple-safe-view>
            
            <!-- 商品操作导航 -->
            <goods-navbar class="navbar" :class="navbarType" @rightClick="navbarRightClick" @leftClick="navbarLeftClick">
                <template v-slot:left>
                    <view class="left-btn text1" v-text="leftButton[0]"></view>
                    <view class="left-btn" v-if="leftButton[1]">
                        <text class="prefix">券后</text>
                        <text class="text2" v-text="leftButton[1]"></text>
                    </view>
                </template>
                <template v-slot:right>
                    <view class="right-btn text1" v-text="rightButton[0]"></view>
                    <view class="right-btn" v-if="rightButton[1]">
                        <text class="prefix">券后</text>
                        <text class="text2" v-text="rightButton[1]"></text>
                    </view>
                </template>
            </goods-navbar>
            
            <!-- 活动价 -->
            <cm-goods-activity-popup
                ref="activitypPopup"
                :ladderList="ladderPriceList"
                @open="goodsBuyPopup = false"
                @close="goodsBuyPopup = true"
            ></cm-goods-activity-popup>
            
            <!-- 分享弹窗 -->
            <cm-share-popup ref="sharePopup" :data="posterData" type="product"></cm-share-popup>
            
            <!-- 优惠券弹窗 -->
            <cm-coupon-popup
                :list="couponList"
                :visiable="couponVisiable"
                :hasSafeArea="true"
                @close="couponVisiable = false"
                @couponClick="onCouponClick"
            ></cm-coupon-popup>
            
            <!-- 返回顶部 -->
            <tui-scroll-top :scrollTop="scrollTop" :bottom="80"></tui-scroll-top>
            
            <!-- 购买弹窗 -->
            <cm-goods-buy-popup
                v-model="goodsBuyPopup"
                :product="productInfo"
                :couponList="couponList"
                :useType="useType"
                :buttonType="buttonType"
                @activityClick="handleShowActivity"
                @confirm="onSubmit"
                v-if="productInfo"
            ></cm-goods-buy-popup>
            
        </template>
    </view>
</template>

<script>
import uParse from './uParse/src/wxParse.vue'
import { debounce } from '@/common/utils.js'
import { shareDataResult } from '@/common/share.helper.js'
import { queryStringify } from '@/common/utils.js'
import { mapGetters, mapActions } from 'vuex'
import {
    generateNavbarButtonText,
    fetchPorductInfo,
    fetchCouponListByProduct,
    generateNavbarType
} from '@/common/goods.helper.js'

export default {
    components: {
        uParse
    },
    data() {
        return {
            isRequest: true,
            jumpState: 0,
            productId: '',
            // 轮播图
            currentTab: 0,
            current: 0,
            leftButton: {},
            rightButton: {},
            // 锚点列表
            anchorList: [],
            scrollTop: 0,
            productInfo: {},
            couponList: [],
            couponVisiable: false,
            navbarTypeFlag: '',
            // 海报数据
            posterData: {},
            collageId: '',
            groupBuyFlag: false, // 用户是否拼团购买
            autoplay: true,
            // 购买商品弹窗
            goodsBuyPopup: false,
            useType: 'buy',
            buttonType: 'left',
            ladderPriceList: []
        }
    },
    computed: {
        ...mapGetters(['userId']),
        // 轮播图
        imageList() {
            return this.productInfo.imageList
        },
        // 活动价
        // ladderList() {
        //     return this.productInfo.ladderList
        // },
        // 商品详情
        productDetail() {
            return this.productInfo.productDetail
        },
        // 商品导航类型
        navbarType() {
            return generateNavbarType(this.productInfo)
        },
        // 当前商品默认可以使的优惠券
        couponTip() {
            if (this.productInfo.couponId) {
                const currentCoupon = this.couponList.find(coupon => this.productInfo.couponId === coupon.couponId)
                return currentCoupon?.couponTitle
            } else {
                return this.productInfo?.couponInfo?.split('|')[1]
            }
        },
        returnGoodsStutas() {
            return this.productInfo.returnGoodsStutas && this.productInfo.returnGoodsStutas === 2
        },
        helpContent() {
            return this.productInfo.helpContent
        }
    },
    onPageScroll(e) {
        this.scrollTop = e.scrollTop
        this.getAnchorList()
    },
    onShareAppMessage() {
        const shareData = {
            type: 1,
            productId: this.productInfo.productId,
            inviteUserId: this.userId,
            jumpState: this.jumpState
        }
        return shareDataResult(shareData, this.productInfo.name, this.imageList[0])
    },
    onLoad(options) {
        this.productId = parseInt(options.productId)
        this.jumpState = parseInt(options.jumpState)
    },
    onShow() {
        this.initPage()
    },
    onHide() {
        this.autoplay = false
    },
    methods: {
        ...mapActions('cart', ['addToCart']),

        // 选择规格
        onUnitClick() {
            this.useType = 'unit'
            this.goodsBuyPopup = true
        },

        async initPage() {
            this.autoplay = true
            // 获取商品详情
            this.fetchProductDetail()
            // 获取商品可用优惠券
            this.couponList = await fetchCouponListByProduct(this.productId)
        },

        // 获取商品详情
        async fetchProductDetail() {
            this.productInfo = await fetchPorductInfo(this.productId)
            this.isRequest = false
            this.productInfo.heUserId = this.jumpState === 1 ? 0 : this.userId
            this.initNavbarButton()
        },

        // 活动价弹窗
        handleShowActivity(current) {
            if (!current.ladderPriceList) return
            this.ladderPriceList = current.ladderPriceList
            this.$refs.activitypPopup.open()
        },

        // 商品提交
        onSubmit(detail) {
            // return uni.navigateTo({
            //     url:'/pages/views/goods/Update-Maintenance'
            // })
            // 用户未登录
            if (!this.userId) {
                const pages = getCurrentPages()
                const page = pages[pages.length - 1]
                uni.setStorageSync('LOGIN_REDIRECT_URL', page.$page.fullPath)
                uni.redirectTo({ url: '/pages/authorize/login-custom' })
                this.goodsBuyPopup = false
                return
            }

            // 加入购物车
            if (detail.type === 'cart') {
                this.addToCart({
                    skuId: detail.sku.skuId,
                    productCount: detail.count,
                    heUserId: this.productInfo.heUserId
                })
                this.goodsBuyPopup = false
                return
            }

            console.log(detail)

            // 立即购买
            if (detail.type === 'buy') {
                const submitData = {
                    productId: detail.sku.productId, // 产品id
                    skuId: detail.sku.skuId, // sku id
                    productCount: detail.count, // 产品购买数量
                    heUserId: this.productInfo.heUserId, // 协销用户id
                    collageFlag: this.groupBuyFlag ? 1 : 0, // 是否拼团购买
                    collageId: this.collageId, // 拼团id
                    couponId: detail.sku.couponId, // 默认使用优惠券id
                    allCount: detail.count // 商品总数
                }
                uni.setStorageSync('COMMIT_PRODUCT_INFO', submitData)
                this.$router.navigateTo('order/order-create?type=product')
                this.goodsBuyPopup = false
                return
            }
        },

        // 优惠券点击事件
        onCouponClick(couponData) {
            if (couponData.controlType === 'receive') {
                this.fetchCouponList()
            }
        },

        // 分享事件
        onShare() {
            const query = queryStringify({
                type: 1,
                productId: this.productInfo.productId,
                inviteUserId: this.userId,
                jumpState: this.jumpState
            })
            this.posterData = {
                porductName: this.productInfo.name,
                productPrice: this.productInfo.price,
                productOriginPrice:
                    this.productInfo.normalPrice === this.productInfo.price ? 0 : this.productInfo.normalPrice,
                productImage: this.productInfo.mainImage,
                query: query
            }
            this.$refs.sharePopup.open()
        },

        // 轮播图事件
        onSwiperClick() {
            uni.previewImage({
                urls: this.imageList,
                current: this.current,
                loop: true
            })
        },

        // 轮播图切换
        onSwiperChange(current) {
            this.current = current
        },

        // 初始化导航按钮文案
        initNavbarButton() {
            const navbarButton = generateNavbarButtonText(this.productInfo)
            this.leftButton = navbarButton.left
            this.rightButton = navbarButton.right
        },

        // 导航菜单右侧按钮点击
        navbarRightClick(index) {
            this.navbarTypeFlag = index > 0 || this.productInfo.collageStatus > 0 ? 'buy' : 'cart'
            if (this.productInfo.activityType === 'group') {
                this.groupBuyFlag = index > 0
            }
            this.useType = 'buy'
            this.buttonType = index === 0 ? 'left' : 'right'
            this.goodsBuyPopup = true
        },

        // 导航栏菜单左侧按钮点击
        navbarLeftClick(index) {
            if (index === 0) {
                this.$router.switchTab('home')
            }
            if (index === 2) {
                if (!this.userId) {
                    const pages = getCurrentPages()
                    const page = pages[pages.length - 1]
                    uni.setStorageSync('LOGIN_REDIRECT_URL', page.$page.fullPath)
                    uni.redirectTo({ url: '/pages/authorize/login-custom' })
                    return
                }
                this.$router.navigateTo('cart/cart')
            }
        },

        // 顶部tab切换
        onTabChange(index) {
            const offset = this.anchorList[index].top
            uni.pageScrollTo({
                scrollTop: this.scrollTop + offset - 40 - 10,
                duration: 300
            })
        },

        // 初始化锚点
        getAnchorList: debounce(
            function() {
                const query = uni.createSelectorQuery().in(this)
                query
                    .selectAll('.anchor')
                    .boundingClientRect(data => {
                        this.anchorList = data
                        this.setCurrentTabIndex()
                    })
                    .exec()
            },
            300,
            false
        ),

        // 设置tab索引
        setCurrentTabIndex() {
            this.anchorList.forEach((item, index) => {
                if (item.bottom < 100) {
                    this.currentTab = index
                }
            })
        }
    }
}
</script>

<style lang="scss">
.section.detail {
    image {
        display: block;
    }
}
</style>

<style lang="scss" scoped>
.product-detail {
    min-height: 100vh;
    padding-bottom: 100rpx;
    box-sizing: border-box;

    .section {
        margin: 24rpx 0;
        background-color: #fff;

        &.detail {
            padding: 24rpx;
        }

        &.service-items {
            padding: 24rpx;
        }

        .title {
            margin-bottom: 24rpx;
            font-size: 26rpx;
            font-weight: bold;
        }

        .section-empty {
            font-size: 24rpx;
            color: #999;
        }
    }

    .navbar {
        line-height: 1;
        text-align: center;
        &.group,
        &.normal {
            .prefix {
                display: none !important;
            }
        }

        .left-btn {
            color: #ff457b;
            &.text1 {
                font-size: 24rpx;
                margin-bottom: 4rpx;
            }
            .text2 {
                font-size: 24rpx;
                font-weight: bold;
            }

            .prefix {
                font-size: 20rpx;
            }
        }

        .right-btn {
            color: #fff;
            &.text1 {
                font-size: 24rpx;
                margin-bottom: 4rpx;
            }

            .text2 {
                font-size: 24rpx;
                font-weight: bold;
            }

            .prefix {
                font-size: 20rpx;
            }
        }
    }
}
</style>
