<script setup lang="ts">
import Rs from "@@/services/RequestService"
const props = withDefaults(
	defineProps<{
		src: string
		prefixSrc?: string
		fit?: "" | "fill" | "none" | "contain" | "cover" | "scale-down"
		width?: string | number
		height?: string | number
		imageStyle?: any
		url?: string
		load?: (e: any) => void
		error?: (e: any) => void
	}>(),
	{
		width: 75,
		height: 50,
		prefixSrc: "/resource/oss/preview/",
		url: "/resource/oss/preview/",
		fit: "cover",
		imageStyle: () => {
			return {
				margin: "0 5px"
			}
		}
	}
)
function formatUrl(url: string) {
	if (isExternal(url)) {
		return url
	}
	url = import.meta.env.VITE_APP_BASE_API + (props.prefixSrc ? props.prefixSrc : "") + url
	return url
}
const srcList = ref<any>([])

const imgStyle = computed(() => {
	const style = typeof props.imageStyle == "object" ? props.imageStyle : {}
	if (!style.width) {
		style.width = typeof props.width == "string" ? props.width : `${props.width}px`
	}
	if (!style.height) {
		style.height = typeof props.height == "string" ? props.height : `${props.height}px`
	}
	return style
})

function load() {
	srcList.value = []
	if (!props.src) {
		return
	}
	const src_list = props.src.split(",")
	src_list.forEach((v) => {
		if (props.url) {
			Rs.get({
				url: props.url + v.split("$")[0],
				loading: false,
				responseType: "blob"
			}).then((res: any) => {
				if (res.type === "application/json") {
					return
				}
				const data = new Blob([res])
				const url = URL.createObjectURL(data)
				srcList.value.push(url)
			})
		} else {
			const url = formatUrl(v)
			srcList.value.push(url)
		}
	})
}

function init() {
	load()
}
function onLoad(e: any) {
	props.load && props.load(e)
}
function onError(e: any) {
	props.error && props.error(e)
}
onMounted(init)
</script>
<template>
	<el-image
		v-for="(v, i) in srcList"
		:key="i"
		:fit="fit"
		:src="`${v}`"
		:initial-index="i"
		:style="imgStyle"
		:preview-src-list="srcList"
		@load="onLoad"
		@error="onError"
		append-to-body="true">
		<template #error>
			<div class="image-slot">
				<el-icon><picture-filled /></el-icon>
			</div>
		</template>
	</el-image>
</template>

<style lang="scss" scoped>
.el-image {
	border-radius: 5px;
	background-color: #ebeef5;
	box-shadow: 0 0 5px 1px #ccc;

	:deep(.el-image__inner) {
		transition: all 0.3s;
		cursor: pointer;

		&:hover {
			transform: scale(1.2);
		}
	}

	:deep(.image-slot) {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 100%;
		color: #909399;
		font-size: 30px;
	}
}
</style>
