<template>
    <view class="share-buy-detail">
        <tui-skeleton v-if="isRequest" :loadingType="3" :isLoading="true"></tui-skeleton>
        <!-- 拼单信息 && 立即拼单 -->
        <view class="group-message">
            <share-buy-group-message :countDownTime="countDownTime" :hasEndTip="true">
                <template v-slot:head>
                    <view class="message">
                        还差
                        <text v-text="collageData.needNum"></text>
                        人参团，赶快邀请好友来拼单吧！
                    </view>
                </template>
                <template v-slot:foot>
                    <tui-button type="base" width="600rpx" height="90rpx" shape="circle" :size="30" @click="onShare">
                        <text>邀请好友拼单</text>
                    </tui-button>
                    <view class="line"></view>
                    <tui-button
                        type="base"
                        width="600rpx"
                        height="90rpx"
                        shape="circle"
                        :plain="true"
                        :size="30"
                        @click="handleToHome"
                    >
                        <text>去首页逛逛</text>
                    </tui-button>
                </template>
            </share-buy-group-message>
        </view>
        <!-- 商品基本信息 参与拼单用户信息-->
        <view class="member-info">
            <share-buy-member-info
                :memberNum="collageData.memberNum"
                :existNum="collageData.existNum"
                :shopInfo="collageData"
            ></share-buy-member-info>
        </view>

        <!-- 分享 -->
        <cm-share-popup ref="sharePopup" :data="posterData" type="product" @share="onAfterShare">
            <template #title>
                <view class="share-title">
                    <view class="title">
                        还差
                        <text v-text="collageData.needNum"></text>
                        人，赶快邀请好友来拼单吧！
                    </view>
                    <view class="share-desc">
                        拼单已发起，人满后立即发货
                        <text v-if="canShare">（首次分享可获得一张消费分享券）</text>
                    </view>
                </view>
            </template>
        </cm-share-popup>
    </view>
</template>

<script>
import { fetchCollageOrderDetail, orderShare } from '@/services/api/order.js'
import { fetchCouponDisplay } from '@/services/api/coupon.js'
import { countDown, queryStringify } from '@/common/utils.js'
import { mapGetters } from 'vuex'
export default {
    data() {
        return {
            isRequest: true,
            collageId: '',
            collageData: {},
            // 海报生成数据
            posterData: {},
            timer: null,
            countDownTime: {},
            couponTipStr: ''
        }
    },
    computed: {
        ...mapGetters(['userId']),
        canShare() {
            return this.collageData.shareFlag === 1 && this.couponTipStr.indexOf('3') > -1
        }
    },
    // 分享到微信用户
    onShareAppMessage() {
        const shareData = {
            type: 4,
            collageId: this.collageData.collageId,
            initiatorId: this.userId
        }

        const state_str = encodeURIComponent(this.$crypto.encrypt(shareData))
        console.log(state_str)
        return {
            title: '哈喽，赶快来参团吧！这件商品拼团买更便宜~',
            path: `/pages/index/index?state_str=${state_str}`,
            imageUrl: this.collageData.productImage
        }
    },
    onLoad(options) {
        this.collageId = options.collageId
        this.fetchCouponDisplay()
    },
    onShow() {
        this.fetchOrderDetails()
    },
    methods: {
        // 获取可领取优惠券类型
        async fetchCouponDisplay() {
            try {
                const res = await fetchCouponDisplay({ userId: this.userId })
                this.couponTipStr = res.data
            } catch (e) {
                console.log('获取优惠券类型失败')
            }
        },

        // 分享结束
        async onAfterShare() {
            if (!this.canShare) return
            try {
                await orderShare({ orderId: this.collageData.orderId, userId: this.userId })
                this.$toast('分享成功')
            } catch (e) {
                this.$toast('分享失败')
            }
        },

        // 分享
        async onShare() {
            const query = queryStringify({
                type: 4,
                collageId: this.collageData.collageId,
                initiatorId: this.userId
            })
            this.posterData = {
                porductName: '哈喽，赶快来参团吧！这件商品拼团买更便宜~',
                productPrice: this.collageData.price,
                productOriginPrice: this.collageData.normalPrice,
                productImage: this.collageData.productImage,
                query: query
            }
            this.$refs.sharePopup.open()
        },

        // 获取拼单详情
        async fetchOrderDetails() {
            try {
                const res = await fetchCollageOrderDetail({
                    collageId: this.collageId,
                    userId: this.userId
                })
                this.collageData = res.data
                const { memberNum, existNum, productName, productImage, price } = this.collageData
                // 验证拼单是否成功
                if (memberNum === existNum) {
                    uni.setStorageSync('SHARE_BUY_COLLAGE_DATA', this.collageData)
                    setTimeout(() => {
                        this.$router.redirectTo('share-buy/share-buy-success')
                    }, 500)
                    return
                }
                // 设置分享海报商品信息
                this.posterData.porductName = productName
                this.posterData.productImage = productImage
                this.posterData.productPrice = price
                this.countDown()
                this.isRequest = false
            } catch (e) {
                console.log(e)
            }
        },
        // 去首页
        handleToHome() {
            this.$router.switchTab('home')
        },

        // 倒计时
        countDown() {
            const startTime = Date.now()
            const endTime = new Date(this.collageData.endTime).getTime()
            this.timer && clearTimeout(this.timer)
            countDown(endTime, startTime, {}, item => {
                this.countDownTime = item.conttainer
                this.timer = item.t
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.share-buy-detail {
    .line {
        height: 24rpx;
    }

    .member-info {
        margin-top: 24rpx;
    }

    .message {
        font-size: 30rpx;
        color: #333333;
        text {
            color: #ff457b;
        }
    }

    .share-title {
        text-align: center;
        padding-bottom: 40rpx;
        .title {
            font-size: 34rpx;
            font-weight: bold;
            line-height: 48rpx;
            color: #666666;

            text {
                color: #ff457b;
            }
        }
        .share-desc {
            margin-top: 14rpx;
            font-size: 26rpx;
            color: #333;
            line-height: 1.6;

            text {
                color: #ff457b;
            }
        }
    }
}
</style>
