qcDataProcessor.uts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. import { getToken, getTokenFromApi, getCurrentUserNameSync, getCurrentUserSync } from './auth'
  2. import { saveTaskInfo, saveTaskPhoto, saveTaskKeyProcess, saveTaskRecord, saveTaskRecordItem, getLatestTask, removeTaskAndRecord, getList, updateData } from '@/api/work'
  3. import { globalConfig } from '@/config'
  4. // 类型定义保持不变
  5. export type ApiResponse = {
  6. code : number;
  7. msg : string;
  8. data : AppTaskInfo;
  9. }
  10. export type AppTaskInfo = {
  11. gxpk : string;
  12. pk_serial : string;
  13. cardno ?: string;
  14. productcode ?: string;
  15. model ?: string;
  16. workorder ?: string;
  17. invname ?: string;
  18. graphid ?: string;
  19. processno ?: string;
  20. ver ?: string;
  21. lastupdatetime ?: string;
  22. qcrecord ?: AppTaskRecord;
  23. photolist ?: AppTaskPhoto[];
  24. keyprocesslist ?: AppTaskKeyProcess[];
  25. username ?: string;
  26. user ?: string;
  27. gxno ?: string;
  28. }
  29. export type AppTaskRecord = {
  30. pk ?: string;
  31. fk_invcode ?: string;
  32. no ?: string;
  33. invcode ?: string;
  34. invname : string;
  35. processStep ?: string;
  36. fk_processTask ?: string;
  37. checkTarget ?: string;
  38. checknum ?: number;
  39. oknum ?: number;
  40. ngnum ?: number;
  41. status ?: string;
  42. result ?: string;
  43. checkTime ?: string;
  44. cs ?: string;
  45. ts ?: string;
  46. items ?: AppTaskRecordItem[];
  47. }
  48. export type AppTaskRecordItem = {
  49. pk ?: string;
  50. fk_qcRecord ?: string;
  51. fk_prodcode ?: string;
  52. prodno ?: string;
  53. name ?: string;
  54. no ?: string;
  55. nature ?: string;
  56. unit ?: string;
  57. maxNum ?: number;
  58. minNum ?: number;
  59. status ?: string;
  60. memo ?: string;
  61. measuredvalue ?: string;
  62. result ?: string;
  63. cs ?: string;
  64. ts ?: string;
  65. recorder ?: string;
  66. measuredvaluemax ?: string;
  67. }
  68. export type AppTaskPhoto = {
  69. pk : string;
  70. photographpoint ?: string;
  71. photographdescription ?: string;
  72. photourl ?: string;
  73. photoname ?: string;
  74. fk_qcRecord ?: string;
  75. fk_prodcode ?: string;
  76. prodno ?: string;
  77. fk_creator ?: string;
  78. fks_operator ?: string;
  79. operator ?: string;
  80. processStep ?: string;
  81. fk_processTask ?: string;
  82. cs ?: string;
  83. ts ?: string;
  84. }
  85. export type AppTaskKeyProcess = {
  86. pk ?: string;
  87. pdid ?: string;
  88. testapparatus ?: string;
  89. tableid ?: string;
  90. testrequirelower ?: string;
  91. testrequireupper ?: string;
  92. parametername ?: string;
  93. parameterorder ?: string;
  94. measureunit ?: string;
  95. parameterinstruction ?: string;
  96. parameterid ?: string;
  97. fk_creator ?: string;
  98. fk_prodcode ?: string;
  99. prodno ?: string;
  100. processstep ?: string;
  101. fk_processtask ?: string;
  102. measuredvaluemin ?: string;
  103. measuredvaluemax ?: string;
  104. fks_operator ?: string;
  105. cs ?: string;
  106. ts ?: string;
  107. operator ?: string;
  108. result ?: string;
  109. memo ?: string;
  110. }
  111. export type UploadImg = {
  112. sxid : string,
  113. pk : string,
  114. path : string
  115. }
  116. export type Task = {
  117. pdid : number,
  118. gxpk : string,
  119. cardno : string,
  120. productcode : string,
  121. model : string,
  122. workorder : string,
  123. invname : string,
  124. graphid : string,
  125. processno : string,
  126. gxno : string,
  127. ver : string,
  128. lastupdatetime : string
  129. }
  130. export const showProgress = (index : number, title : string) => {
  131. // 在Android设备上,需要给hideLoading和showLoading之间添加延迟
  132. // 先隐藏之前的加载提示
  133. uni.hideLoading();
  134. // 添加50ms的延迟,确保hideLoading完全执行后再显示新的进度
  135. setTimeout(() => {
  136. uni.showLoading({
  137. title: `正在${title}第${index}个任务数据`,
  138. mask: true
  139. });
  140. }, 50);
  141. }
  142. export const moveFile = (oldPath : string) : Promise<string> => {
  143. return new Promise((resolve, reject) => {
  144. // 生成唯一的文件名
  145. const timestamp = Date.now();
  146. const randomNum = Math.floor(Math.random() * 1000);
  147. const fileExtension = oldPath.substring(oldPath.lastIndexOf('.'));
  148. const newImgName = `download_${timestamp}_${randomNum}${fileExtension}`;
  149. // 定义新的保存路径 - 不放在相册里,放在应用数据目录下的downloadImgs文件夹
  150. const destPath = `${uni.env.USER_DATA_PATH}/downloadImgs/${newImgName}`;
  151. try {
  152. // 确保目标目录存在
  153. const fs = uni.getFileSystemManager();
  154. try {
  155. fs.accessSync(`${uni.env.USER_DATA_PATH}/downloadImgs`);
  156. } catch (e) {
  157. // 目录不存在,创建目录
  158. fs.mkdirSync(`${uni.env.USER_DATA_PATH}/downloadImgs`, true);
  159. }
  160. // 先拷贝文件到新路径
  161. fs.copyFile({
  162. srcPath: oldPath,
  163. destPath: destPath,
  164. success: function () {
  165. // 删除原文件,释放空间
  166. fs.unlink({
  167. filePath: oldPath,
  168. success: function () {
  169. console.log('原文件已删除');
  170. },
  171. fail: function (unlinkErr) {
  172. console.error('删除原文件失败', unlinkErr);
  173. }
  174. });
  175. console.log('文件移动成功,新路径:', destPath);
  176. resolve(destPath);
  177. },
  178. fail: function (copyErr) {
  179. console.error('拷贝文件失败', copyErr);
  180. reject(copyErr);
  181. }
  182. });
  183. } catch (error) {
  184. console.error('文件移动过程发生错误', error);
  185. reject(error);
  186. }
  187. });
  188. }
  189. //检验任务下载
  190. export const downloadDataFromAPI = async (gxpk : string, callback ?: () => void) : Promise<boolean> => {
  191. try {
  192. uni.showLoading({ title: '任务开始下载' });
  193. const apiToken = await getTokenFromApi();
  194. if (apiToken == null || apiToken == '') {
  195. uni.hideLoading();
  196. uni.showToast({ title: `获取Token失败,请联系技术IT`, icon: 'error' });
  197. return false;
  198. }
  199. //校验是否已经存在未执行的产品号,若已经存在则提示用户该产品号是否需要被覆盖,
  200. //如果没有则直接保存。如果有存在已经在执行中的产品号,则提示已存在执行中的任务
  201. const infoJson = await getLatestTask(gxpk, null);
  202. if (infoJson?.['data'] != null) {
  203. let info = infoJson?.['data'] as UTSJSONObject ?? {} as UTSJSONObject
  204. // let ingNum = parseInt(info?.['pdid'] as string);
  205. //覆盖标识位
  206. let overwiteFlag = ref(false);
  207. // 先检查是否有任务正在执行中
  208. // if (info != null && ingNum > 0) {
  209. // uni.showToast({ title: `当前产品号已有任务在执行中!`, icon: 'error' });
  210. // return false;
  211. // }
  212. // 使用Promise来处理异步流程
  213. let deleteDataPromise = new Promise<boolean>((resolve) => {
  214. // if (info != null && ingNum == 0) {
  215. if (info != null) {
  216. //可以被覆盖,需要有提示框,给用户确认
  217. uni.showModal({
  218. title: '系统提示',
  219. content: '该工序编号已存在任务是否覆盖掉?',
  220. cancelText: '取消',
  221. confirmText: '确定',
  222. success: function (res) {
  223. if (res.confirm) {
  224. // 标记为需要覆盖
  225. overwiteFlag.value = true;
  226. // 执行删除数据操作
  227. removeTaskAndRecord(gxpk).then((recordDelResponse) => {
  228. console.log('删除数据响应:', recordDelResponse);
  229. // 删除成功,解析Promise并允许继续执行
  230. // 确保模态框已完全关闭后再解析Promise
  231. setTimeout(() => {
  232. resolve(true);
  233. }, 300);
  234. }).catch((error) => {
  235. console.error('删除数据失败:', error);
  236. uni.showToast({ title: '删除旧数据失败', icon: 'error' });
  237. resolve(false);
  238. });
  239. } else {
  240. // 用户取消覆盖
  241. uni.hideLoading();
  242. overwiteFlag.value = false;
  243. resolve(false);
  244. }
  245. }
  246. });
  247. } else {
  248. // 不需要显示确认框,直接解析Promise
  249. resolve(true);
  250. }
  251. });
  252. // 等待删除数据操作完成
  253. const canContinue : boolean = await deleteDataPromise;
  254. if (!canContinue) {
  255. // 如果不能继续(删除失败或用户取消),则终止函数执行
  256. return false;
  257. }
  258. }
  259. // 直接使用async/await处理HTTP请求,避免嵌套Promise
  260. const requestResult = await new Promise<UTSJSONObject>((resolve, reject) => {
  261. console.log(`${globalConfig.host}${globalConfig.downloadTaskURL}${gxpk}`)
  262. uni.request({
  263. url: `${globalConfig.host}${globalConfig.downloadTaskURL}${gxpk}`,
  264. method: 'GET',
  265. header: {
  266. 'token': apiToken
  267. },
  268. success: (res) => resolve(res?.['data'] as UTSJSONObject ?? {} as UTSJSONObject),
  269. fail: (err) => reject(err)
  270. });
  271. });
  272. // 处理请求结果
  273. if (requestResult != null && requestResult.code == 666) {
  274. let taskInfo = requestResult?.['data'] as UTSJSONObject ?? {} as UTSJSONObject;
  275. if (taskInfo != null) {
  276. let data = JSON.parse<AppTaskInfo>(taskInfo.toJSONString());
  277. if (data != null) {
  278. // 保存任务信息
  279. const resSave = await saveTaskInfo(taskInfo);
  280. const lastIdStr = resSave?.['lastId'] as string | null;
  281. const lastId = lastIdStr != null ? parseInt(lastIdStr) : null;
  282. if (lastId != null) {
  283. let photoList = taskInfo?.['photolist'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  284. if (photoList != null && photoList.length > 0) {
  285. const totalRecords = photoList.length;
  286. // 按顺序处理所有图片记录
  287. for (let i = 0; i < photoList.length; i++) {
  288. // 更新进度
  289. showProgress(i + 1, '下载');
  290. let photoObj = photoList[i] as UTSJSONObject;
  291. // 获取各个字段的值
  292. const pk = photoObj['pk'] as string;
  293. const photographpoint = photoObj['photographpoint'] as string | null;
  294. const photographdescription = photoObj['photographdescription'] as string | null;
  295. const photourl = photoObj['photourl'] as string | null;
  296. const photoname = photoObj['photoname'] as string | null;
  297. const fk_qcRecord = photoObj['fk_qcRecord'] as string | null;
  298. const fk_prodcode = photoObj['fk_prodcode'] as string | null;
  299. const prodno = photoObj['prodno'] as string | null;
  300. const fk_creator = photoObj['fk_creator'] as string | null;
  301. const fks_operator = photoObj['fks_operator'] as string | null;
  302. const operator = photoObj['operator'] as string | null;
  303. const processStep = photoObj['processStep'] as string | null;
  304. const fk_processTask = photoObj['fk_processTask'] as string | null;
  305. const cs = photoObj['cs'] as string | null;
  306. const ts = photoObj['ts'] as string | null;
  307. // 获取图片
  308. let imagePathsArr = [] as string[];
  309. try {
  310. // 串行执行,等待前一张图片处理完成再处理下一张
  311. const tempFilePath = await downloadAndSaveImage(pk, apiToken);
  312. if (tempFilePath != null && tempFilePath != '') {
  313. imagePathsArr.push(tempFilePath);
  314. }
  315. } catch (error) {
  316. console.error(`处理图片时出错:`, error);
  317. // 出错后继续处理下一张图片
  318. }
  319. // 拼接图片ID和路径
  320. const imagePaths = imagePathsArr.join(",");
  321. // 使用三目运算符判断,当值为null时直接插入null,否则用单引号括起来
  322. var values = `${lastId === null ? 0 : lastId},${pk === null ? '' : `'${pk}'`}, ${photographpoint === null ? 'null' : `'${photographpoint}'`}, ${photographdescription === null ? 'null' : `'${photographdescription}'`},${photourl === null ? 'null' : `'${photourl}'`},
  323. ${imagePaths === null ? 'null' : `'${imagePaths}'`},${photoname === null ? 'null' : `'${photoname}'`},${fk_qcRecord === null ? 'null' : `'${fk_qcRecord}'`},${fk_prodcode === null ? 'null' : `'${fk_prodcode}'`}, ${prodno === null ? 'null' : `'${prodno}'`},
  324. ${fk_creator === null ? 'null' : `'${fk_creator}'`},${fks_operator === null ? 'null' : `'${fks_operator}'`}, ${operator === null ? 'null' : `'${operator}'`}, ${processStep === null ? 'null' : `'${processStep}'`}, ${fk_processTask === null ? 'null' : `'${fk_processTask}'`}, ${cs === null ? 'null' : `'${cs}'`}, ${ts === null ? 'null' : `'${ts}'`}`;
  325. // 立即保存当前图片的任务信息
  326. saveTaskPhoto(values);
  327. }
  328. }
  329. //保存关键工序
  330. let keyProcessList = taskInfo?.['keyprocesslist'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  331. if (keyProcessList != null && keyProcessList.length > 0) {
  332. keyProcessList.forEach(item => {
  333. item['pdid'] = lastId;
  334. console.log(item);
  335. saveTaskKeyProcess(item);
  336. })
  337. }
  338. //保存检验记录
  339. let recordObj = taskInfo?.['qcrecord'] as (UTSJSONObject | null);
  340. // console.log('------------------------------>');
  341. // console.log(recordObj);
  342. if (recordObj != null) {
  343. recordObj['pdid'] = lastId;
  344. let recordItemList = recordObj?.['items'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  345. if (recordItemList != null && recordItemList.length > 0) {
  346. const resSave = await saveTaskRecord(recordObj);
  347. const recordIdStr = resSave?.['lastId'] as string | null;
  348. const recordId = recordIdStr != null ? parseInt(recordIdStr) : null;
  349. if (recordId != null) {
  350. recordItemList.forEach(item => {
  351. item['psxid'] = recordId;
  352. console.log(item);
  353. saveTaskRecordItem(item);
  354. })
  355. }
  356. }
  357. }
  358. } else {
  359. console.log('保存信息成功,但未获取到主键ID');
  360. }
  361. }
  362. }
  363. // 所有记录处理完成,显示完成提示
  364. uni.hideLoading();
  365. uni.showToast({ title: `下载完成`, icon: 'success' });
  366. if (callback != null) {
  367. callback();
  368. }
  369. return true;
  370. } else {
  371. const errorMsg = requestResult?.msg != null ? requestResult.msg : '未知错误';
  372. uni.hideLoading();
  373. uni.showToast({ title: `请求失败: ${errorMsg}`, icon: 'error' });
  374. return false;
  375. }
  376. } catch (error) {
  377. console.error('下载数据时发生错误:', error);
  378. uni.hideLoading();
  379. uni.showToast({ title: '下载失败,请重试', icon: 'error' });
  380. return false;
  381. }
  382. }
  383. // 辅助函数:下载并保存图片
  384. const downloadAndSaveImage = async (pk : string, apiToken : string) : Promise<string> => {
  385. return new Promise<string>((resolve, reject) => {
  386. // 使用uni.downloadFile下载图片
  387. uni.downloadFile({
  388. url: `${globalConfig.getImgURL}${pk}`,
  389. header: {
  390. 'token': apiToken
  391. },
  392. success: (res) => {
  393. if (res.statusCode === 200) {
  394. // 等待一小段时间确保文件完全下载
  395. setTimeout(() => {
  396. moveFile(res.tempFilePath).then((newFilePath) => {
  397. console.log('图片已移动并添加到数组:', newFilePath);
  398. // 处理完成后等待1秒再处理下一张
  399. setTimeout(() => {
  400. resolve(newFilePath);
  401. }, 500);
  402. }).catch((error) => {
  403. console.error('文件移动失败,使用原始路径:', error);
  404. // 如果移动失败,使用原始路径作为备选
  405. // 处理完成后等待1秒再处理下一张
  406. setTimeout(() => {
  407. resolve(res.tempFilePath);
  408. }, 1000);
  409. });
  410. }, 500); // 等待500ms确保文件完全下载
  411. } else {
  412. console.error('下载图片失败,状态码:', res.statusCode);
  413. reject(new Error(`下载图片失败,状态码: ${res.statusCode}`));
  414. }
  415. },
  416. fail: (err) => {
  417. console.error('请求图片失败:', err);
  418. reject(err);
  419. }
  420. });
  421. });
  422. }
  423. //检验任务上传
  424. export const uploadDataToAPI = async (gxpk : string, callback ?: () => void) : Promise<boolean> => {
  425. try {
  426. //暂定需要上传的数据文件
  427. const apiToken = await getTokenFromApi();
  428. if (apiToken == null || apiToken == '') {
  429. uni.hideLoading();
  430. uni.showToast({ title: `获取Token失败,请联系技术IT`, icon: 'error' });
  431. return false
  432. }
  433. // 获取数据
  434. const infoJson = await getLatestTask(gxpk, null);
  435. // console.log(infoJson)
  436. if (infoJson != null) {
  437. let taskInfoJson = infoJson?.['data'] as UTSJSONObject ?? {};
  438. if (taskInfoJson == null) {
  439. uni.hideLoading();
  440. uni.showToast({ title: '未获取到数据', icon: 'error' });
  441. return false;
  442. }
  443. console.log('--------------------->')
  444. console.log(taskInfoJson)
  445. uni.showLoading({ title: `开始上传数据`});
  446. let taskInfo = JSON.parse<Task>(taskInfoJson.toJSONString());
  447. let canContinueFlag = true;
  448. // 1. 收集所有需要上传的图片
  449. let res = await getList('app_task_photo', 'pdid', taskInfo?.pdid.toString(), 'uploadFlag', '0', null)
  450. let dataList = res?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
  451. if (dataList != null && dataList.length > 0) {
  452. //处理图片对象数组
  453. let allImagesToUpload : UploadImg[] = [];
  454. let processStep = 1;
  455. for (let index = 0; index < dataList.length; index++) {
  456. const record = dataList[index];
  457. if (record.getString('photourl') == '' || record.getString('photourl') == null
  458. || record.getString('pk') == '' || record.getString('pk') == null) {
  459. continue
  460. }
  461. showProgress(processStep, '准备上传');
  462. //收集图片信息
  463. let photourlStr = record.getString('photourl');
  464. let sxid = record.getString('sxid');
  465. let pk = record.getString('pk');
  466. let urlArr = photourlStr?.split(",") ?? [];
  467. for (let j = 0; j < urlArr.length; j++) {
  468. let path = urlArr[j];
  469. const fullFilePath = `${uni.env.USER_DATA_PATH}` + path;
  470. allImagesToUpload.push({ sxid: sxid ?? '', pk: pk ?? '', path: fullFilePath });
  471. }
  472. processStep++;
  473. }
  474. // 2. 统计总图片数量
  475. const totalImages = allImagesToUpload.length;
  476. console.log(`总共需要上传${totalImages}张图片`);
  477. if (totalImages === 0) {
  478. uni.hideLoading();
  479. uni.showToast({ title: '没有需要上传的图片', icon: 'none' });
  480. return true;
  481. }
  482. // 3. 执行第一次上传
  483. let failedImages : UploadImg[] = [];
  484. let successCount = 0;
  485. uni.showLoading({ title: `正在上传图片 (0/${totalImages})` });
  486. for (let i = 0; i < allImagesToUpload.length; i++) {
  487. const { sxid, pk, path } = allImagesToUpload[i];
  488. console.log(`开始上传文件: ${path}, 索引: ${i}, apiToken: ${apiToken}, billid: ${pk}, sxid: ${sxid}`);
  489. try {
  490. // 串行执行,等待前一个图片上传完成再处理下一张
  491. await new Promise<void>((resolve, reject) => {
  492. // 使用uni.uploadFile进行文件上传
  493. console.log(`上传路径:${globalConfig.uploadURL}`)
  494. const uploadTask = uni.uploadFile({
  495. url: `${globalConfig.uploadURL}`,
  496. filePath: path,
  497. name: 'file', // 文件参数名
  498. header: {
  499. 'token': apiToken,
  500. 'content-type': 'multipart/form-data'
  501. },
  502. formData: {
  503. 'billid': pk
  504. },
  505. success: (uploadRes) => {
  506. if (uploadRes.statusCode === 200) {
  507. console.log(`文件${path}上传成功`, uploadRes);
  508. successCount++;
  509. //更新数据库记录
  510. let updatedData = " uploadFlag = 1 "
  511. updateData('app_task_photo', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  512. console.log(`更新图片记录的上传标识 ${sxid}`)
  513. });
  514. // 等待一小段时间确保文件完全上传并处理完成
  515. setTimeout(() => {
  516. resolve();
  517. }, 1000);
  518. } else {
  519. console.error(`文件${path}上传失败,状态码:`, uploadRes.statusCode);
  520. let updatedData = " uploadFlag = 0 "
  521. updateData('app_task_photo', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  522. console.log(`上传失败更新图片记录的上传标识 ${sxid}`)
  523. });
  524. uni.showModal({
  525. content: `图片上传失败,状态码:${uploadRes.statusCode}`,
  526. title: '图片上传失败'
  527. })
  528. setTimeout(() => {
  529. reject(new Error(`上传失败,状态码: ${uploadRes.statusCode}`));
  530. }, 500);
  531. }
  532. },
  533. fail: (err) => {
  534. console.error(`文件${path}上传失败`, err);
  535. // 上传失败也继续处理下一张,但记录错误
  536. let updatedData = " uploadFlag = 0 "
  537. updateData('app_task_photo', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  538. console.log(`上传错误更新图片记录的上传标识 ${sxid}`)
  539. });
  540. uni.showModal({
  541. content: `文件上传失败:${err}`,
  542. title: '图片上传失败'
  543. })
  544. setTimeout(() => {
  545. reject(err);
  546. }, 500);
  547. },
  548. complete: () => {
  549. // console.log(`文件${path}上传操作完成`);
  550. // 更新进度
  551. uni.hideLoading();
  552. uni.showLoading({ title: `正在上传图片 (${i + 1}/${totalImages})` });
  553. }
  554. });
  555. //调试时开启
  556. // uploadTask.onProgressUpdate((res) => {
  557. // console.log('上传进度' + res.progress);
  558. // console.log('已经上传的数据长度' + res.totalBytesSent);
  559. // console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
  560. // });
  561. });
  562. } catch (error) {
  563. // 捕获上传失败的错误,将失败的图片信息添加到错误数组
  564. console.log(`处理第${i + 1}张图片时出错:`, error);
  565. failedImages.push({ sxid, pk, path });
  566. // 出错后继续处理下一张图片
  567. uni.showModal({
  568. content: `文件上传失败:${error}`,
  569. title: '图片上传失败'
  570. })
  571. }
  572. // 在两次上传之间增加一个短暂的延迟,避免请求过于频繁
  573. if (i < allImagesToUpload.length - 1) {
  574. await new Promise<void>((resolve) => {
  575. setTimeout(() => {
  576. resolve()
  577. }, 1000)
  578. })
  579. }
  580. }
  581. // 4. 执行重试逻辑(最多3次)
  582. const maxRetries = 3;
  583. let retryImages = [...failedImages]; // 复制初始失败的图片数组
  584. for (let retryCount = 1; retryCount <= maxRetries; retryCount++) {
  585. if (retryImages.length === 0) {
  586. // 如果没有需要重试的图片,提前结束循环
  587. break;
  588. }
  589. console.log(`开始第${retryCount}次重试上传失败的图片,共${retryImages.length}张`);
  590. uni.hideLoading();
  591. uni.showLoading({ title: `第${retryCount}次重试 (0/${retryImages.length})` });
  592. // 创建新的错误数组,用于收集本次重试失败的图片
  593. let currentFailedImages : UploadImg[] = [];
  594. let currentSuccessCount = 0;
  595. // 串行上传失败的图片
  596. for (let i = 0; i < retryImages.length; i++) {
  597. const { sxid, pk, path } = retryImages[i];
  598. console.log(`重试上传文件: ${path}, 索引: ${i}, 重试次数: ${retryCount}, apiToken: ${apiToken}, billid: ${pk}, sxid: ${sxid}`);
  599. console.log(`重试上传路径:${globalConfig.uploadURL}`)
  600. await new Promise<void>((resolve) => {
  601. uni.uploadFile({
  602. url: `${globalConfig.uploadURL}`,
  603. filePath: path,
  604. name: 'file',
  605. header: {
  606. 'token': apiToken
  607. },
  608. formData: {
  609. 'billid': pk
  610. },
  611. success: (uploadRes) => {
  612. if (uploadRes.statusCode === 200) {
  613. currentSuccessCount++;
  614. //更新数据库
  615. let updatedData = " uploadFlag = 1 "
  616. updateData('app_task_photo', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  617. console.log(`更新图片记录的上传标识 ${sxid}`)
  618. });
  619. console.log(`重试上传完成,当前成功: ${currentSuccessCount}, 当前失败: ${currentFailedImages.length}`);
  620. resolve();
  621. } else {
  622. currentFailedImages.push({ sxid, pk, path });
  623. }
  624. },
  625. fail: (err) => {
  626. console.error(`重试文件${path}上传失败`, err);
  627. currentFailedImages.push({ sxid, pk, path });
  628. resolve();
  629. },
  630. complete: () => {
  631. // console.log(`重试文件${path}上传操作完成`);
  632. // 更新进度
  633. uni.hideLoading();
  634. uni.showLoading({ title: `第${retryCount}次重试 (${i + 1}/${retryImages.length})` });
  635. }
  636. });
  637. });
  638. // 在两次上传之间增加一个短暂的延迟,避免请求过于频繁
  639. if (i < retryImages.length - 1) {
  640. await new Promise<void>((resolve) => {
  641. setTimeout(() => {
  642. resolve()
  643. }, 1000)
  644. })
  645. }
  646. }
  647. // 更新成功数量
  648. successCount += currentSuccessCount;
  649. // 更新下一次重试的图片列表为本次失败的图片
  650. retryImages = currentFailedImages;
  651. }
  652. // 5. 显示总结信息
  653. const finalFailedCount = retryImages.length;
  654. console.log(`上传总结: 总共${totalImages}张图片, 成功${successCount}张, 失败${finalFailedCount}张`);
  655. // 三次重试后如果仍有失败的图片,显示提示
  656. if (finalFailedCount > 0) {
  657. uni.hideLoading();
  658. uni.showModal({
  659. title: '上传提示',
  660. content: `总共需要上传${totalImages}张图片,成功${successCount}张,失败${finalFailedCount}张。\n经过${maxRetries}次重试后,仍有${finalFailedCount}张图片上传失败,请检查网络后重新上传。`,
  661. showCancel: false
  662. });
  663. }
  664. if (callback != null) {
  665. callback();
  666. }
  667. if (finalFailedCount > 0) {
  668. canContinueFlag = false
  669. }
  670. }
  671. //执行照片上传以外的逻辑
  672. if (!canContinueFlag) {
  673. uni.showToast({
  674. title: `图片上传失败,请重新上传`,
  675. icon: 'error'
  676. });
  677. }
  678. taskInfoJson.set('photolist', Array<UTSJSONObject>())
  679. taskInfoJson.set('lastupdatetime', null)
  680. taskInfoJson.set('user', getCurrentUserNameSync())
  681. taskInfoJson.set('username', getCurrentUserSync())
  682. //1.填充关键工序数据
  683. let keyRes = await getList('app_task_keyprocess', 'pdid', taskInfo?.pdid.toString(), null, null, null)
  684. let keyList = keyRes?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
  685. if (keyList != null && keyList.length > 0) {
  686. let keyObjectList = [] as AppTaskKeyProcess[]
  687. keyList.forEach(item => {
  688. let keyObject = JSON.parse<AppTaskKeyProcess>(item.toJSONString());
  689. if (keyObject != null) {
  690. keyObjectList.push(keyObject)
  691. }
  692. })
  693. taskInfoJson.set('keyprocesslist', keyObjectList)
  694. }
  695. //2.填充检验任务数据
  696. let qcRecoerdRes = await getList('app_task_record', 'pdid', taskInfo?.pdid.toString(), null, null, null)
  697. let qcRecordList = qcRecoerdRes?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
  698. if (qcRecordList != null && qcRecordList.length > 0) {
  699. let qcRecordJson = qcRecordList[0]
  700. let sxid = qcRecordJson.getString("sxid")
  701. // 3.填充检验任务item 数据据
  702. let qcRecoerdItemRes = await getList('app_task_record_item', 'psxid', sxid, null, null, null)
  703. let qcRecordItemList = qcRecoerdItemRes?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
  704. if (qcRecordItemList != null && qcRecordItemList.length > 0) {
  705. let itemList = [] as AppTaskRecordItem[]
  706. qcRecordItemList.forEach(item => {
  707. let itemObj = JSON.parse<AppTaskRecordItem>(item.toJSONString());
  708. if (itemObj != null) {
  709. itemList.push(itemObj)
  710. }
  711. })
  712. qcRecordJson.set('items', itemList)
  713. }
  714. let qcRecord = JSON.parse<AppTaskRecord>(qcRecordJson.toJSONString());
  715. taskInfoJson.set("qcrecord", qcRecord)
  716. }
  717. let requestTask = JSON.parse<AppTaskInfo>(taskInfoJson.toJSONString());
  718. console.log("请求体:", requestTask)
  719. const requestResult = await new Promise<UTSJSONObject>((resolve, reject) => {
  720. // Ensure we properly stringify the JSON object and set the correct content-type
  721. uni.request({
  722. url: `${globalConfig.uploadTaskURL}`,
  723. method: 'POST',
  724. header: {
  725. 'token': apiToken,
  726. 'content-type': 'application/json'
  727. },
  728. data: JSON.stringify(requestTask), // Convert object to JSON string
  729. success: (res) => resolve(res?.['data'] as UTSJSONObject ?? {} as UTSJSONObject),
  730. fail: (err) => reject(err)
  731. });
  732. });
  733. // 检查返回的code值
  734. const code = requestResult?.['code'] as number;
  735. if (code === 666) {
  736. let updatedData = " uploadFlag = 1, uploadtime = strftime('%Y-%m-%d %H:%M:%S', 'now', 'localtime') "
  737. updateData('app_task_info', updatedData, 'pdid', taskInfo?.pdid.toString()).then((res : UTSJSONObject) => {
  738. console.log(`更新检验任务记录的上传标识 ${taskInfo?.pdid.toString()}`)
  739. });
  740. uni.showToast({
  741. title: `上传成功`,
  742. icon: 'success'
  743. });
  744. } else {
  745. const errorMsg = requestResult?.['msg'] as string ?? '未知错误';
  746. console.error(`上传失败,错误码: ${code}, 错误信息: ${errorMsg}`);
  747. uni.showToast({
  748. title: `上传失败: ${errorMsg}`,
  749. icon: 'error'
  750. });
  751. }
  752. }
  753. return true;
  754. } catch (error) {
  755. console.error(error);
  756. uni.showToast({ title: '上传失败,请重试', icon: 'error' });
  757. uni.hideLoading();
  758. uni.showModal({
  759. content: `文件上传失败:${error}`,
  760. title: '图片上传失败'
  761. })
  762. return false;
  763. }
  764. }