<template>
    <view class="cm-share-popup">
        <!-- 分享弹窗 -->
        <simple-share-popup ref="sharePopup" :posterUrl="posterUrl" @click="onPopupClick" @close="onClose">
            <slot name="title"></slot>
        </simple-share-popup>
        <!-- 海报画布 -->
        <canvas canvas-id="poster" class="poster-canvas"></canvas>
    </view>
</template>

<script>
import DrawPoster from './draw-poster.js'
import { getUserProfile } from '@/common/auth.js'
import { generateWxUnlimited } from '@/common/share.helper.js'
export default {
    name: 'cm-share-popup',
    props: {
        data: {
            type: Object,
            default: () => {}
        },
        type: {
            type: String,
            default: 'normal',
            validator: value => {
                return ['product', 'normal', 'activity'].indexOf(value) > -1
            }
        }
    },
    data() {
        return {
            posterUrl: '',
            posterData: {
                /* 用户信息 */
                avatar: '', // 用户头像
                username: '', // 用户名

                /* 页面参数 */
                query: '', // 查询参数字符串
                path: '', // 页面路径
                qrCodeImage: '', //页面二维码，小程序二维码

                /* 产品参数 */
                porductName: '', // 产品名
                productPrice: '', // 产品价格
                productOriginPrice: '', // 产品原价
                productImage: '', // 产品图片

                /* 活动参数 */
                activityName:
                    '活动名称活动名称活动名称活动名称活动名称活动名称活动名称活动名称活动名称活动名称活动名称活动名称活动名称活动名称活动名称活动名称', // 活动名称
                activityImage: 'https://picsum.photos/400/400' //活动封面
            }
        }
    },
    methods: {
        // 分享操作
        onPopupClick(e) {
            if (e.type === 'create-poster') {
                console.log('生成海报')
                this.createPoster()
            } else {
                console.log('普通分享')
                this.$refs.sharePopup.close()
                this.onShare()
            }
        },
        // 打开弹窗
        open() {
            this.$refs.sharePopup.open()
            this.$emit('open')
        },
        close() {
            this.$refs.sharePopup.close()
        },
        onClose() {
            uni.hideLoading()
            this.$emit('close')
        },
        onShare() {
            this.$emit('share')
            console.log('分享')
        },
        // 创建海报
        async createPoster() {
            try {
                uni.showLoading({ title: '正在生成海报' })
                if (!this.posterUrl) {
                    this.posterData = { ...this.posterData, ...this.data }
                    // 从本地缓存中获取微信用户基本信息
                    let userProfile = this.$getStorage('USER_PROFILE')
                    if (!userProfile) {
                        userProfile = await getUserProfile()
                        this.$setStorage('USER_PROFILE', userProfile)
                    }
                    this.posterData.avatar = userProfile.avatarUrl
                    this.posterData.username = userProfile.nickName

                    const { data: qrCodeImage } = await generateWxUnlimited({
                        pagePath: this.posterData.path,
                        queryStr: this.posterData.query
                    })

                    this.posterData.qrCodeImage = qrCodeImage

                    switch (this.type) {
                        case 'product':
                            await this.createProductPoster()
                            break
                        case 'activity':
                            await this.createActivityPoster()
                            break
                        default:
                            await this.createNormalPoster()
                    }

                    const { tempFilePath } = await this.canvasToTempFilePath()
                    this.posterUrl = tempFilePath
                }
                uni.hideLoading()
                // 下载完成后转发
                wx.showShareImageMenu({ path: this.posterUrl })
                this.onShare()
            } catch (e) {
                console.log(e)
            } finally {
                uni.hideLoading()
            }
        },

        // 画布转图片临时链接
        canvasToTempFilePath() {
            return new Promise((resolve, reject) => {
                uni.canvasToTempFilePath(
                    {
                        canvasId: 'poster',
                        success: res => {
                            resolve(res)
                        },
                        fail() {
                            reject(false)
                        }
                    },
                    this
                )
            })
        },

        // 生成绘制文本数组
        generateTextArray() {
            const textArray = []
            const { productPrice, productOriginPrice, porductName, activityName } = this.posterData

            // 处理价格
            let priceText = ''
            if (this.type === 'product') {
                if (productPrice) {
                    priceText += productPrice
                }
                if (productOriginPrice) {
                    priceText += '￥' + productOriginPrice
                }
            }
            textArray.push(priceText)

            // 处理产品名称
            if (porductName || activityName) {
                const nameStr = porductName || activityName
                textArray.push(nameStr.substring(0, 12))
                if (nameStr.length > 24) {
                    textArray.push(nameStr.substring(12, 23) + '...')
                } else {
                    textArray.push(nameStr.substring(12))
                }
            }
            return textArray
        },

        // 商品海报
        async createProductPoster() {
            try {
                const ctx = uni.createCanvasContext('poster', this)
                const drawPoster = new DrawPoster(ctx, {
                    avatarUrl: this.posterData.avatar,
                    userName: this.posterData.username,
                    subTitle: '强烈为你推荐该商品',
                    coverUrl: this.posterData.productImage,
                    ewmUrl: this.posterData.qrCodeImage,
                    textArray: this.generateTextArray()
                })
                return await drawPoster.draw()
            } catch (e) {
                throw e
            }
        },

        // 活动页面
        async createActivityPoster() {
            try {
                const ctx = uni.createCanvasContext('poster', this)
                const drawPoster = new DrawPoster(ctx, {
                    avatarUrl: this.posterData.avatar,
                    userName: this.posterData.username,
                    subTitle: '强烈为你推荐该活动',
                    coverUrl: this.posterData.activityImage,
                    ewmUrl: this.posterData.qrCodeImage,
                    textArray: this.generateTextArray()
                })
                return await drawPoster.draw()
            } catch (e) {
                throw e
            }
        },

        // 普通海报
        async createNormalPoster() {
            try {
                const ctx = uni.createCanvasContext('poster', this)
                const drawPoster = new DrawPoster(ctx, {
                    avatarUrl: this.posterData.avatar,
                    userName: this.posterData.username,
                    subTitle: '强烈为你推荐该商城',
                    textArray: ['', '护肤上颜选，正品', '有好货~~']
                })
                return await drawPoster.draw()
            } catch (e) {
                throw e
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.poster-canvas {
    position: fixed;
    top: -9999px;
    left: -9999px;
    width: 375px;
    height: 610px;
}
</style>
