<template>
	<div class="pi-upload-file">
		<el-upload
			:disabled="disabled"
			:auto-upload="autoUpload"
			:action="action"
			:name="name"
			:data="data"
			:http-request="request"
			v-model:file-list="defaultFileList"
			:show-file-list="showFileList"
			:drag="drag"
			:accept="accept"
			:multiple="multiple"
			:limit="limit"
			:before-upload="before"
			:on-success="success"
			:on-error="error"
			:on-preview="handlePreview"
			:on-exceed="handleExceed">
			<slot>
				<el-button type="primary" :disabled="disabled">上传</el-button>
			</slot>
			<template #tip>
				<div v-if="tip" class="el-upload__tip">{{tip}}</div>
			</template>
		</el-upload>
		<span style="display:none!important"><el-input v-model="value"></el-input></span>
	</div>
</template>

<script setup>
import config from "@/config/upload"
import {ref, watch, onMounted, getCurrentInstance} from "vue";
const props = defineProps({
	modelValue: { type: [String, Array], default: "" },
	tip: { type: String, default: "" },
	action: { type: String, default: "" },
	api: { type: Function, default: () => {} },
	name: { type: String, default: config.filename },
	data: { type: Object, default: () => {} },
	accept: { type: String, default: "" },
	maxSize: { type: Number, default: config.maxSize },
	limit: { type: Number, default: 0 },
	autoUpload: { type: Boolean, default: true },
	showFileList: { type: Boolean, default: true },
	drag: { type: Boolean, default: false },
	multiple: { type: Boolean, default: true },
	disabled: { type: Boolean, default: false },
	onSuccess: { type: Function, default: () => { return true } }
})

const emit = defineEmits(['update:modelValue'])
const {proxy} = getCurrentInstance()
let value = ref('')
let defaultFileList = ref([])

watch(() => props.modelValue, (val) => {
	if(Array.isArray(val)){
		if (JSON.stringify(val) != JSON.stringify(formatArr(defaultFileList.value))) {
			defaultFileList.value = val
			value.value = val
		}
	}else{
		if (val != toStr(defaultFileList.value)) {
			defaultFileList.value = toArr(val)
			value.value = val
		}
	}
})

watch(defaultFileList, (val) => {
	emit('update:modelValue', Array.isArray(props.modelValue) ? formatArr(val) : toStr(val))
	value.value = toStr(val)
}, {deep: true})

onMounted(() => {
	defaultFileList.value = Array.isArray(props.modelValue) ? props.modelValue : toArr(props.modelValue)
	value.value = props.modelValue
})

//默认值转换为数组
function toArr(str){
	var _arr = []
	var arr = str.split(",")
	arr.forEach(item => {
		if(item){
			var urlArr = item.split('/');
			var fileName = urlArr[urlArr.length - 1]
			_arr.push({
				name: fileName,
				url: item
			})
		}
	})
	return _arr
}

//数组转换为原始值
function toStr(arr){
	return arr.map(v => v.url).join(",")
}

//格式化数组值
function formatArr(arr){
	var _arr = []
	arr.forEach(item => {
		if(item){
			_arr.push({
				name: item.name,
				url: item.url
			})
		}
	})
	return _arr
}

function before(file){
	const maxSize = file.size / 1024 / 1024 < props.maxSize;
	if (!maxSize) {
		proxy.$message.warning(`上传文件大小不能超过 ${props.maxSize}MB!`);
		return false;
	}
}

function success(res, file){
	var os = props.onSuccess(res, file)
	if(os!=undefined && os==false){
		return false
	}
	file.name = res.fileName
	file.url = res.src
}

function error(err){
	proxy.$notify.error({
		title: '上传文件未成功',
		message: err
	})
}

function beforeRemove(uploadFile){
	return proxy.$confirm(`是否移除 ${uploadFile.name} ?`, '提示', {
		type: 'warning',
	}).then(() => {
		return true
	}).catch(() => {
		return false
	})
}

function handleExceed(){
	proxy.$message.warning(`当前设置最多上传 ${props.limit} 个文件，请移除后上传!`)
}

function handlePreview(uploadFile){
	window.open(uploadFile.url)
}

function request(param){
	var api = config.api;
	if(props.api){
		api = props.api;
	}
	const data = new FormData();
	data.append(param.filename, param.file);
	for (const key in param.data) {
		data.append(key, param.data[key]);
	}
	api(data, {
		onUploadProgress: e => {
			const complete = parseInt(((e.loaded / e.total) * 100) | 0, 10)
			param.onProgress({percent: complete})
		}
	}).then(res => {
		var response = config.parseData(res.data);
		if(res.code == config.successCode){
			param.onSuccess(response)
		}else{
			param.onError(res.msg || "未知错误")
		}
	}).catch(err => {
		param.onError(err)
	})
}
</script>

<style scoped>
	.el-form-item.is-error .pi-upload-file:deep(.el-upload-dragger) {border-color: var(--el-color-danger);}
	.pi-upload-file {width: 100%;}
	.pi-upload-file:deep(.el-upload-list__item) {transition: none !important;}
</style>
