qcDataProcessor.uts 28 KB

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