<template>
    <view class="product-detail" :class="{ hasBottom: isIphoneX }">
        <tui-skeleton :loadingType="2" v-if="isRequest"></tui-skeleton>
        <template v-else>
            <!-- 顶部tabs -->
            <tui-tabs
                v-show="scrollTop > 40"
                class="fixed"
                :tabs="tabs"
                :currentTab="currentTab"
                @change="tabChange"
                color="#666666"
                bold
                selectedColor="#FF457B"
                sliderBgColor="#FF457B"
            ></tui-tabs>
            <view id="anchor1" class="anchor">
                <!-- 商品图片 -->
                <uni-swiper-dot :info="imageList" :current="swiperCurrent" mode="left" class="swiper-box">
                    <swiper @change="swiperChange" class="swiper">
                        <swiper-item v-for="(image, index) in imageList" :key="index">
                            <image :src="image" class="image" @click="previewImage(index)"></image>
                        </swiper-item>
                    </swiper>
                </uni-swiper-dot>
                <view class="row">
                    <!-- 价格 -->
                    <cm-product-price :productInfo="productInfo" class="cm-product-price"></cm-product-price>
                    <!-- 商品信息 -->
                    <cm-product-info :productInfo="productInfo" class="cm-product-info"></cm-product-info>
                </view>
                <!-- 商品参数 -->
                <view class="row touch-bar params" @click="paramsVisible = true">
                    <view class="name">
                        <text class="p1">参数：</text><text class="p2">品牌</text><text class="p2">分类...</text>
                    </view>
                    <text class="iconfont icon-chakangengduo"></text>
                </view>
                <!-- 优惠券 -->
                <view class="row touch-bar coupon" @click="couponVisible = true" v-if="couponList.length > 0">
                    <view class="name">优惠券：</view>
                    <view class="left">
                        <view class="coupon-tags">
                            <text class="tag" v-for="(tagName, index) in couponTags" :key="index">{{ tagName }}</text>
                        </view>
                        <text class="iconfont icon-chakangengduo"></text>
                    </view>
                </view>
            </view>
            <!-- 商品详情 -->
            <view class="row product-info anchor" id="anchor2">
                <view class="title">商品详情</view>
                <view class="product-rich-text">
                    <parser :html="detailHtml" :img-mode="widthFix" v-if="detailHtml"></parser>
                    <view class="product-rich-text-none" v-else>暂无商品信息</view>
                </view>
            </view>
            <!-- 服务项目 -->
            <view class="row product-info anchor" id="anchor3">
                <!-- 服务项目 -->
                <view class="title">服务项目</view>
                <template v-if="product.productDetail.orderInfo || product.productDetail.serviceInfo">
                    <cm-service :product="product.productDetail"></cm-service>
                </template>
                <view class="content-none" v-else> <text>暂无服务项目</text> </view>
            </view>
        </template>
        <!-- 商品导航 -->
        <cm-goods-nav :productInfo="productInfo"></cm-goods-nav>
        <!-- 回到顶部 -->
        <tui-scroll-top :scrollTop="scrollTop" :bottom="0" :duration="500"></tui-scroll-top>
        <!-- 商品参数 -->
        <cm-product-params
            :visible="paramsVisible"
            :productInfo="productInfo"
            @close="paramsVisible = false"
        ></cm-product-params>
        <!-- 优惠券列表 TODO-->
        <cm-coupon-list
            title="获取优惠券"
            listType="receive"
            :couponList="couponList"
            :visible="couponVisible"
            :showStatus="true"
            @close="closeCouponList"
            @couponClick="couponClick"
        ></cm-coupon-list>
    </view>
</template>

