<script setup lang="ts">
import { shareApi } from '@/api/agent/promotion'
import { getHeaderImage } from '@/utils/common'

const { screenWidth } = uni.getSystemInfoSync()

const qrcodeRef = ref()

const userInfo = ref<{ head_img: string; id: number; phone: string; nickname: string }>({
    head_img: '',
    id: 0,
    phone: '',
    nickname: ''
})

const showSaveImgWin = ref(false)

const canvasToTempFilePath = ref('')

const oncomplete = ({ success }: { success: boolean }) => {
    if (!success) return
    qrcodeRef.value.toTempFilePath({
        success: ({ tempFilePath }: { tempFilePath: string }) => {
            createCanvas(tempFilePath)
        }
    })
}

const saveShareImg = () => {
    uni.saveImageToPhotosAlbum({
        filePath: canvasToTempFilePath.value,
        success: () => {
            showSaveImgWin.value = false
            uni.showToast({
                title: '保存成功，快去分享到朋友圈吧~',
                icon: 'none',
                duration: 1000
            })
        },
        fail: () => {
            uni.showToast({
                title: '保存失败，请检查是否授权保存图片权限~',
                icon: 'none',
                duration: 1000
            })
        }
    })
}

const createCanvas = (tempFilePath: string) => {
    uni.getImageInfo({
        src: getHeaderImage(userInfo.value.head_img),
        success: ({ path }) => {
            const ctx = uni.createCanvasContext('shareCanvas', this)
            const canvasWidth = screenWidth - 30
            const canvasHeight = (screenWidth - 30) * 1.62

            ctx.translate(0, 0)
            ctx.beginPath()
            ctx.drawImage('../../static/invite.jpg', 0, 0, canvasWidth, canvasHeight)
            ctx.restore()

            ctx.beginPath()
            ctx.translate(0, canvasHeight - 78)
            ctx.beginPath()
            ctx.setFillStyle('rgba(0, 0, 0, 0.24)')
            ctx.fillRect(0, 0, canvasWidth, 78)
            ctx.save()

            ctx.save()
            ctx.beginPath()
            ctx.arc(40, 40, 22, 0, 2 * Math.PI, false)
            ctx.setFillStyle('rgba(0, 0, 0, 0.29)')
            ctx.clip()
            ctx.drawImage(path, 19, 19, 42, 42)
            ctx.restore()

            ctx.font = 'normal normal 13px sans-serif'
            ctx.setFillStyle('#ffffff')
            ctx.fillText('用户昵称', 71, 37)

            ctx.font = 'normal normal 12px sans-serif'
            ctx.setFillStyle('#ffffff')
            ctx.fillText(`${userInfo.value.nickname}`, 71, 54)
            ctx.save()

            ctx.beginPath()
            const x = canvasWidth - 78,
                y = 7,
                width = 64,
                height = 64,
                radius = 4
            ctx.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 1.5)
            ctx.lineTo(x + width - radius, y)
            ctx.arc(x + width - radius, y + radius, radius, Math.PI * 1.5, Math.PI * 2)
            ctx.lineTo(x + width, y + height - radius)
            ctx.arc(x + width - radius, y + height - radius, radius, 0, Math.PI * 0.5)
            ctx.lineTo(x + radius, y + height)
            ctx.arc(x + radius, y + height - radius, radius, Math.PI * 0.5, Math.PI)
            ctx.lineTo(x, y + radius)
            ctx.setFillStyle('#ffffff')
            ctx.fill()
            ctx.closePath()

            ctx.beginPath()
            ctx.drawImage(tempFilePath, x + 3, y + 3, 58, 58)
            ctx.restore()

            ctx.draw(false, () => {
                uni.canvasToTempFilePath({
                    width: canvasWidth,
                    height: canvasHeight,
                    destWidth: canvasWidth * 2,
                    destHeight: canvasHeight * 2,
                    canvasId: 'shareCanvas',
                    quality: 1,
                    success: ({ tempFilePath }) => {
                        canvasToTempFilePath.value = tempFilePath
                    },
                    complete: () => {
                        uni.hideLoading()
                        setTimeout(() => uni.hideToast(), 1000)
                    }
                })
            })
        }
    })
}

// const shareToFriends = () => {
//     plus.share.sendWithSystem(
//         { content: '分享内容', href: 'https://www.dcloud.io/' },
//         function () {
//             console.log('分享成功')
//         },
//         function (e) {
//             console.log('分享失败：' + JSON.stringify(e))
//         }
//     )
// }

onLoad(() => {
    uni.showLoading({ title: '加载中...' })
    shareApi().then((res) => {
        const { data } = res as { data: { head_img: string; id: number; phone: string; nickname: string } }
        userInfo.value = data
        qrcodeRef.value.make()
    })
})
</script>

<template>
    <view class="invite">
        <ex-header title="邀请好友" />

        <uv-qrcode
            ref="qrcodeRef"
            class="qrcode"
            size="174rpx"
            :value="`http://pos-admin.lingji.vip/#/sign?p=${userInfo.phone}&t=a`"
            @complete="oncomplete"
        />

        <canvas canvas-id="shareCanvas" :style="{ width: `${screenWidth - 30}px`, height: `${(screenWidth - 30) * 1.62}px` }" hidpi />
        <image @longpress="showSaveImgWin = true" style="width: 100%; height: 100%" :src="canvasToTempFilePath" />

        <view class="option-box flex-center-between">
            <view class="btn" @click="showSaveImgWin = true">保存图片</view>

            <!-- <view class="option-box-item">
                <view class="img-box">
                    <image src="http://cdn-pos.lingji.vip/static/share/circle_of_friends.png" mode="widthFix" />
                </view>
                <view class="label">朋友圈</view>
            </view>
            <view class="option-box-item" @click="shareToFriends()">
                <view class="img-box">
                    <image src="http://cdn-pos.lingji.vip/static/share/wechart.png" mode="widthFix" />
                </view>
                <view class="label">微信</view>
            </view>
            <view class="option-box-item" @click="downloadFn()">
                <view class="img-box">
                    <image src="http://cdn-pos.lingji.vip/static/share/download.png" mode="widthFix" />
                </view>
                <view class="label">保存</view>
            </view> -->
        </view>

        <u-modal
            :show="showSaveImgWin"
            show-cancel-button
            close-on-click-overlay
            @cancel="showSaveImgWin = false"
            @close="showSaveImgWin = false"
            @confirm="saveShareImg"
        >
            确定要保存图片吗？
        </u-modal>
    </view>
</template>

<style lang="scss" scoped>
.invite {
    width: 100vw;
    min-height: 100vh;
    padding: 30rpx;

    .qrcode {
        position: absolute;
        top: -100%;
    }

    .option-box {
        padding: 46rpx 37rpx 102rpx;

        &-item {
            .img-box {
                @extend .flex;
                width: 104rpx;
                height: 104rpx;
                overflow: hidden;
                border-radius: 50%;
                margin-bottom: 10rpx;
                background-color: #f2f6ff;

                image {
                    width: 66rpx;
                }
            }

            .label {
                width: 100%;
                color: #000;
                font-size: 28rpx;
                font-weight: 400;
                letter-spacing: 0;
                line-height: 40rpx;
                text-align: center;
            }
        }

        .btn {
            width: 100%;
            color: #ffffff;
            font-size: 32rpx;
            font-weight: 500;
            letter-spacing: 0;
            line-height: 40rpx;
            text-align: center;
            padding: 20rpx 0;
            border-radius: 8rpx;
            background: linear-gradient(90deg, #4778ff 0%, #4778ffb8 100%);
        }
    }
}
</style>
