<template>
    <view class="qrcode">
        <view class="core">
            <view class="code">
                <image class="image" :src="src" :show-menu-by-longpress="true" v-if="src" />
                <u-loading :size="60" mode="flower" v-else />
            </view>
            <view>长按识别二维码</view>
        </view>
        <view class="operation">
            <view>
                <button class="part bg-white" open-type="share">
                    <text class="icon share"></text>
                    <text class="label">分享</text>
                </button>
            </view>
            <view>
                <button class="part-photo bg-white" :disabled="isDisabled" @click="saveToAlbum">
                    <text class="icon download"></text>
                    <text class="label">保存到相册</text>
                </button>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, unref } from 'vue'
import { onShareAppMessage } from '@dcloudio/uni-app'
import { storeToRefs } from 'pinia'
import { useLockFn } from '@/hooks/useLockFn'
import { useUserStore } from '@/stores/user'
import { getDistributorQrcode } from '@/api/distributor_center'

const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

const src = ref('')
const isDisabled = computed(() => !unref(src))

const { lockFn: fetchShareQrcode } = useLockFn(async () => {
    const base64Src = await getDistributorQrcode({ distributorId: unref(userInfo).distributorId })
    src.value = base64Src
})
onMounted(() => fetchShareQrcode())

onShareAppMessage(() => {
    return {
        title: '粤好生活',
        path: `/pages/index/index?scene=${unref(userInfo).distributorId}`,
        imageUrl: '../../../static/images/index.jpg'
    }
})
const saveToAlbum = () => {
    uni.getSetting({
        success: res => {
            let authKey = ''
            // #ifdef MP-WEIXIN
            authKey = 'scope.writePhotosAlbum'
            // #endif

            // #ifdef MP-TOUTIAO
            authKey = 'scope.album'
            // #endif

            // 无权限
            if (!res.authSetting[authKey]) {
                uni.authorize({
                    scope: authKey,
                    success: async () => {
                        saveImg()
                    },
                    // 拒绝授权
                    fail: () => {
                        uni.showModal({
                            title: '您已拒绝获取相册权限',
                            content: '是否进入权限管理，调整授权',
                            success: res => {
                                if (res.confirm) {
                                    uni.openSetting({
                                        success: res => {
                                            res.authSetting[authKey]
                                                ? saveImg()
                                                : uni.$u.toast('已取消')
                                        }
                                    })
                                } else if (res.cancel) {
                                    uni.$u.toast('已取消')
                                }
                            }
                        })
                    }
                })
            } else {
                // 有权限
                saveImg()
            }
        }
    })
}
/**保存图片 */
async function saveImg() {
    try {
        const filePath = (await base64ToSave()) as string
        uni.saveImageToPhotosAlbum({
            filePath,
            success: () => {
                uni.$u.toast('图片保存成功')
                removeSave()
            },
            fail: res => {
                console.log(res)

                uni.$u.toast('图片保存失败')
            }
        })
    } catch (error) {}
}
/**base64转图片 */
function base64ToSave() {
    const fsm = uni.getFileSystemManager()
    return new Promise((resolve, reject) => {
        const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(unref(src)) || []
        if (!format) {
            reject(new Error('图片格式错误'))
        }
        const filePath = wx.env.USER_DATA_PATH + '/img.jpg'
        const buffer = uni.base64ToArrayBuffer(bodyData)
        fsm.writeFile({
            filePath,
            data: buffer,
            encoding: 'base64',
            success: () => {
                resolve(filePath)
            },
            fail: () => {
                reject(new Error('图片写入失败'))
            }
        })
    })
}
/**删除文件 */
function removeSave(format = 'jpeg') {
    return new Promise(resolve => {
        const fsm = uni.getFileSystemManager()
        const filePath = wx.env.USER_DATA_PATH + '/img.jpg'
        fsm.unlink({
            filePath,
            success: () => {
                console.log('删除成功')
            }
        })
    })
}
</script>
<style lang="scss" scoped>
.qrcode {
    height: 100vh;
    background: #fff;
    .core {
        @include center;
        flex-direction: column;
        padding: 40rpx 0;
        background-color: $white;

        .code {
            @include center;
            width: 500rpx;
            height: 500rpx;
            margin-bottom: 40rpx;

            .image {
                width: 100%;
                height: 100%;
            }
        }
    }

    .operation {
        @include center;

        > view {
            flex: 1;
            @include flex-center;
            margin-top: 40rpx;

            .icon {
                width: 80rpx;
                height: 80rpx;
                background-repeat: no-repeat;
                background-size: 100%;
            }

            .label {
                font-size: 28rpx;
            }

            .part {
                @include flex-column;

                .share {
                    background-image: url('~@/static/images/share-friend.png');
                }
            }

            .part-photo {
                @include flex-center;

                .download {
                    background-image: url('~@/static/images/download.png');
                }
            }
        }
    }
}
</style>
