277 lines
8.8 KiB
TypeScript
277 lines
8.8 KiB
TypeScript
import type { WallpaperConfig } from '../../utils/api'
|
|
import {
|
|
getWallpaper,
|
|
reorderWallpaper,
|
|
uploadWallpaperRotation,
|
|
uploadWallpaperSingle
|
|
} from '../../utils/api'
|
|
import { BASE_URL } from '../../utils/config'
|
|
import { getDeviceSn } from '../../utils/token'
|
|
|
|
interface WallpaperImage {
|
|
/** 本地临时路径;从服务端读取的壁纸为空 */
|
|
localPath: string
|
|
/** 服务端图片 URL(可能是相对路径);尚未上传完成时为空 */
|
|
url: string
|
|
/** 展示用地址:本地路径优先,否则补全后的服务端 URL */
|
|
src: string
|
|
/** 列表 key:取本地路径或 URL,保证重排后不闪烁 */
|
|
key: string
|
|
}
|
|
|
|
/** 轮换壁纸数量上限(与后端 MAX_ROTATION_IMAGES 一致) */
|
|
const MAX_ROTATION = 7
|
|
|
|
/** 服务端可能返回相对路径,展示与下载前补全域名 */
|
|
const resolveUrl = (url: string): string => {
|
|
if (!url || url.indexOf('http') === 0) return url
|
|
return `${BASE_URL}${url.charAt(0) === '/' ? '' : '/'}${url}`
|
|
}
|
|
|
|
const makeImage = (localPath: string, url: string): WallpaperImage => ({
|
|
localPath,
|
|
url,
|
|
src: localPath || resolveUrl(url),
|
|
key: localPath || url
|
|
})
|
|
|
|
/** 预览优先使用服务端 URL:本地临时路径(http://tmp/…)在部分基础库下无法被 previewImage 打开 */
|
|
const previewUrlOf = (item: WallpaperImage | null | undefined): string => {
|
|
if (!item) return ''
|
|
return item.url ? resolveUrl(item.url) : item.src
|
|
}
|
|
|
|
Page({
|
|
data: {
|
|
maxRotation: MAX_ROTATION,
|
|
segment: 0,
|
|
singleImage: null as WallpaperImage | null,
|
|
rotationItems: [] as WallpaperImage[],
|
|
loading: false,
|
|
uploading: false
|
|
},
|
|
|
|
onLoad() {
|
|
void this.loadWallpaper()
|
|
},
|
|
|
|
async loadWallpaper() {
|
|
const sn = getDeviceSn()
|
|
if (!sn) {
|
|
this.toast('请先在首页选择设备')
|
|
return
|
|
}
|
|
this.setData({ loading: true })
|
|
try {
|
|
const config = await getWallpaper(sn)
|
|
this.applyConfig(config)
|
|
} catch (err) {
|
|
this.toast((err as Error).message || '壁纸读取失败')
|
|
} finally {
|
|
this.setData({ loading: false })
|
|
}
|
|
},
|
|
|
|
/** mode=1 回填轮换列表,否则取第一张作为单个壁纸 */
|
|
applyConfig(config?: WallpaperConfig | null) {
|
|
const images = config?.images || []
|
|
if (Number(config?.mode) === 1) {
|
|
this.setData({
|
|
rotationItems: images.map((url) => makeImage('', url)),
|
|
singleImage: null
|
|
})
|
|
} else {
|
|
this.setData({
|
|
rotationItems: [],
|
|
singleImage: images.length > 0 ? makeImage('', images[0]) : null
|
|
})
|
|
}
|
|
},
|
|
|
|
/** 切换「单个 / 轮换」并重新拉取最新壁纸数据 */
|
|
onSegmentTap(e: WechatMiniprogram.TouchEvent) {
|
|
const { index } = e.currentTarget.dataset as { index: number }
|
|
const next = Number(index)
|
|
if (next === this.data.segment) return
|
|
this.setData({ segment: next })
|
|
if (!this.data.uploading) void this.loadWallpaper()
|
|
},
|
|
|
|
onChangeSingle() {
|
|
const sn = getDeviceSn()
|
|
if (!sn) {
|
|
this.toast('请先绑定设备')
|
|
return
|
|
}
|
|
if (this.data.uploading || this.data.loading) return
|
|
wx.chooseImage({
|
|
count: 1,
|
|
sizeType: ['compressed'],
|
|
sourceType: ['album', 'camera'],
|
|
success: (res) => {
|
|
const filePath = res.tempFilePaths[0]
|
|
if (filePath) void this.uploadSingle(sn, filePath)
|
|
}
|
|
})
|
|
},
|
|
|
|
/** 单个模式:选图后立即上传并推送设备(mode=0) */
|
|
async uploadSingle(sn: string, filePath: string) {
|
|
this.setData({
|
|
singleImage: makeImage(filePath, ''),
|
|
uploading: true,
|
|
loading: false
|
|
})
|
|
try {
|
|
const result = await uploadWallpaperSingle(sn, filePath)
|
|
if (getDeviceSn() !== sn) return
|
|
this.setData({
|
|
// 上传成功后改用服务端 URL,保证再次进入页面或点击预览都能正常加载
|
|
singleImage: result?.url ? makeImage('', result.url) : makeImage(filePath, ''),
|
|
rotationItems: []
|
|
})
|
|
this.toast('壁纸已保存')
|
|
} catch (err) {
|
|
this.toast((err as Error).message || '壁纸上传失败')
|
|
} finally {
|
|
this.setData({ uploading: false })
|
|
}
|
|
},
|
|
|
|
onAddRotation() {
|
|
const sn = getDeviceSn()
|
|
if (!sn) {
|
|
this.toast('请先绑定设备')
|
|
return
|
|
}
|
|
if (this.data.uploading || this.data.loading) return
|
|
const items = this.data.rotationItems
|
|
if (items.length >= MAX_ROTATION) {
|
|
this.toast(`最多只能添加 ${MAX_ROTATION} 张壁纸`)
|
|
return
|
|
}
|
|
wx.chooseImage({
|
|
count: 1,
|
|
sizeType: ['compressed'],
|
|
sourceType: ['album', 'camera'],
|
|
success: (res) => {
|
|
const filePath = res.tempFilePaths[0]
|
|
if (!filePath) return
|
|
this.setData({ rotationItems: [...items, makeImage(filePath, '')] })
|
|
void this.uploadRotation(sn)
|
|
}
|
|
})
|
|
},
|
|
|
|
onRemoveRotation(e: WechatMiniprogram.TouchEvent) {
|
|
const { index } = e.currentTarget.dataset as { index: number }
|
|
const items = this.data.rotationItems.filter((_, i) => i !== Number(index))
|
|
this.setData({ rotationItems: items })
|
|
// 删到最后一张时后端无清空接口(rotation 需 1~7 张、reorder 不收空列表),仅更新本地展示
|
|
const sn = getDeviceSn()
|
|
if (!sn || items.length === 0 || this.data.uploading) return
|
|
void this.uploadRotation(sn)
|
|
},
|
|
|
|
/** 调整顺序:把该项上移/下移一格后持久化到后端 */
|
|
onMove(e: WechatMiniprogram.TouchEvent) {
|
|
const { index, offset } = e.currentTarget.dataset as { index: number; offset: number }
|
|
const items = [...this.data.rotationItems]
|
|
const from = Number(index)
|
|
const to = from + Number(offset)
|
|
if (to < 0 || to >= items.length || this.data.uploading || this.data.loading) return
|
|
const [item] = items.splice(from, 1)
|
|
items.splice(to, 0, item)
|
|
this.setData({ rotationItems: items })
|
|
void this.persistOrder()
|
|
},
|
|
|
|
/** 顺序持久化:全部已上传时只调排序接口,否则整组重传以保序 */
|
|
async persistOrder() {
|
|
const sn = getDeviceSn()
|
|
if (!sn) return
|
|
const urls = this.data.rotationItems.map((item) => item.url)
|
|
if (urls.some((url) => !url)) {
|
|
await this.uploadRotation(sn)
|
|
return
|
|
}
|
|
try {
|
|
await reorderWallpaper(sn, urls)
|
|
} catch (err) {
|
|
this.toast((err as Error).message || '排序保存失败')
|
|
}
|
|
},
|
|
|
|
/** 轮换模式:把当前列表整组上传并推送设备(mode=1),成功后回填各图 URL */
|
|
async uploadRotation(sn: string) {
|
|
if (this.data.uploading) return
|
|
this.setData({ uploading: true, loading: false })
|
|
const items = [...this.data.rotationItems]
|
|
try {
|
|
const localPaths: string[] = []
|
|
for (const item of items) {
|
|
if (item.localPath) {
|
|
localPaths.push(item.localPath)
|
|
} else {
|
|
localPaths.push(await this.downloadTemp(resolveUrl(item.url)))
|
|
}
|
|
}
|
|
const urls = await uploadWallpaperRotation(sn, localPaths)
|
|
if (getDeviceSn() !== sn) return
|
|
if (urls.length === items.length) {
|
|
this.setData({
|
|
singleImage: null,
|
|
rotationItems: items.map((item, i) => makeImage(item.localPath, urls[i]))
|
|
})
|
|
}
|
|
this.toast('壁纸已保存')
|
|
} catch (err) {
|
|
this.toast((err as Error).message || '壁纸上传失败')
|
|
} finally {
|
|
this.setData({ uploading: false })
|
|
}
|
|
},
|
|
|
|
/** 服务端已有的图片需先下载为本地文件再整组上传 */
|
|
downloadTemp(url: string): Promise<string> {
|
|
return new Promise<string>((resolve, reject) => {
|
|
wx.downloadFile({
|
|
url,
|
|
success: (res) => {
|
|
if (res.statusCode === 200) resolve(res.tempFilePath)
|
|
else reject(new Error('壁纸图片下载失败'))
|
|
},
|
|
fail: () => reject(new Error('壁纸图片下载失败'))
|
|
})
|
|
})
|
|
},
|
|
|
|
onPreview(e: WechatMiniprogram.TouchEvent) {
|
|
// 与首页截图/相册一致走 data-url;取不到时回退页面数据,避免点击静默无响应
|
|
const { url } = e.currentTarget.dataset as { url?: string }
|
|
const list = this.data.segment === 0 ? [this.data.singleImage] : this.data.rotationItems
|
|
const urls = list.map(previewUrlOf).filter((value) => !!value)
|
|
// 点击项按本地/展示地址匹配,再换成服务端 URL 交给 previewImage
|
|
const tapped = list.find((item) => !!item && item.src === url)
|
|
const current = previewUrlOf(tapped) || urls[0] || ''
|
|
if (!current) {
|
|
this.toast('图片未就绪,无法预览')
|
|
return
|
|
}
|
|
wx.previewImage({
|
|
current,
|
|
urls: urls.length > 0 ? urls : [current],
|
|
fail: (err) => this.toast(`预览失败:${err.errMsg || '未知错误'}`)
|
|
})
|
|
},
|
|
|
|
/** 单个壁纸加载失败时给出明确提示,避免只看到灰块 */
|
|
onImageError() {
|
|
if (!this.data.uploading) this.toast('壁纸加载失败,请重新选择')
|
|
},
|
|
|
|
toast(title: string) {
|
|
wx.showToast({ title, icon: 'none', duration: 1800 })
|
|
}
|
|
})
|