<template>
    <div>
        <el-upload
            :action="`${VITE_API_URL}/api/file/upload`"
            :headers="{ Admin: getToken() }"
            multiple
            :before-upload="beforeUpload"
            @progress="uploadProgress"
            @success="handleSuccess"
            :show-file-list="false"
            :accept="accept"
        >
            <el-button
                >上传

                <template #icon>
                    <icon name="el-icon-Upload" />
                </template>
            </el-button>
        </el-upload>
        <div class="flex v-center wrap mt-10">
            <FileList v-model:files="files" :removeEnable="true" />
            <div v-if="loading">
                <el-progress type="circle" :percentage="uploadPercentage" :width="80" />
            </div>
        </div>
    </div>
</template>
<script setup>
import { getToken } from "@/utils/auth";
const { VITE_API_URL } = process.env;

const props = defineProps({
    modelValue: {
        type: Array,
        default: () => [],
    },
    accept: {
        type: String,
        default: "image/*,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/pdf,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,audio/mpeg,audio/mp4a-latm",
    }
});

const emit = defineEmits(["update:modelValue"]);

const files = ref(props.modelValue);

watch(() => props.modelValue, (newValue) => {
    if (newValue) {
        files.value = newValue;
    } else {
        files.value = []
    }
})

const loading = ref(false)
const uploadPercentage = ref(0)
function beforeUpload() {
    uploadPercentage.value = 0
    loading.value = true
}

function uploadProgress(progressEvent) {
    uploadPercentage.value = parseInt(progressEvent.percent)
}

function handleSuccess(data, file) {
    loading.value = false
    if (data.code !== 200) {
        return;
    }
    files.value.push({
        filepath: data.data.filepath,
        orgiinFilename: file.name,
        type: file.raw.type,
        size: file.size,
        docxFilepath: data.data.docxFilepath
    });
    emit("update:modelValue", files.value);
}
</script>