<script>
import { mapGetters, mapActions, mapMutations } from 'vuex'
import CmProductPrice from '@/components/cm-module/cm-product-price/cm-product-price.vue'
import CmProductInfo from '@/components/cm-module/cm-product-info/cm-product-info.vue'
import CmCouponList from '@/components/cm-module/cm-coupon-list/cm-coupon-list'
import CmProductParams from '@/components/cm-module/cm-product-params/cm-product-params.vue'
import CmGoodsNav from '@/components/cm-module/cm-goods-nav/cm-goods-nav.vue'
import Parser from '@/components/jyf-Parser/index' //富文本处理
const observers = {}
export default {
    components: {
        Parser,
        CmProductPrice,
        CmProductInfo,
        CmCouponList,
        CmProductParams,
        CmGoodsNav
    },
    data() {
        return {
            tabs: [{ name: '商品' }, { name: '详情' }, { name: '服务项目' }],
            currentTab: 0,
            productId: 1014,
            imageList: [
                'https://picsum.photos/750/750?random=1',
                'https://picsum.photos/750/750?random=2',
                'https://picsum.photos/750/750?random=3'
            ],
            swiperCurrent: 0,
            productInfo: {},
            isRequest: true,
            scrollTop: 0,
            couponList: [],
            couponVisible: false,
            paramsVisible: false,
            jumpState: 1,
            selectorTimer: null,
            anchorList: [], // 锚点元素节点信息
            anchorStatus: [0, 0, 0] // 分别代表三个锚点区域的开关 0:关  1:开
        }
    },
    computed: {
        ...mapGetters(['isIphoneX', 'kindCount', 'userId']),
        // 优惠券标签
        couponTags() {
            const result = []
            for (let i = 0; i < this.couponList.length; i++) {
                if (i >= 3) return result
                if (this.couponList[i].noThresholdFlag === 1) {
                    result.push(`减${this.couponList[i].couponAmount}`)
                } else {
                    result.push(`满${this.couponList[i].touchPrice}减${this.couponList[i].couponAmount}`)
                }
            }
            return result
        },
        // 商品详情html
        detailHtml() {
            return this.productInfo.hasOwnProperty('productDetail') ? this.productInfo.productDetail.detailInfo : ''
        }
    },
    onPageScroll(e) {
        this.scrollTop = e.scrollTop
        // this.observerAnchor()
        this.setCurrentTab()
    },
    onLoad(option) {
        this.jumpState = parseInt(option.jumpState)
        this.productId = parseInt(option.productId)
        this.initProductDetail()
        this.getCouponByProduct()
    },
    onReady() {
        this.selectorTimer = setInterval(() => {
            if (!this.isRequest) {
                this.getAnchorSection()
            }
        }, 1000)
    },
    //分享转发
    onShareAppMessage(res) {
        // 加密参数
        const shareData = {
            type: 1,
            productId: this.productInfo.productId,
            inviteUserId: this.userId,
            jumpState: this.jumpState
        }
        // 加密
        const state_str = encodeURIComponent(this.$crypto.encrypt(shareData))
        console.log(state_str)
        return {
            title: this.productInfo.name,
            path: `pages/tabBar/index/index?state_str=${state_str}`,
            imageUrl: this.imageList[0]
        }
    },
    methods: {
        // tab切换
        tabChange(e) {
            this.currentTab = e.index
            this.scrollToAnchor()
        },
        // 加入购物车 / 立即下单信息
        initProductInfo(data) {
            // jumpState 1: 非活动页商品详情 2: 活动页面商品详情
            data.heUserId = this.jumpState === 1 ? 0 : this.userId
            return data
        },
        // 初始化商品详情
        initProductDetail() {
            this.ProductService.QueryProductDetils({
                productId: this.productId,
                userId: this.userId
            }).then(res => {
                const data = res.data
                this.imageList = data.imageList
                this.productInfo = this.initProductInfo(data)
                this.isRequest = false
            })
        },
        // 获取当前商品可用优惠券列表
        getCouponByProduct() {
            this.CouponService.GetCouponByProduct({
                productId: this.productId,
                userId: this.userId
            }).then(res => {
                this.couponList = res.data
            })
        },
        // 关闭优惠券列表
        closeCouponList() {
            this.couponVisible = false
        },
        // 优惠券列表按钮点击事件
        couponClick() {
            this.getCouponByProduct()
            // this.couponVisible = false
        },
        // 轮播图切换
        swiperChange(e) {
            this.swiperCurrent = e.detail.current
        },
        // 图片预览
        previewImage(index) {
            uni.previewImage({
                current: index,
                urls: this.imageList
            })
        },
        // 获取锚点元素信息
        getAnchorSection() {
            const query = uni.createSelectorQuery().in(this)
            query
                .selectAll('.anchor')
                .boundingClientRect(data => {
                    if (data.length > 0) {
                        this.anchorList = data
                        clearInterval(this.selectorTimer)
                        this.observerAnchor(data)
                    }
                })
                .exec()
        },
        // 滚动到锚点
        scrollToAnchor() {
            // const selector = '#anchor' + (this.currentTab + 1)
            uni.pageScrollTo({
                scrollTop: this.anchorList[this.currentTab].top - 40
            })
        },
        // 为需要观测的区域创建观测者
        observerAnchor(selectorList = []) {
            const height = uni.getSystemInfoSync().windowHeight - 50
            selectorList.forEach((selector, index) => {
                observers[selector.id] = uni.createIntersectionObserver(this)
                observers[selector.id].relativeToViewport({ bottom: -height }).observe(`#${selector.id}`, res => {
                    if (res.intersectionRatio > 0) {
                        this.anchorStatus[index] = 1
                        // console.log(index, `当前区域为${selector.id}标签选择器的区域...`)
                    } else {
                        this.anchorStatus[index] = 0
                        // console.log(index, `离开区域为${selector.id}标签选择器的区域...`)
                    }
                })
            })
        },
        // 设置currentTab
        setCurrentTab() {
            const index = this.anchorStatus.lastIndexOf(1)
            if (this.currentTab !== index) this.currentTab = index
        }
    }
}
</script>

