<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 { mapState } from 'vuex'
import { generateWxUnlimited, enCodeQueryStr } from '@/pages/goods/mixins/share.helper.js'
import simpleSharePopup from './simple-share-popup/simple-share-popup.vue'
export default {
    name: 'cm-share-popup',
    components: {
        simpleSharePopup
    },
    props: {
        data: {
            type: Object,
            default: () => {}
        },
        type: {
            type: String,
            default: 'normal',
            validator: value => {
                return ['product', 'normal', 'activity'].indexOf(value) > -1
            }
        }
    },
    data() {
        return {
            posterUrl: '',
            ctx: '',
            posterData: {
                /* 用户信息 */
                image: '', // 用户头像
                qrCode: '', // 用户二维码
                linkMan: '', // 用户名
                contractMobile: '', // 用户手机号
                /* 页面参数 */
                query: '', // 查询参数字符串
                path: '', // 页面路径
                qrCodeImage: '', //页面二维码，小程序二维码

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

                /* 活动参数 */
                activityName: '', // 活动名称
                activityImage: 'https://picsum.photos/400/400' //活动封面
            }
        }
    },
    computed: {
        ...mapState(['userInfo'])
    },
    methods: {
        async getUserInfo() {
            const { data } = await this.SellerService.GetSellerHome({ userId: this.userInfo.userId })
            this.posterData.image = this.posterData.image.length > 12 ? this.posterData.image : 'https://static.caimei365.com/app/img/icon/default-head-new.png' // 用户头像
            this.posterData.qrCode = data.qrCode // 用户二维码
            this.posterData.linkMan = data.linkMan // 用户名
            this.posterData.contractMobile = data.contractMobile // 用户手机号
        },
        // 分享操作
        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) {
                    await this.getUserInfo()
                    this.posterData = { ...this.posterData, ...this.data }
                    const { data: qrCodeImage } = await generateWxUnlimited(this, {
                        pagePath: this.posterData.path,
                        queryStr: 'sellerUserId=' + this.userInfo.userId + '&id=' + this.posterData.id
                    })
                    this.posterData.qrCodeImage = qrCodeImage
                    switch (this.type) {
                        case 'product':
                            await this.createProductPoster()
                            break
                    }
                    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, productName, activityName } = this.posterData

            // 处理价格
            let priceText = ''
            if (this.type === 'product') {
                if (productPrice) {
                    priceText += productPrice
                }
                if (productOriginPrice) {
                    priceText += '￥' + productOriginPrice
                }
            }
            textArray.push(priceText)
            // 处理产品名称
            if (productName) {
                const nameStr = productName || 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 [error, result] = await uni.downloadFile({ url: this.posterData.productImage })
                const [error2, result2] = await uni.downloadFile({ url: this.posterData.qrCodeImage })
                this.posterData.productImage = result.tempFilePath
                this.posterData.qrCodeImage = result2.tempFilePath
                const ctx = uni.createCanvasContext('poster', this)
                const drawPoster = new DrawPoster(ctx, {
                    avatarUrl: this.posterData.avatar,
                    userName: this.posterData.username,
                    coverUrl: this.posterData.productImage,
                    ewmUrl: this.posterData.qrCodeImage,
                    textArray: this.generateTextArray(),
                    image: this.posterData.image,
                    qrCode: this.posterData.qrCode, // 用户二维码
                    linkMan: this.posterData.linkMan, // 用户名
                    contractMobile: this.posterData.contractMobile.replace(/(?=(\d{4})+$)/g,"-") // 用户手机号
                })
                return await drawPoster.draw()
            } catch (e) {
                throw e
            }
        }
    }
}
</script>

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