Files
gaoYuJournal/miniprogram/pages/main/journal-creater/index.ts
2025-12-11 15:06:50 +08:00

377 lines
9.3 KiB
TypeScript

// pages/main/journal-creater/index.ts
import Events from "../../../utils/Events";
import Time from "../../../utils/Time";
import Toolkit from "../../../utils/Toolkit";
import config from "../../../config/index";
import { JournalType } from "../../../types/Journal";
import IOSize, { Unit } from "../../../utils/IOSize";
enum MediaItemType {
IMAGE,
VIDEO
}
type MediaItem = {
type: MediaItemType;
path: string;
thumbPath: string;
size: number;
duration: number | undefined;
raw: any;
}
export type Location = {
lat: number;
lng: number;
text?: string;
}
interface JournalEditorData {
idea: string;
date: string;
time: string;
type: JournalType;
mediaList: MediaItem[];
location?: Location;
qqMapSDK?: any;
isAuthLocation: boolean;
uploaded: string;
uploadTotal: string;
uploadSpeed: string;
uploadProgress: number;
isSubmitting: boolean;
}
Page({
data: <JournalEditorData>{
idea: "",
date: "2025-06-28",
time: "16:00",
type: JournalType.NORMAL,
mediaList: [],
location: undefined,
isAuthLocation: false,
uploaded: "0",
uploadTotal: "0 MB",
uploadSpeed: "0 MB / s",
uploadProgress: 0,
isSubmitting: false,
mediaItemTypeEnum: {
...MediaItemType
}
},
async onLoad() {
// 授权定位
const setting = await wx.getSetting();
wx.setStorageSync("isAuthLocation", setting.authSetting["scope.userLocation"]);
let isAuthLocation = JSON.parse(wx.getStorageSync("isAuthLocation"));
this.setData({ isAuthLocation });
if (!isAuthLocation) {
wx.authorize({
scope: "scope.userLocation"
}).then(() => {
isAuthLocation = true;
this.setData({ isAuthLocation });
});
}
const unixTime = new Date().getTime();
this.setData({
date: Time.toDate(unixTime),
time: Time.toTime(unixTime)
});
// 获取默认定位
wx.getLocation({
type: "gcj02"
}).then(resp => {
this.setData({
location: {
lat: resp.latitude,
lng: resp.longitude
},
});
const argLoc = `location=${this.data.location!.lat},${this.data.location!.lng}`;
const argKey = "key=WW5BZ-J4LCM-UIT6I-65MXY-Z5HDT-VRFFU";
wx.request({
url: `https://apis.map.qq.com/ws/geocoder/v1/?${argLoc}&${argKey}`,
success: res => {
if (res.statusCode === 200) {
this.setData({
location: {
lat: this.data.location!.lat,
lng: this.data.location!.lng,
text: (res.data as any).result?.formatted_addresses?.recommend
}
});
}
}
});
});
},
onChangeType(e: any) {
const { value } = e.detail;
this.setData({ type: value });
},
async chooseLocation() {
const location = await wx.chooseLocation({});
this.setData({
location: {
lat: location.latitude,
lng: location.longitude,
text: location.name
}
});
},
addMedia() {
const that = this;
wx.chooseMedia({
mediaType: ["mix"],
sourceType: ["album", "camera"],
camera: "back",
success(res) {
wx.showLoading({
title: "加载中..",
mask: true
})
const tempFiles = res.tempFiles;
const mediaList = tempFiles.map(item => {
return {
type: (<any>MediaItemType)[item.fileType.toUpperCase()],
path: item.tempFilePath,
thumbPath: item.thumbTempFilePath,
size: item.size,
duration: item.duration,
raw: item
} as MediaItem;
});
that.setData({
mediaList: [...that.data.mediaList, ...mediaList]
});
wx.hideLoading();
}
})
},
clearMedia() {
wx.showModal({
title: "提示",
content: "确认清空已选照片或视频吗?",
confirmText: "清空",
confirmColor: "#E64340",
cancelText: "取消",
success: res => {
if (res.confirm) {
this.setData({
mediaList: []
});
}
}
})
},
preview(e: WechatMiniprogram.BaseEvent) {
const itemIndex = e.currentTarget.dataset.index;
const total = this.data.mediaList.length;
const startIndex = Math.max(0, itemIndex - 25);
const endIndex = Math.min(total, startIndex + 50);
const newCurrentIndex = itemIndex - startIndex;
const sources = this.data.mediaList.slice(startIndex, endIndex).map(item => {
return {
url: item.path,
type: MediaItemType[item.type].toLowerCase()
} as WechatMiniprogram.MediaSource;
});
wx.previewMedia({
current: newCurrentIndex,
sources
});
},
deleteMedia(e: WechatMiniprogram.BaseEvent) {
const index = e.currentTarget.dataset.index;
const mediaList = [...this.data.mediaList];
mediaList.splice(index, 1);
this.setData({
mediaList
});
},
cancel() {
wx.switchTab({
url: "/pages/main/journal/index",
})
},
submit() {
const handleFail = () => {
wx.showToast({ title: "上传失败", icon: "error" });
wx.hideLoading();
this.setData({
isSubmitting: false
});
};
this.setData({
isSubmitting: true
});
// 获取 openId
const getOpenId = new Promise<string>((resolve, reject) => {
wx.login({
success: (res) => {
if (res.code) {
wx.request({
url: `${config.url}/journal/openid`,
method: "POST",
header: {
Key: wx.getStorageSync("key")
},
data: {
code: res.code
},
success: (resp) => {
const data = resp.data as any;
if (data.code === 20000) {
resolve(data.data);
} else {
reject(new Error("获取 openId 失败"));
}
},
fail: () => reject(new Error("获取 openId 请求失败"))
});
} else {
reject(new Error("获取登录凭证失败"));
}
},
fail: () => reject(new Error("登录失败"))
});
});
// 文件上传
const uploadFiles = new Promise<string[]>((resolve, reject) => {
const mediaList = this.data.mediaList || [];
if (mediaList.length === 0) {
resolve([]);
return;
}
wx.showLoading({ title: "正在上传..", mask: true });
// 计算总大小
const sizePromises = mediaList.map(item => {
return new Promise<number>((sizeResolve, sizeReject) => {
wx.getFileSystemManager().getFileInfo({
filePath: item.path,
success: (res) => sizeResolve(res.size),
fail: (err) => sizeReject(err)
});
});
});
Promise.all(sizePromises).then(fileSizes => {
const totalSize = fileSizes.reduce((acc, size) => acc + size, 0);
const uploadTasks: WechatMiniprogram.UploadTask[] = [];
let uploadedSize = 0;
let lastUploadedSize = 0;
this.setData({
uploadTotal: IOSize.format(totalSize, 2, Unit.MB)
});
// 计算上传速度
const speedUpdateInterval = setInterval(() => {
const chunkSize = uploadedSize - lastUploadedSize;
this.setData({
uploadSpeed: `${IOSize.format(chunkSize)} / s`
});
lastUploadedSize = uploadedSize;
}, 1000);
// 上传文件
const uploadPromises = mediaList.map(item => {
return new Promise<string>((uploadResolve, uploadReject) => {
const task = wx.uploadFile({
url: `${config.url}/temp/file/upload`,
filePath: item.path,
name: "file",
success: (resp) => {
const result = JSON.parse(resp.data);
if (result && result.code === 20000) {
uploadResolve(result.data[0].id);
} else {
uploadReject(new Error(`文件上传失败: ${result?.message || "未知错误"}`));
}
},
fail: (err) => uploadReject(new Error(`文件上传失败: ${err.errMsg}`))
});
// 监听上传进度
let prevProgress = 0;
task.onProgressUpdate((res) => {
const fileUploaded = (res.totalBytesExpectedToSend * res.progress) / 100;
const delta = fileUploaded - prevProgress;
uploadedSize += delta;
prevProgress = fileUploaded;
// 更新进度条
this.setData({
uploaded: IOSize.formatWithoutUnit(uploadedSize, 2, Unit.MB),
uploadProgress: Math.round((uploadedSize / totalSize) * 10000) / 100
});
});
uploadTasks.push(task);
});
});
Promise.all(uploadPromises).then((tempFileIds) => {
// 清除定时器
clearInterval(speedUpdateInterval);
uploadTasks.forEach(task => task.offProgressUpdate());
this.setData({
uploadProgress: 100,
uploadSpeed: "0 MB / s"
});
resolve(tempFileIds);
}).catch((e: Error) => {
// 取消所有上传任务
uploadTasks.forEach(task => task.abort());
clearInterval(speedUpdateInterval);
reject(e);
});
}).catch(reject);
});
// 并行执行获取 openId 和文件上传
Promise.all([getOpenId, uploadFiles]).then(([openId, tempFileIds]) => {
wx.showLoading({ title: "正在保存..", mask: true });
wx.request({
url: `${config.url}/journal/create`,
method: "POST",
header: {
Key: wx.getStorageSync("key")
},
data: {
idea: this.data.idea,
type: this.data.type,
lat: this.data.location?.lat,
lng: this.data.location?.lng,
location: this.data.location?.text,
pusher: openId,
createdAt: Date.parse(`${this.data.date} ${this.data.time}`),
tempFileIds
},
success: async () => {
Events.emit("JOURNAL_REFRESH");
wx.showToast({ title: "提交成功", icon: "success" });
this.setData({
idea: "",
mediaList: [],
isSubmitting: false,
uploaded: "0",
uploadTotal: "0 MB",
uploadProgress: 0
});
await Toolkit.sleep(1000);
wx.switchTab({
url: "/pages/main/journal/index"
});
},
fail: handleFail
});
}).catch(handleFail);
}
});