<template>
    <cell :title="label" :required="required">
        <uploader class="abc" slot="label" v-model="fileList" 
        :image-fit="imageFit"
        :disabled="disabled" :max-count="limit" :multiple="false" :preview-size="previewSize" :after-read="handleUpload" @delete="handleDelete"
        :upload-icon="uploadIcon"
        upload-text="上传照片"
        >
            <!-- <img  :style="{width:selfImageWidth,height:selfImageHeight}" alt="" v-if="selfImage"> -->
        </uploader>
    </cell>

</template>

<script>
import mixin from "./mixin";
import { uploadImage } from "@/api/system/common";
import { join } from "lodash";
import { Cell, Uploader } from "vant";
/**
 * 文件上传组件
 */
export default {
    name: "Upload",
    components: { Cell, Uploader },
    mixins: [mixin],
    model: {
        prop: "value",
        event: "change",
    },
    props: {
        uploadIcon: {
            type: String,
            default: 'plus',
        },
        selfImageWidth:String,
        selfImageHeight:String,
        selfImageUrl:{
             type: String,
            default: "fill",
        },
        selfImage: {
            type: Boolean,
            default: false,
        },
        limit: {
            type: Number,
            default: 1,
        },
        imageFit: {
            type: String,
            default: "fill",
        },
        previewSize: Number,
    },
    data() {
        return {
            fileList: this.extractFiles(),
        };
    },
    watch: {
        value() {
            this.fileList = this.extractFiles();
        },
    },
    methods: {
        async handleUpload(file) {
            file.status = "uploading";
            const { code, url } = await uploadImage(file.file);
            if (code === 200) {
                this.$emit("change", this.generateUrl(url));
            } else {
                file.status = "failed";
            }
        },
        handleDelete() {
            if (!this.fileList || this.fileList.length === 0) {
                this.$emit("change", null);
                return;
            }
            const urls = this.fileList.map(({ url }) => url);
            this.$emit("change", urls);
        },
        extractFiles() {
            return (
                this.value
                    ?.split(",")
                    .map((url) => ({ url, status: "done" })) || []
            );
        },
        generateUrl(url) {
            const urls = this.value?.split(",") || [];
            if (url && url.length > 0) {
                urls.push(url);
            }
            return join(urls, ",");
        },
    },
};
</script>
<style scoped>
</style>