<template>
    <view class="share-popup">
        <!-- 弹窗 -->
        <uni-popup ref="sharePopup" type="bottom" @change="popupChange">
            <view class="popup-content">
                <view class="title" v-if="title" v-text="title"></view>
                <view class="content">
                    <view class="row">
                        <button class="share item" open-type="share" @click="close">
                            <view class="icon-image"><image :src="staticUrl + 'icon-share-wechat.png'"></image></view>
                            <text class="label">微信</text>
                        </button>
                        <view class="poster item" @click="createPoster" v-if="!posterUrl">
                            <view class="icon-image"><image :src="staticUrl + 'icon-poster.png'"></image></view>
                            <text class="label">生成海报</text>
                        </view>
                        <view class="poster item" @click="savePoster" v-else>
                            <view class="icon-image"><image :src="staticUrl + 'icon-download.png'"></image></view>
                            <text class="label">保存相册</text>
                        </view>
                    </view>
                    <tui-divider :height="64"></tui-divider>
                    <view class="cancel" @click="close">取消</view>
                </view>
            </view>
        </uni-popup>

        <canvas canvas-id="poster" id="poster" class="canvas"></canvas>

        <!-- 海报 -->
        <view class="poster-container" v-show="visiable">
            <!-- 画布 -->
            <image :src="posterUrl" class="poster-image"></image>
        </view>
    </view>
</template>

