Commit 9c5abf6b by yixinjj

添加记录管理类

1 parent f02ffeac
...@@ -23,7 +23,7 @@ ...@@ -23,7 +23,7 @@
* @param {Object} options - (可选)包含上传器配置的对象,如 region * @param {Object} options - (可选)包含上传器配置的对象,如 region
* @throws {Error} 如果缺少必要的参数,将抛出错误 * @throws {Error} 如果缺少必要的参数,将抛出错误
*/ */
window.msgFromUniapp = function (accessKeyId, accessKeySecret, stsToken, fileName, filePath, options = {}) { window.msgFromUniapp = function (accessKeyId, accessKeySecret, stsToken, fileName, filePath, recordId, options = {}) {
if (!accessKeyId || !accessKeySecret || !stsToken || !fileName || !filePath) { if (!accessKeyId || !accessKeySecret || !stsToken || !fileName || !filePath) {
throw new Error('accessKeyId,accessKeySecret,stsToken,fileName,filePath is required') throw new Error('accessKeyId,accessKeySecret,stsToken,fileName,filePath is required')
} }
...@@ -38,7 +38,8 @@ ...@@ -38,7 +38,8 @@
uni.postMessage({ uni.postMessage({
data: { data: {
...result, ...result,
fileName fileName,
recordId
} }
}); });
// 调用 destroy 方法,这将重置上传器的状态,释放资源 // 调用 destroy 方法,这将重置上传器的状态,释放资源
...@@ -52,6 +53,7 @@ ...@@ -52,6 +53,7 @@
data: { data: {
code: 1, code: 1,
fileName, fileName,
recordId,
error: e.message error: e.message
} }
}); });
......
import { storageApi } from "@/utils/cache";
const UPLOAD_STATUS = {
// 上传状态
SUCCESS: 1,
FAIL: 2,
};
let wv, getResult;
import { uploadFile, getOssToken } from "@/utils/ossUploadFile/uploadFile.js";
import config from "@/config.js";
import RecordManager from "@/utils/recordManager";
const recordManager = new RecordManager();
export default {
onLoad() {},
data() {
return {
wv: null,
};
},
mounted() {
this.initWebview().then((wv) => {
this.wv = wv;
});
},
methods: {
handlerMessage(result) {
console.log(result);
getResult = result;
},
checkRecord() {
uni.$isNetWork().then(async (res) => {
let recordList = storageApi.getRecords() || "[]";
console.log(recordList, "recordList");
for (let i = 0; i < recordList.length; i++) {
await this.handleRerord(recordList[i]);
}
});
},
getFilePath() {
return new Promise((resolve) => {
plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function (fs) {
resolve(fs.root.fullPath);
});
});
},
setTimeoutResult() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(getResult);
}, 1000);
});
},
/**上传记录*/
async handleRerord(val) {
let recordList = JSON.parse(uni.$storage.get("recordList") || "[]");
let idx = recordList.findIndex(
(item) => item.receptionStartTime == val.receptionStartTime
);
let recordUrlList = val.recordUrlList;
// 上传失败的记录
for (let i of recordUrlList) {
console.log(i.status == UPLOAD_STATUS.fail);
if (i.status == UPLOAD_STATUS.fail) {
const filePath = i.file.split("/").pop();
const { lsaccessKeySecret, securityToken, lsaccessKeyId } =
await getOssToken();
console.log(lsaccessKeySecret, securityToken, lsaccessKeyId);
const rootPath = await this.getFilePath();
wv.evalJS(
`msgFromUniapp('${lsaccessKeyId}','${lsaccessKeySecret}','${securityToken}','${filePath}','file://${rootPath}uniapp_save/')`
);
for (let k = 0; k < 100; k++) {
const result = await this.setTimeoutResult();
if (result) {
if (result.detail.data[0].code == 0) {
uni.removeSavedFile({
filePath: i.file,
complete: function (res) {
console.log(res);
},
});
i.status = UPLOAD_STATUS.success;
i.file = config.OSS_DOMAIN + "/" + config.FOLDER + filePath;
}
getResult = "";
break;
}
}
// const result = await this.checkFileUpload(filePath);
// if (!(result instanceof Error)) {
// i.status = UPLOAD_STATUS.success;
// i.file = result;
// }
}
}
// 判断是否全部上传成功
if (recordUrlList.every((i) => i.status == UPLOAD_STATUS.success)) {
val.recordUrlList = val.recordUrlList.map((i) => i.file);
try {
const res = await uni.$api.commonApi.saveRecCustomer(val);
console.log(res, val);
recordList.splice(idx, 1);
uni.$storage.set("recordList", JSON.stringify(recordList));
} catch (err) {
Promise.reject(error);
}
}
},
async checkFileUpload(tempFilePath) {
console.log(tempFilePath);
let attempt = 0;
let errorMsg = "";
while (attempt < 2) {
try {
const result = await uploadFile(tempFilePath);
// 上传成功
return result;
} catch (error) {
errorMsg = error;
attempt++;
// 等待一段时间后重试
await new Promise((resolve) => setTimeout(resolve, 3000)); // 3秒后重试
}
}
// 达到最大尝试次数后,如果上传仍然失败,可以进行相应的处理
console.error("上传失败,达到最大尝试次数");
// 返回一个错误或者进行其他操作
return new Error(errorMsg);
},
initWebview() {
return new Promise((resolve, reject) => {
var currentWebview = this.$scope.$getAppWebview(); //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
setTimeout(function () {
var wv = currentWebview.children()[0];
wv.setStyle({ top: "100%", height: 300 });
}, 1000); //如果是页面初始化调用时,需要延时一下
resolve(this.wv);
});
},
async uploadRecord() {
const record = recordManager.getRecord();
if (!record) return;
const recordFileList = record.recordUrlList;
if (recordFileList.length == 0) {
//TODO 上传记录?
}
for (let fileInfo of recordFileList) {
const { file, status } = fileInfo;
if (status == UPLOAD_STATUS.FAIL) {
const filePath = file.split("/").pop();
const { lsaccessKeySecret, securityToken, lsaccessKeyId } =
await getOssToken();
// console.log(lsaccessKeySecret, securityToken, lsaccessKeyId);
const rootPath = await this.getFilePath();
wv.evalJS(
`msgFromUniapp('${lsaccessKeyId}','${lsaccessKeySecret}','${securityToken}','${filePath}','file://${rootPath}uniapp_save/')`
);
}
}
},
async uploadSuccess(recordId, filePath) {
const record = recordManager.getRecordById(recordId);
if (!record) return;
const recordFileList = record.recordUrlList;
let isAllSuccess = true;
for (let fileInfo of recordFileList) {
const { file } = fileInfo;
if (file == filePath) {
delete fileInfo.status;
}
if (fileInfo.status == UPLOAD_STATUS.FAIL) {
isAllSuccess = false;
}
}
if (isAllSuccess) {
try {
const res = await uni.$api.commonApi.saveRecCustomer(record);
if (res.code == 0) {
recordManager.removeRecord(recordId);
}
} catch (err) {
Promise.reject(error);
}
}
},
},
};
import { STORAGE_OBJECTkEY } from './constantData'
// console.log(storage)
/** */
// 实例化对象存储 // 实例化对象存储
import Storage from './storage' import Storage from './storage'
const storage = new Storage() const storage = new Storage()
...@@ -56,6 +59,15 @@ export function setSystem_info(that) { ...@@ -56,6 +59,15 @@ export function setSystem_info(that) {
}) })
} }
export function getRecords() {
return storage.get(STORAGE_OBJECTkEY.recordList)
}
export function setRecords(data) {
storage.set(STORAGE_OBJECTkEY.recordList, data)
}
export function removeRecords() {
storage.rm(STORAGE_OBJECTkEY.recordList)
}
export default{ export default{
getSessionId, getSessionId,
setSessionId, setSessionId,
...@@ -66,5 +78,8 @@ export default{ ...@@ -66,5 +78,8 @@ export default{
getStorageSync, getStorageSync,
setNavigationBarTitleText, setNavigationBarTitleText,
getNavigationBarTitleText, getNavigationBarTitleText,
setSystem_info setSystem_info,
getRecords,
setRecords,
removeRecords
} }
import { storageApi } from "@/utils/cache";
class RecordManager {
constructor() {}
/**
* 将一条新记录添加到当前对象的记录列表中
*
* @param {Object} record - 要添加的新记录对象
* @returns {Array} - 包含新记录的更新后的记录列表
*/
addRecord(record) {
const records = this.getRecords();
records.push(record);
this.setRecords(records);
return records;
}
/**
* 移除一个ID对应的记录
*
* @param {number} id - 要移除的记录的ID
* @returns {Array} - 移除记录后的更新后的记录列表
*/
removeRecord(id) {
let records = this.getRecords();
records = records.filter((i) => i.id !== id);
this.setRecords(records);
return records;
}
/**
* 获取并移除当前对象记录列表中的最后一条记录
*
* @returns {Object} - 被移除的最后一条记录对象,如果记录列表为空,则返回 undefined
*/
getRecord() {
const records = this.getRecords();
return records.pop();
}
/**
* 根据给定的 ID 获取一条记录
*
* @param {number} id - 要获取的记录的 ID
* @returns {Object} - 具有给定 ID 的记录对象,如果没有找到符合条件的记录,则返回 undefined
*/
getRecordById(id) {
const records = this.getRecords();
return records.find((i) => i.id === id);
}
/**
* 获取记录列表
*
* @returns {Array} - 从 storageApi 获取的记录列表
*/
getRecords() {
return storageApi.getRecords();
}
/**
* 设置记录列表
*
* @param {Array} records - 要设置的记录列表
* @returns {void} - 此函数不返回任何值
*/
setRecords(records) {
storageApi.setRecords(records);
}
/**
* 清除所有记录
*
* @returns {void} - 此函数不返回任何值
*/
clearRecords() {
storageApi.removeRecords();
}
}
export default RecordManager;
/* /*
* @Author: 前端 qianduan01@didihu.com.cn * @Author: 前端 qianduan01@didihu.com.cn
* @Date: 2024-04-08 17:16:46 * @Date: 2024-04-08 17:16:46
* @LastEditors: 前端 qianduan01@didihu.com.cn * @LastEditors: limin
* @LastEditTime: 2024-04-16 10:13:29 * @LastEditTime: 2024-06-28 17:51:38
* @FilePath: \gl_tape\utils\utils.js * @FilePath: \gl_tape\utils\utils.js
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
...@@ -90,6 +90,34 @@ var isNetWork = function () { ...@@ -90,6 +90,34 @@ var isNetWork = function () {
}); });
}); });
}; };
var uuid = function(len, radix) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
var uuid = [], i;
radix = radix || chars.length;
if (len) {
// Compact form
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
} else {
// rfc4122, version 4 form
var r;
// rfc4122 requires these characters
uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';
// Fill in random data. At i==19 set the high bits of clock sequence as
// per rfc4122, sec. 4.1.5
for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random()*16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}
return uuid.join('');
}
export default { export default {
convertDateTimeFormat, convertDateTimeFormat,
deepClone, deepClone,
...@@ -97,4 +125,5 @@ export default { ...@@ -97,4 +125,5 @@ export default {
debounce, debounce,
throttle, throttle,
isNetWork, isNetWork,
uuid
}; };
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!