<template>
    <view>
        <view class="cHcontainer">
            <image class="bgPic" :src="bgPic" v-if="bgPic"></image>
            <view class="emptyBg" v-else></view>
        </view>
        <view class="btnContainer">
            <button class="cbtn" data-way="avatar" open-type="chooseAvatar" @chooseavatar="getAvatar" @getuserinfo="getAvatar">使用头像</button>
            <button @tap="chooseImage" class="cbtn" data-way="album">选择图片</button>
            <button @tap="nextPage" class="cbtn" :disabled="!picChoosed">下一步</button>
        </view>
    </view>
</template>

<script>
var app = getApp();
export default {
    data() {
        return {
            bgPic: null,
            picChoosed: false
        };
    },
    methods: {
        assignPicChoosed: function () {
            if (this.bgPic) {
                this.picChoosed=true;
            } else {
                this.picChoosed=false;
            }
        },

        getAvatar: function (e) {
            const url = e?.detail?.avatarUrl || e?.detail?.userInfo?.avatarUrl;
            if (!url) {
                uni.showToast({ title: '未获取到头像权限', icon: 'none', duration: 2000 });
                return;
            }
            let finalUrl = url;
            // 仅对微信头像网络地址做尺寸升级，避免破坏本地临时路径
            if (/qlogo\.cn/.test(url)) {
                finalUrl = url.replace(/\/(\d+)$/, '/0');
            }
            this.bgPic = finalUrl;
            this.assignPicChoosed();
        },

        chooseImage: function (e) {
            var that = this;
            uni.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: [e.target.dataset.way],
                success: (e) => {
                    const img = e?.tempFilePaths?.[0];
                    if (!img) {
                        uni.showToast({ title: '未选择图片', icon: 'none', duration: 2000 });
                        that.assignPicChoosed();
                        return;
                    }
                    that.bgPic = img;
                    that.assignPicChoosed();
                },
                fail: function (e) {
                    that.assignPicChoosed();
                },
                complete: function (e) {
                    that.assignPicChoosed();
                }
            });
        },

        nextPage: function () {
            app.globalData.bgPic = this.bgPic;
            uni.navigateTo({
                url: '../imageeditor/imageeditor'
            });
        }
    }
};
</script>
<style>
@import './index.css';
</style>
