<template>
    <view class="upload">
        <view class="upload-image">
            <image src="/static/image/login/upload.png" />
            <view class="upload-del">
                <uni-icons type="closeempty" :size="14" color="#fff"></uni-icons>
            </view>
        </view>
        <view class="upload-button" @tap="handleUpload">
            <uni-icons type="plusempty" :size="24" color="rgba(0, 0, 0, 0.4)"></uni-icons>
        </view>
    </view>
</template>

<script setup>
import { ref, reactive } from 'vue'

//上传图片
const handleUpload = () => {
    // 调用拍照/选择图片
    // 选择图片条件编译
    // #ifdef H5 || APP-PLUS
    // 微信小程序从基础库 2.21.0 开始， wx.chooseImage 停止维护，请使用 uni.chooseMedia 代替
    uni.chooseImage({
        count: 1,
        success: (res) => {
            // 文件路径
            const tempFilePaths = res.tempFilePaths
            // 上传
            uploadFile(tempFilePaths[0])
        }
    })
    // #endif

    // #ifdef MP-WEIXIN
    // uni.chooseMedia 仅支持微信小程序端
    uni.chooseMedia({
        // 文件个数
        count: 1,
        // 文件类型
        mediaType: ['image'],
        success: (res) => {
            // 本地路径
            const { tempFilePath } = res.tempFiles[0]
            // 上传
            uploadFile(tempFilePath)
        }
    })
    // #endif
}

// 文件上传-兼容小程序端、H5端、App端
const uploadFile = (file) => {
    // 文件上传
    uni.uploadFile({
        url: '/member/profile/avatar',
        name: 'file',
        filePath: file,
        success: (res) => {
            if (res.statusCode === 200) {
                const avatar = JSON.parse(res.data).result.avatar
                uni.showToast({ icon: 'success', title: '更新成功' })
            } else {
                uni.showToast({ icon: 'error', title: '出现错误' })
            }
        }
    })
}
</script>
<style lang="scss" scoped>
.upload {
    display: flex;
    flex-wrap: wrap;
    &-image {
        position: relative;
        margin-right: 16rpx;
        image {
            width: 160rpx;
            height: 160rpx;
        }
    }
    &-del {
        position: absolute;
        top: 0;
        right: 0;
        background: rgba(0, 0, 0, 0.6);
        width: 32rpx;
        height: 32rpx;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    &-button {
        width: 160rpx;
        height: 160rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f3f3f3;
    }
}
</style>
