import { ossCdnBase, videoArr } from '@/config' import db from '@/db' import { reactive, watch, type Ref } from 'vue' const defaultBackground = 'https://aihlp.com.cn/admin/wallpaper/508d3994-3727-4839-bfe9-41b97ccf4fba_66a3272c874d41e5b9ec7562fe5822cd (1).jpg' const defaultResource = { image: '', video: '', brief: '' } export default function useResource(tag: Ref, type: string) { const resource = reactive(defaultResource) watch( tag, (val) => { // '' 表示使用默认,如果是背景,使用默认背景图片 if (!val) { Object.assign(resource, { ...defaultResource, image: type === 'background' ? defaultBackground : '' }) return } if (val.startsWith('http')) { // 内源 if (val.startsWith(ossCdnBase)) { // 地址后缀 const suffix = val.split('.').pop() if (!suffix) { return } if (videoArr.includes(suffix)) { // 内部视频 // 先显示截图,再去数据库看是否有存货 resource.video = '' resource.image = val + '?x-oss-process=video/snapshot,t_0,f_jpg,m_fast' resource.brief = val + '?x-oss-process=video/snapshot,t_0,f_jpg,w_400,h_225,m_fast' db.getItem<{ tag: string; file: Blob }[]>('videoList').then((res) => { if (!res) return const item = res.find((item) => item.tag === val) if (item) { resource.video = URL.createObjectURL(item.file) resource.image = '' } else { // 不存在,需要存入 fetch(val) .then((res) => res.blob()) .then((blob) => { if (res.length > 10) { res.pop() } res.unshift({ tag: val, file: blob }) resource.video = URL.createObjectURL(blob) resource.image = '' }) } }) } else { // 图片 resource.image = val resource.video = '' resource.brief = val + '?x-oss-process=image/resize,w_400,h_225' } return } // 外部资源 const suffix = val.split('.').pop() if (!suffix) { resource.image = val resource.video = '' resource.brief = val return } resource.image = videoArr.includes(suffix) ? '' : val resource.video = videoArr.includes(suffix) ? val : '' resource.brief = val return } // 本地 db.getItem<{ tag: string; file: Blob; type: 'image' | 'video' }[]>('localList').then( (res) => { if (!res) return const item = res.find((item) => item.tag === val) if (!item) return const url = URL.createObjectURL(item.file) resource.image = item.type === 'image' ? url : '' resource.video = item.type === 'video' ? url : '' resource.brief = url } ) }, { immediate: true } ) return resource }