<template>
	<view>
		<wd-upload :accept="accept" multiple :before-preview="beforeChoose" :file-list="fileList" :action="action" @change="handleChange" :disabled="disabled" @fail="fail"
			:before-remove="beforeRemove" :multiple="multiple">
			<template #preview-cover="{ file,index }">
				<!-- 小程序拿不到文件 -->
				<view class="preview-cover text-ellipsis" style="color: #0081ff;" @click="onLinePreview(file)">
					{{ file?.name||`文件${index+1}` }}
				</view>
			</template>
		</wd-upload>
		<wd-toast></wd-toast>
		<wd-message-box></wd-message-box>
	</view>
</template>

<script lang="ts" setup>
	import { ref, watch } from 'vue'
	import { useToast, useMessage, useNotify, dayjs } from 'wot-design-uni'
	import { deleteFile } from '@/api/system'
	import { http } from '@/utils/http'
	import {
		getEnvBaseUrl,
		getFileAccessHttpUrl
	} from '@/utils/index'
	import { init } from 'echarts'
	defineOptions({ //文件上传组件 by 闵
		name: 'Mupload',
		options: {
			styleIsolation: 'shared'
		}
	})
	const props = defineProps({
		modelValue: {
			type: String,
			default: '',
		},
		multiple: { //是否多选上传
			type:  Boolean,
			default: true
		},
		path: { //自定义path
			type: String,
			default: ''
		},
		disabled: { //是否禁用
			type: Boolean,
			default: false
		},
		accept: { //可上传的文件
			type: String,
			default: 'all'
		}
	})
	const toast = useToast()
	const message = useMessage()
	const emit = defineEmits(['change', 'update:modelValue'])
	const fileList = ref([])
	const action = ref(getEnvBaseUrl() + '/sys/common/upload?appPath=APP文件/')
	const defaultPath = ref(getEnvBaseUrl() + '/sys/common/upload?appPath=')

	/**
	 * 监听value数值
	 */
	watch(
		() => props.modelValue,
		(val) => {
			if (val) {
				initFileList(val); //初始化文件列表
			}
		},
		{ immediate: true },
	)

	watch( //监听文件路径更改
		() => props.path,
		(val) => {
			if (val) {
				action.value = defaultPath.value + val;
			}
		},
		{ immediate: true },
	)

	const beforeChoose = (val) =>{
		onLinePreview(val.file);
		return false;
	}

	const handleChange = (val) => { //文件发生变化
		let pathArr = [];
		if (val.fileList && val.fileList.length > 0) {
			let fileListTemp = val.fileList.map((file) => {
				console.log(file)
				if (file.response) {
					let reUrl = JSON.parse(file.response).message;
					pathArr.push(reUrl)
					file.url = getFileAccessHttpUrl(reUrl, '')
				}
				return file;
			});
			fileList.value = fileListTemp
		}
		if (pathArr.length > 0) {
			emit('change', pathArr.join(","))
			emit('update:modelValue', pathArr.join(","))
		}
		console.log(pathArr)
		console.log(val)
		console.log(fileList)
	}

	const uidGenerator = () => {
		return '-' + parseInt(Math.random() * 10000 + 1 + '', 10);
	}

	const getFileName = (path) => {
		if (path.lastIndexOf("\\") >= 0) {
			let reg = new RegExp("\\\\", "g");
			path = path.replace(reg, "/");
		}
		return path.substring(path.lastIndexOf("/") + 1);
	}

	const initFileList = (paths) => {
		if (!paths || paths.length == 0) {
			fileList.value = [];
			return;
		}
		let fileListTemp = [];
		let arr = paths.split(",")
		for (var a = 0; a < arr.length; a++) {
			let url = getFileAccessHttpUrl(arr[a], '');
			fileListTemp.push({
				uid: uidGenerator(),
				name: getFileName(arr[a]),
				status: 'success',
				url: getFileAccessHttpUrl(arr[a], ''),
				response: JSON.stringify({
					status: "success",
					message: arr[a]
				})
			})
		}
		fileList.value = fileListTemp
		console.log(fileList)
	}

	const onLinePreview = (val) => { //在线预览
		// let prex = props.path ? props.path : 'APP文件'
		let usePath = JSON.parse( val.response).message
		uni.navigateTo({
			url: `/pages/onlinePreview/detail?data=${usePath}`
		});
	}

	const beforeRemove = ({ file, fileList, resolve }) => { //文件删除
		console.log(file)
		if (file) {
			message
				.confirm({
					msg: '是否删除该文件？',
					title: '确认删除吗',
				})
				.then(() => {
					deleteFile({ name: file.name, url: file.url }).then(res => {
						console.log(res)
						if (res.success) {
							toast.success(res.message)
							resolve(true)
						} else {
							toast.error(res.message)
						}
					})
				})

		}
	}
	
	const fail = ({ error, file,formData })=>{ //上传失败
		toast.error(error)
	}
</script>

<style lang="scss" scoped>
	.text-ellipsis {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		-o-text-overflow: ellipsis;
		width: 100%;
	}
</style>