<script setup>
import CLOSE_ICON from "../static/icons/close2.png";
import ADDICON from "../static/icons/add.png";
import {uploadFile} from "../utils/uils";
import XImage from "./XImage.vue";
import useUploadLength from "../hooks/useUploadLength.js";

const {size, single, del} = defineProps({
    size: {
        type: String,
        default: "160rpx"
    },
    single: {
        type: Boolean,
        default: false,
    },
    del: {
        type: Boolean,
        default: false,
    }
});
const emits = defineEmits(['success']);
const files = defineModel('files');

if (single) useUploadLength({
    array: files.value,
    length: 1,
})

const upload = async () => {
    uploadFile({
        count: 1,
    }).then(([res]) => {
        const {data} = res;
        if (!single) {
            files.value?.push(data);
        } else {
            files.value = [data];
        }
        emits('success', data);
    })
}
</script>

<template>
    <view class="!flex gap-[12rpx] flex-wrap">
        <view class="x-upload" @click="upload" v-if="!single || single && files?.length < 1">
            <image class="!size-[28rpx]" :src="ADDICON"></image>
            <view>上传图片</view>
        </view>

        <view class="!relative" v-for="(v, index) in files" :key="v">
            <image v-if="del" @click="files.splice(index, 1)" :src="CLOSE_ICON"
                   class="!size-[48rpx] !absolute !z-10 !top-0 !right-0"
                   mode="aspectFill"></image>
            <x-image
                :style="{
            width: size,
            height: size,
        }"
                class="border border-[rgb(229,230,235)]"
                :src="v"
                :list="[v]">
            </x-image>
        </view>
    </view>
</template>

<style scoped lang="scss">
.x-upload {
    border: 1px dashed rgb(229, 230, 235);
    background-color: #F2F3F5;
    width: v-bind(size);
    height: v-bind(size);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 22rpx;
    font-size: 24rpx;
    border-radius: 4px;
}
</style>