<style lang="scss" scoped>
$swiper-width: 750rpx;
.fixed {
    position: fixed;
    width: 100%;
    top: 0;
    left: 0;
    z-index: 99;
}
.product-detail {
    min-height: 100vh;
    background: #f7f7f7;
    box-sizing: border-box;
    // padding-top: 80rpx;
    padding-bottom: 100rpx;
    &.hasBottom {
        padding-bottom: 144rpx;
    }
}
.swiper-box {
    position: relative;
}
.swiper {
    width: $swiper-width;
    height: $swiper-width;
    .image {
        width: $swiper-width;
        height: $swiper-width;
    }
}
.row {
    padding: 0 24rpx;
    margin-bottom: 24rpx;
    background: #ffffff;
    &.touch-bar {
        line-height: 90rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .name {
            font-size: 28rpx;
        }
    }
    &.params {
        .p1,
        .iconfont {
            color: #999999;
        }
        .p2 {
            margin: 0 32rpx;
            color: #333333;
        }
    }
    &.coupon {
        color: #ff457b;
        .left {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            .tag {
                padding: 2rpx 8rpx;
                font-size: 20rpx;
                background: #fff3f7;
                border: 1rpx solid #ff457b;
                border-radius: 8rpx;
                margin-left: 8rpx;
                box-sizing: border-box;
            }
            .iconfont {
                margin-left: 24rpx;
            }
        }
    }
    &.product-info {
        padding-bottom: 24rpx;
        .title {
            padding: 40rpx 0 32rpx;
            font-size: 28rpx;
            font-weight: bold;
            color: #333333;
        }
        .product-rich-text-none {
            box-sizing: border-box;
            text-align: left;
            font-size: 24rpx;
            color: #999999;
            line-height: 60rpx;
        }
        .content-none {
            height: 80rpx;
            line-height: 80rpx;
            text-align: left;
            font-size: 26rpx;
            color: #999999;
            box-sizing: border-box;
        }
    }
}
</style>