<script>
import { mapGetters } from 'vuex'
import { getUserProfile } from '@/common/auth.js'
export default {
    props: {
        title: {
            type: String,
            default: ''
        },
        data: {
            type: Object,
            default: () => {}
        },
        type: {
            type: String,
            default: 'normal',
            validator: value => {
                return ['product', 'normal'].indexOf(value) > -1
            }
        }
    },
    data() {
        return {
            visiable: false,
            imageList: [],
            posterUrl: '',
            // 海报数据信息
            posterData: {
                avatar: '',
                username: '',
                porductName: '',
                productPrice: '',
                productOriginPrice: '',
                productImage: '',
                qrCodeImage: ''
            }
        }
    },
    computed: {
        ...mapGetters(['systemInfo'])
    },
    methods: {
        // 绘制海报  初始化
        initDrawPoster() {
            this.downLoadImageTask()
        },

        // 下载图片任务
        async downLoadImageTask() {
            const { avatar, productImage, qrCodeImage } = this.posterData
            // 图片资源链接
            const bgImageUrl = this.staticUrl + 'bg-share-01.png'
            const avatarUrl = avatar || this.staticUrl + 'icon-join-us.png'
            let coverUrl = productImage || this.staticUrl + 'icon-share.png'
            let ewmUrl = qrCodeImage || this.staticUrl + 'icon-ewm-hehe.jpg'
            if (this.type === 'normal') {
                coverUrl = this.staticUrl + 'icon-share.png'
                ewmUrl = this.staticUrl + 'icon-ewm-hehe.jpg'
            }

            // 下载图片任务
            const taskList = [
                this.downloadImage(bgImageUrl),
                this.downloadImage(avatarUrl),
                this.downloadImage(coverUrl),
                this.downloadImage(ewmUrl)
            ]

            // 执行下载图片
            try {
                this.imageList = await Promise.all(taskList)
                this.drawPoster()
            } catch (e) {
                console.log(e)
            }
        },

        // 绘制海报
        drawPoster() {
            const windowWidth = this.systemInfo.windowWidth
            // const scale = this.systemInfo.windowWidth / 750
            const scale = 1
            var ctx = uni.createCanvasContext('poster', this)
            // 绘制背景
            ctx.drawImage(this.imageList[0].tempFilePath, 0, 0, 540 * scale, 878 * scale)
            ctx.save()

            // 绘制用户信息
            this.drawPosterHead(ctx, scale)

            // 绘制白色矩形区域
            ctx.beginPath()
            ctx.rect(20 * scale, 154 * scale, 500 * scale, 704 * scale)
            ctx.setFillStyle('#FFFFFF')
            ctx.fill()
            ctx.clip()

            const type = this.type
            // 绘制底部内容
            if (!type || type === 'normal') {
                this.drawPosterFoot(ctx, scale)
            } else {
                this.drawGoodsInfo(ctx, scale)
            }

            ctx.restore()
            ctx.draw(true, () => {
                uni.canvasToTempFilePath(
                    {
                        canvasId: 'poster',
                        success: res => {
                            this.posterUrl = res.tempFilePath
                            this.visiable = true
                        },
                        complete: () => {
                            uni.hideLoading()
                        }
                    },
                    this
                )
            })
        },

        // 绘制海报头部
        drawPosterHead(ctx, scale) {
            const { username } = this.posterData
            // 绘制头像
            ctx.beginPath()
            ctx.arc(40 * scale + (90 * scale) / 2, 32 * scale + (90 * scale) / 2, (90 * scale) / 2, 0, 2 * Math.PI)
            ctx.setFillStyle('#fff')
            ctx.fill()
            ctx.clip()
            ctx.drawImage(this.imageList[1].tempFilePath, 40 * scale, 32 * scale, 90 * scale, 90 * scale)
            ctx.restore()
            ctx.save()
            // 绘制用户名和推荐语
            ctx.setFillStyle('#FFFFFF')
            ctx.font = 'bold 10px sans-serif'
            ctx.setFontSize(30 * scale)
            ctx.fillText(username, 146 * scale, (30 + 34) * scale, 350 * scale)
            ctx.font = 'normal 10px sans-serif'
            ctx.setFontSize(24 * scale)
            let txt = '强烈为你推荐该商城'
            if (this.type === 'product') {
                txt = '强烈为你推荐该商品'
            }
            ctx.fillText(txt, 146 * scale, (87 + 24) * scale, 350 * scale)
        },

        // 绘制海报底部
        drawPosterFoot(ctx, scale) {
            // 绘制中心图片
            ctx.drawImage(this.imageList[2].tempFilePath, 40 * scale, 174 * scale, 460 * scale, 460 * scale)
            // 绘制底部
            ctx.setFontSize(24 * scale)
            ctx.setFillStyle('#333')
            ctx.fillText('护肤上颜选，正品', 60 * scale, (710 + 24) * scale)
            ctx.fillText('有好货', 60 * scale, (710 + 24 + 40) * scale)
            // 绘制二维码
            ctx.drawImage(this.imageList[3].tempFilePath, 364 * scale, 690 * scale, 116 * scale, 116 * scale)
        },

        // 绘制商品信息
        drawGoodsInfo(ctx, scale) {
            // 参数处理
            let { porductName, productPrice, productOriginPrice } = this.posterData
            productPrice = productPrice.toFixed(2)
            if (productOriginPrice) {
                productOriginPrice = '￥' + productOriginPrice.toFixed(2)
            }
            const porductNames = this.getProductNames(porductName)

            console.log(porductNames)

            // 绘制中心图片
            ctx.drawImage(this.imageList[2].tempFilePath, 40 * scale, 174 * scale, 460 * scale, 460 * scale)
            // 绘制价格符号
            ctx.setFillStyle('#FF457B')
            ctx.setFontSize(24 * scale)
            ctx.fillText('￥', 40 * scale, (680 + 24) * scale)
            // 绘制购买价格
            ctx.setFontSize(40 * scale)
            ctx.fillText(productPrice, 62 * scale, (665 + 40) * scale)
            // 绘制原价
            if (productOriginPrice) {
                ctx.setFillStyle('#999')
                ctx.setFontSize(24 * scale)
                ctx.fillText(productOriginPrice, 200 * scale, (680 + 24) * scale)
                let m = ctx.measureText(productOriginPrice)
                ctx.fillRect(200 * scale, (680 + 16) * scale, parseInt(m.width), 1)
            }
            // 绘制商品标题
            ctx.setFillStyle('#333')
            ctx.setFontSize(26 * scale)

            porductNames.forEach((text, index) => {
                text = index === 1 ? text.slice(0, text.length - 1) + '...' : text
                ctx.fillText(text, 40 * scale, (732 + 26 + 40 * index) * scale)
            })
            // 绘制商品二维码
            ctx.drawImage(this.imageList[3].tempFilePath, 384 * scale, 702 * scale, 116 * scale, 116 * scale)
        },

        // 处理产品名称
        getProductNames(porductName) {
            const list = []
            if (porductName.length > 12) {
                for (let i = 0; i < porductName.length; i += 12) {
                    if (list.length < 2) {
                        list.push(porductName.slice(i, i + 12))
                    }
                }
            } else {
                list.push(porductName)
            }
            return list
        },

        // 下载图片
        downloadImage(url) {
            return new Promise((resolve, reject) => {
                uni.downloadFile({
                    url: url,
                    success(data) {
                        resolve(data)
                    },
                    fail(err) {
                        reject(err)
                    }
                })
            })
        },

        open() {
            this.$refs.sharePopup.open()
            this.$emit('open')
        },
        close() {
            this.$refs.sharePopup.close()
            this.$emit('close')
            this.visiable = false
        },
        popupChange(e) {
            if (!e.show) {
                this.visiable = false
                this.posterUrl = ''
            }
            this.$emit('change', e)
        },
        async createPoster() {
            // 合并海报数据
            this.posterData = { ...this.posterData, ...this.data }
            try {
                // 从本地缓存中获取微信用户基本信息
                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
                uni.showLoading({
                    mask: true,
                    title: '正在为您生成海报'
                })
                // 绘制海报
                this.initDrawPoster()
            } catch (e) {
                //TODO handle the exception
                uni.hideLoading()
            }
        },
        savePoster() {
            console.log('保存图片到本地')
            uni.saveImageToPhotosAlbum({
                filePath: this.posterUrl,
                success: res => {
                    this.close()
                    this.$emit('saveSuccess', this.posterUrl)
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.canvas {
    position: fixed;
    left: -600px;
    top: 0;
    width: 540px;
    height: 878px;
    opacity: 0;
}

.poster-container {
    z-index: 100;
    position: fixed;
    top: 80rpx;
    left: 50%;
    transform: translateX(-50%);
    width: 540rpx;
    height: 878rpx;
    background-color: #fff;
    overflow: hidden;

    .poster-image {
        display: block;
        width: 540rpx;
        height: 878rpx;
    }
}

.popup-content {
    position: relative;
    padding: 40rpx;
    padding-bottom: 0;
    border-radius: 16rpx 16rpx 0 0;
    background-color: #fff;

    &::after {
        position: absolute;
        content: '';
        width: 100%;
        height: 80rpx;
        bottom: -80rpx;
        left: 0;
        background-color: #fff;
    }

    .title {
        font-size: 34rpx;
        color: #666;
        text-align: center;
        padding-bottom: 28rpx;
    }

    .content {
        .row {
            @extend .cm-flex-around;
        }

        .item {
            @extend .cm-flex-center;
            flex-direction: column;

            .label {
                color: #333;
                font-size: 26rpx;
                margin-top: 16rpx;
            }

            .icon-image {
                @extend .cm-flex-center;
                width: 100rpx;
                height: 100rpx;
                background-color: #f7f7f7;

                image {
                    width: 64rpx;
                    height: 64rpx;
                    display: block;
                }
            }

            &.share {
                line-height: inherit;
                padding: 0;
                margin: 0;
                border: 0;
                background: transparent;
                &::after {
                    border: 0;
                }
            }
        }
        .cancel {
            font-size: 28rpx;
            color: #666;
            font-weight: bold;
            text-align: center;
            padding-bottom: 32rpx;
        }
    }
}
</style>
