<template>
    <!-- 全局图片下载 -->
    <up-upload
        :width="width + 'rpx'"
        :height="height + 'rpx'"
        :fileList="getFileList"
        @afterRead="afterRead"
        @delete="deletePic"
        multiple
        :maxCount="10"
        :previewFullImage="true"
    >
        <slot>
            <view class="upload-button" :style="getUploadButtonSize">
                <uni-icons :type="uploadIcon" :size="24" color="rgba(0, 0, 0, 0.4)"></uni-icons>
            </view>
        </slot>
    </up-upload>
</template>

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

const es = defineEmits(['handleUpload'])
const ps = defineProps({
    fileList: {
        type: Array,
        default: () => []
    },
    width: {
        type: [String, Number],
        default: '155'
    },
    height: {
        type: [String, Number],
        default: '155'
    },
    url: {
        type: String,
        default: ''
    },
    uploadIcon: {
        type: String,
        default: 'plusempty'
    }
})
const getUploadButtonSize = computed(() => {
    return {
        width: ps.width + 'rpx',
        height: ps.height + 'rpx'
    }
})

const fileList = ref(ps.fileList)
const getFileList = computed(() => {
    return fileList.value.map((item) => {
        return { ...item, url: item.fileUrl }
    })
})
// 删除图片
const deletePic = (event) => {
    fileList.value.splice(event.index, 1)
}
// 新增图片
const afterRead = async (event) => {
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    let lists = [].concat(event.file)
    let fileListLen = fileList.value.length
    lists.map((item) => {
        fileList.value.push({
            ...item,
            status: 'uploading',
            message: '上传中'
        })
    })
    for (let i = 0; i < lists.length; i++) {
        const arrayBuffer = new Uint8Array(lists[i].url) //先将本地图片路径转换成array类型
        const binary = arrayBufferToBinary(arrayBuffer)

        // const binary = uni.getFileSystemManager().readFileSync(lists[i].url, 'binary')
        // const imgBlob = await fetch(lists[i].url).then((r) => r.blob())
        // const imgFile = new File([imgBlob], lists[i].name, { type: imgBlob.type })
        // let form = new FormData()
        // form.append('file', imgFile)
        const res = await uploadFilePromise(lists[i].url, binary)
        if (res.code == 200) {
            fileList.value.splice(fileListLen, 1, {
                ...res.data
            })
            fileListLen++
        } else {
            uni.$message.showToast(res.message || '请求错误')
        }
    }
}

function arrayBufferToBinary(buffer) {
    // 创建一个二进制编码器
    const encoder = new TextEncoder()
    // 将ArrayBuffer视为UTF-8字符串的字节序列
    const view = new Uint8Array(buffer)
    // 使用二进制编码器将字节序列转换为字符串
    return encoder.encode(new Uint8Array(buffer)).toString()
}
watch(
    fileList,
    (value) => {
        es('handleUpload', value)
    },
    { deep: true }
)
const uploadFilePromise = (url, binary) => {
    return new Promise((resolve, reject) => {
        uni.uploadFile({
            url: ps.url,
            name: 'file',
            filePath: url,
            file: binary,
            formData: {
                file: binary
            },
            success: (res) => {
                resolve(JSON.parse(res.data))
            }
        })
    })
}
</script>
<style lang="scss" scoped>
.upload-button {
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f3f3f3;
}
</style>
