<template>
    <!-- 这里不能在van-uploader里面使用v-if来切换button，van-uploader的解析问题，会直接显示空白 -->
    <van-uploader v-if="showButton" :readonly="readonly" :deletable="!readonly" accept="image/*" :max-count="limitCount" :mutiple="multiple" :show-upload="showUpload"
    :model-value="photos" :before-read="beforeRead" :after-read="afterRead" @update:model-value="update" max-size="5 * 1024 * 1024">
        <van-button v-if="!readonly" type="primary" size="small" icon="plus">上传图片</van-button>
    </van-uploader>
    <van-uploader v-else :readonly="readonly" :deletable="!readonly" accept="image/*" :max-count="limitCount" :mutiple="multiple" :show-upload="showUpload"
    :model-value="photos" :before-read="beforeRead" :after-read="afterRead" @update:model-value="update" :max-size="5 * 1024 * 1024" @oversize="onOversize">
    </van-uploader>
</template>

<script lang="ts">
import { defineComponent, getCurrentInstance } from 'vue'
import { computedAsync } from '@vueuse/core'
import { UploadPhoto } from '~/types'
import { UpyunAccess } from '~/utils/upyun'
import {Uploader, Button, showFailToast} from 'vant'
import {MediaHelper} from "~/utils";

export default defineComponent({
    name: 'native-photo-uploader',
    props: ['modelValue', 'showButton', 'beforeRead', 'afterRead', 'readonly', 'limitCount', 'multiple', 'showUpload'],
    emits: ['update:modelValue', 'choose'],
    components: {
        [Uploader.name]: Uploader,
        [Button.name]: Button
    },
    setup(props) {
        const instance = getCurrentInstance();
        const photos = computedAsync(async () => {
            return await Promise.all(props.modelValue.map(async ({url, ...rest}: Partial<UploadPhoto>) => {
                if(url && !url.includes('?')) {
                    url = await UpyunAccess.getSign(url);
                }
                return {url, ...rest};
            }))
        });

        const update = async (value: Partial<UploadPhoto>[]) => {
            let deleted = props.modelValue.filter(x => !value.includes(x))
            await MediaHelper.remove(deleted);
            instance?.emit('update:modelValue', value);
        }
        const onOversize = (file: File) => {
          showFailToast('文件大小不能超过5MB!');
        };
        
        return {photos, update, onOversize}
    }
})

</script>
