qcDataProcessor.uts 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. import { getToken, getTokenFromApi, getCurrentUserNameSync, getCurrentUserSync } from './auth'
  2. import { saveTaskInfo, saveTaskPhoto, saveTaskKeyProcess, saveTaskRecord, saveTaskRecordItem, getLatestTask, removeTaskAndRecord, getList, updateData, addOperateLog } 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 photoCount = parseInt(info?.['photoCount'] as string);
  205. let keyCount = parseInt(info?.['keyCount'] as string);
  206. let recordCount = parseInt(info?.['recordCount'] as string);
  207. //覆盖标识位
  208. let overwiteFlag = ref(false);
  209. // 先检查是否有任务正在执行中
  210. if (info != null && ( photoCount + keyCount + recordCount)> 0) {
  211. uni.showToast({ title: `当前工序码已有任务在执行中!`, icon: 'error' });
  212. return false;
  213. }
  214. // 使用Promise来处理异步流程
  215. let deleteDataPromise = new Promise<boolean>((resolve) => {
  216. // if (info != null && ingNum == 0) {
  217. if (info != null) {
  218. //可以被覆盖,需要有提示框,给用户确认
  219. uni.showModal({
  220. title: '系统提示',
  221. content: '该工序码已存在任务是否覆盖掉?',
  222. cancelText: '取消',
  223. confirmText: '确定',
  224. success: function (res) {
  225. if (res.confirm) {
  226. // 标记为需要覆盖
  227. overwiteFlag.value = true;
  228. // 执行删除数据操作
  229. removeTaskAndRecord(gxpk).then((recordDelResponse) => {
  230. console.log('删除数据响应:', recordDelResponse);
  231. // 删除成功,解析Promise并允许继续执行
  232. // 确保模态框已完全关闭后再解析Promise
  233. setTimeout(() => {
  234. resolve(true);
  235. }, 300);
  236. }).catch((error) => {
  237. console.error('删除数据失败:', error);
  238. uni.showToast({ title: '删除旧数据失败', icon: 'error' });
  239. resolve(false);
  240. });
  241. } else {
  242. // 用户取消覆盖
  243. uni.hideLoading();
  244. overwiteFlag.value = false;
  245. resolve(false);
  246. }
  247. }
  248. });
  249. } else {
  250. // 不需要显示确认框,直接解析Promise
  251. resolve(true);
  252. }
  253. });
  254. // 等待删除数据操作完成
  255. const canContinue : boolean = await deleteDataPromise;
  256. if (!canContinue) {
  257. // 如果不能继续(删除失败或用户取消),则终止函数执行
  258. return false;
  259. }
  260. }
  261. // 直接使用async/await处理HTTP请求,避免嵌套Promise
  262. const requestResult = await new Promise<UTSJSONObject>((resolve, reject) => {
  263. console.log(`${globalConfig.host}${globalConfig.downloadTaskURL}${gxpk}`)
  264. uni.request({
  265. url: `${globalConfig.host}${globalConfig.downloadTaskURL}${gxpk}`,
  266. method: 'GET',
  267. header: {
  268. 'token': apiToken
  269. },
  270. success: (res) => resolve(res?.['data'] as UTSJSONObject ?? {} as UTSJSONObject),
  271. fail: (err) => reject(err)
  272. });
  273. });
  274. // 处理请求结果
  275. if (requestResult != null && requestResult.code == 666) {
  276. let taskInfo = requestResult?.['data'] as UTSJSONObject ?? {} as UTSJSONObject;
  277. if (taskInfo != null) {
  278. let data = JSON.parse<AppTaskInfo>(taskInfo.toJSONString());
  279. if (data != null) {
  280. // 保存任务信息
  281. const resSave = await saveTaskInfo(taskInfo);
  282. const lastIdStr = resSave?.['lastId'] as string | null;
  283. const lastId = lastIdStr != null ? parseInt(lastIdStr) : null;
  284. if (lastId != null) {
  285. let photoList = taskInfo?.['photolist'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  286. if (photoList != null && photoList.length > 0) {
  287. const totalRecords = photoList.length;
  288. // 按顺序处理所有图片记录
  289. for (let i = 0; i < photoList.length; i++) {
  290. // 更新进度
  291. showProgress(i + 1, '下载');
  292. let photoObj = photoList[i] as UTSJSONObject;
  293. // 获取各个字段的值
  294. const pk = photoObj['pk'] as string;
  295. const photographpoint = photoObj['photographpoint'] as string | null;
  296. const photographdescription = photoObj['photographdescription'] as string | null;
  297. const photourl = photoObj['photourl'] as string | null;
  298. const photoname = photoObj['photoname'] as string | null;
  299. const fk_qcRecord = photoObj['fk_qcRecord'] as string | null;
  300. const fk_prodcode = photoObj['fk_prodcode'] as string | null;
  301. const prodno = photoObj['prodno'] as string | null;
  302. const fk_creator = photoObj['fk_creator'] as string | null;
  303. const fks_operator = photoObj['fks_operator'] as string | null;
  304. const operator = photoObj['operator'] as string | null;
  305. const processStep = photoObj['processStep'] as string | null;
  306. const fk_processTask = photoObj['fk_processTask'] as string | null;
  307. const cs = photoObj['cs'] as string | null;
  308. const ts = photoObj['ts'] as string | null;
  309. // 获取图片
  310. let imagePathsArr = [] as string[];
  311. try {
  312. // 串行执行,等待前一张图片处理完成再处理下一张
  313. const tempFilePath = await downloadAndSaveImage(pk, apiToken);
  314. if (tempFilePath != null && tempFilePath != '') {
  315. imagePathsArr.push(tempFilePath);
  316. }
  317. } catch (error) {
  318. console.error(`处理图片时出错:`, error);
  319. // 出错后继续处理下一张图片
  320. }
  321. // 拼接图片ID和路径
  322. const imagePaths = imagePathsArr.join(",");
  323. // 使用三目运算符判断,当值为null时直接插入null,否则用单引号括起来
  324. var values = `${lastId === null ? 0 : lastId},${pk === null ? '' : `'${pk}'`}, ${photographpoint === null ? 'null' : `'${photographpoint}'`}, ${photographdescription === null ? 'null' : `'${photographdescription}'`},${photourl === null ? 'null' : `'${photourl}'`},
  325. ${imagePaths === null ? 'null' : `'${imagePaths}'`},${photoname === null ? 'null' : `'${photoname}'`},${fk_qcRecord === null ? 'null' : `'${fk_qcRecord}'`},${fk_prodcode === null ? 'null' : `'${fk_prodcode}'`}, ${prodno === null ? 'null' : `'${prodno}'`},
  326. ${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}'`}`;
  327. // 立即保存当前图片的任务信息
  328. saveTaskPhoto(values);
  329. }
  330. }
  331. //保存关键工序
  332. let keyProcessList = taskInfo?.['keyprocesslist'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  333. if (keyProcessList != null && keyProcessList.length > 0) {
  334. keyProcessList.forEach(item => {
  335. item['pdid'] = lastId;
  336. console.log(item);
  337. saveTaskKeyProcess(item);
  338. })
  339. }
  340. //保存检验记录
  341. let recordObj = taskInfo?.['qcrecord'] as (UTSJSONObject | null);
  342. // console.log('------------------------------>');
  343. // console.log(recordObj);
  344. if (recordObj != null) {
  345. recordObj['pdid'] = lastId;
  346. let recordItemList = recordObj?.['items'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  347. if (recordItemList != null && recordItemList.length > 0) {
  348. const resSave = await saveTaskRecord(recordObj);
  349. const recordIdStr = resSave?.['lastId'] as string | null;
  350. const recordId = recordIdStr != null ? parseInt(recordIdStr) : null;
  351. if (recordId != null) {
  352. recordItemList.forEach(item => {
  353. item['psxid'] = recordId;
  354. console.log(item);
  355. saveTaskRecordItem(item);
  356. })
  357. }
  358. }
  359. }
  360. } else {
  361. console.log('保存信息成功,但未获取到主键ID');
  362. }
  363. }
  364. }
  365. // 所有记录处理完成,显示完成提示
  366. uni.hideLoading();
  367. uni.showToast({ title: `下载完成`, icon: 'success' });
  368. addOperateLog({ module: '检验任务', title: '下载检验任务', content: `下载检验任务,工序码:${gxpk}`, msg: null, createuser: getCurrentUserSync()??'' })
  369. if (callback != null) {
  370. callback();
  371. }
  372. return true;
  373. } else {
  374. const errorMsg = requestResult?.msg != null ? requestResult.msg : '未知错误';
  375. uni.hideLoading();
  376. uni.showToast({ title: `请求失败: ${errorMsg}`, icon: 'error' });
  377. addOperateLog({ module: '检验任务', title: '下载检验任务失败', content: `下载检验任务失败,工序码:${gxpk}`, msg: `错误信息Err:${errorMsg}`, createuser: getCurrentUserSync()??'' })
  378. return false;
  379. }
  380. } catch (error) {
  381. console.error('下载数据时发生错误:', error);
  382. uni.hideLoading();
  383. addOperateLog({ module: '检验任务', title: '下载检验任务失败', content: `下载检验任务失败,工序码:${gxpk}`, msg: `错误信息Err:${error}`, createuser: getCurrentUserSync()??'' })
  384. uni.showToast({ title: '下载失败,请重试', icon: 'error' });
  385. return false;
  386. }
  387. }
  388. // 辅助函数:下载并保存图片
  389. const downloadAndSaveImage = async (pk : string, apiToken : string) : Promise<string> => {
  390. return new Promise<string>((resolve, reject) => {
  391. // 使用uni.downloadFile下载图片
  392. uni.downloadFile({
  393. url: `${globalConfig.getImgURL}${pk}`,
  394. header: {
  395. 'token': apiToken
  396. },
  397. success: (res) => {
  398. if (res.statusCode === 200) {
  399. // 等待一小段时间确保文件完全下载
  400. setTimeout(() => {
  401. moveFile(res.tempFilePath).then((newFilePath) => {
  402. console.log('图片已移动并添加到数组:', newFilePath);
  403. // 处理完成后等待1秒再处理下一张
  404. setTimeout(() => {
  405. resolve(newFilePath);
  406. }, 500);
  407. }).catch((error) => {
  408. console.error('文件移动失败,使用原始路径:', error);
  409. // 如果移动失败,使用原始路径作为备选
  410. // 处理完成后等待1秒再处理下一张
  411. setTimeout(() => {
  412. resolve(res.tempFilePath);
  413. }, 1000);
  414. });
  415. }, 500); // 等待500ms确保文件完全下载
  416. } else {
  417. console.error('下载图片失败,状态码:', res.statusCode);
  418. reject(new Error(`下载图片失败,状态码: ${res.statusCode}`));
  419. }
  420. },
  421. fail: (err) => {
  422. console.error('请求图片失败:', err);
  423. reject(err);
  424. }
  425. });
  426. });
  427. }
  428. //检验任务上传
  429. export const uploadDataToAPI = async (gxpk : string, callback ?: () => void) : Promise<boolean> => {
  430. try {
  431. //暂定需要上传的数据文件
  432. const apiToken = await getTokenFromApi();
  433. if (apiToken == null || apiToken == '') {
  434. uni.hideLoading();
  435. uni.showToast({ title: `获取Token失败,请联系技术IT`, icon: 'error' });
  436. return false
  437. }
  438. // 获取数据
  439. const infoJson = await getLatestTask(gxpk, null);
  440. // console.log(infoJson)
  441. if (infoJson != null) {
  442. let taskInfoJson = infoJson?.['data'] as UTSJSONObject ?? {};
  443. if (taskInfoJson == null) {
  444. uni.hideLoading();
  445. uni.showToast({ title: '未获取到数据', icon: 'error' });
  446. return false;
  447. }
  448. console.log('--------------------->')
  449. console.log(taskInfoJson)
  450. uni.showLoading({ title: `开始上传数据`});
  451. let taskInfo = JSON.parse<Task>(taskInfoJson.toJSONString());
  452. let canContinueFlag = true;
  453. // 1. 收集所有需要上传的图片
  454. let res = await getList('app_task_photo', 'pdid', taskInfo?.pdid.toString(), 'uploadFlag', '0', null)
  455. let dataList = res?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
  456. if (dataList != null && dataList.length > 0) {
  457. //处理图片对象数组
  458. let allImagesToUpload : UploadImg[] = [];
  459. let processStep = 1;
  460. for (let index = 0; index < dataList.length; index++) {
  461. const record = dataList[index];
  462. if (record.getString('photourl') == '' || record.getString('photourl') == null
  463. || record.getString('pk') == '' || record.getString('pk') == null) {
  464. continue
  465. }
  466. showProgress(processStep, '准备上传');
  467. //收集图片信息
  468. let photourlStr = record.getString('photourl');
  469. let sxid = record.getString('sxid');
  470. let pk = record.getString('pk');
  471. let urlArr = photourlStr?.split(",") ?? [];
  472. for (let j = 0; j < urlArr.length; j++) {
  473. let path = urlArr[j];
  474. const fullFilePath = `${uni.env.USER_DATA_PATH}` + path;
  475. allImagesToUpload.push({ sxid: sxid ?? '', pk: pk ?? '', path: fullFilePath });
  476. }
  477. processStep++;
  478. }
  479. // 2. 统计总图片数量
  480. const totalImages = allImagesToUpload.length;
  481. console.log(`总共需要上传${totalImages}张图片`);
  482. if (totalImages === 0) {
  483. uni.hideLoading();
  484. uni.showToast({ title: '没有需要上传的图片', icon: 'none' });
  485. return true;
  486. }
  487. // 3. 执行第一次上传
  488. let failedImages : UploadImg[] = [];
  489. let successCount = 0;
  490. uni.showLoading({ title: `正在上传图片 (0/${totalImages})` });
  491. for (let i = 0; i < allImagesToUpload.length; i++) {
  492. const { sxid, pk, path } = allImagesToUpload[i];
  493. console.log(`开始上传文件: ${path}, 索引: ${i}, apiToken: ${apiToken}, billid: ${pk}, sxid: ${sxid}`);
  494. try {
  495. // 串行执行,等待前一个图片上传完成再处理下一张
  496. await new Promise<void>((resolve, reject) => {
  497. // 使用uni.uploadFile进行文件上传
  498. console.log(`上传路径:${globalConfig.uploadURL}`)
  499. const uploadTask = uni.uploadFile({
  500. url: `${globalConfig.uploadURL}`,
  501. filePath: path,
  502. name: 'file', // 文件参数名
  503. header: {
  504. 'token': apiToken,
  505. 'content-type': 'multipart/form-data'
  506. },
  507. formData: {
  508. 'billid': pk
  509. },
  510. success: (uploadRes) => {
  511. if (uploadRes.statusCode === 200) {
  512. console.log(`文件${path}上传成功`, uploadRes);
  513. successCount++;
  514. //更新数据库记录
  515. let updatedData = " uploadFlag = 1 "
  516. updateData('app_task_photo', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  517. console.log(`更新图片记录的上传标识 ${sxid}`)
  518. });
  519. // 等待一小段时间确保文件完全上传并处理完成
  520. setTimeout(() => {
  521. resolve();
  522. }, 1000);
  523. } else {
  524. console.error(`文件${path}上传失败,状态码:`, uploadRes.statusCode);
  525. let updatedData = " uploadFlag = 0 "
  526. updateData('app_task_photo', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  527. console.log(`上传失败更新图片记录的上传标识 ${sxid}`)
  528. });
  529. uni.showModal({
  530. content: `图片上传失败,状态码:${uploadRes.statusCode}`,
  531. title: '图片上传失败'
  532. })
  533. setTimeout(() => {
  534. reject(new Error(`上传失败,状态码: ${uploadRes.statusCode}`));
  535. }, 500);
  536. }
  537. },
  538. fail: (err) => {
  539. console.error(`文件${path}上传失败`, err);
  540. // 上传失败也继续处理下一张,但记录错误
  541. let updatedData = " uploadFlag = 0 "
  542. updateData('app_task_photo', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  543. console.log(`上传错误更新图片记录的上传标识 ${sxid}`)
  544. });
  545. uni.showModal({
  546. content: `文件上传失败:${err}`,
  547. title: '图片上传失败'
  548. })
  549. setTimeout(() => {
  550. reject(err);
  551. }, 500);
  552. },
  553. complete: () => {
  554. // console.log(`文件${path}上传操作完成`);
  555. // 更新进度
  556. uni.hideLoading();
  557. uni.showLoading({ title: `正在上传图片 (${i + 1}/${totalImages})` });
  558. }
  559. });
  560. //调试时开启
  561. // uploadTask.onProgressUpdate((res) => {
  562. // console.log('上传进度' + res.progress);
  563. // console.log('已经上传的数据长度' + res.totalBytesSent);
  564. // console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
  565. // });
  566. });
  567. } catch (error) {
  568. // 捕获上传失败的错误,将失败的图片信息添加到错误数组
  569. console.log(`处理第${i + 1}张图片时出错:`, error);
  570. failedImages.push({ sxid, pk, path });
  571. // 出错后继续处理下一张图片
  572. uni.showModal({
  573. content: `文件上传失败:${error}`,
  574. title: '图片上传失败'
  575. })
  576. }
  577. // 在两次上传之间增加一个短暂的延迟,避免请求过于频繁
  578. if (i < allImagesToUpload.length - 1) {
  579. await new Promise<void>((resolve) => {
  580. setTimeout(() => {
  581. resolve()
  582. }, 1000)
  583. })
  584. }
  585. }
  586. // 4. 执行重试逻辑(最多3次)
  587. const maxRetries = 3;
  588. let retryImages = [...failedImages]; // 复制初始失败的图片数组
  589. for (let retryCount = 1; retryCount <= maxRetries; retryCount++) {
  590. if (retryImages.length === 0) {
  591. // 如果没有需要重试的图片,提前结束循环
  592. break;
  593. }
  594. console.log(`开始第${retryCount}次重试上传失败的图片,共${retryImages.length}张`);
  595. uni.hideLoading();
  596. uni.showLoading({ title: `第${retryCount}次重试 (0/${retryImages.length})` });
  597. // 创建新的错误数组,用于收集本次重试失败的图片
  598. let currentFailedImages : UploadImg[] = [];
  599. let currentSuccessCount = 0;
  600. // 串行上传失败的图片
  601. for (let i = 0; i < retryImages.length; i++) {
  602. const { sxid, pk, path } = retryImages[i];
  603. console.log(`重试上传文件: ${path}, 索引: ${i}, 重试次数: ${retryCount}, apiToken: ${apiToken}, billid: ${pk}, sxid: ${sxid}`);
  604. console.log(`重试上传路径:${globalConfig.uploadURL}`)
  605. await new Promise<void>((resolve) => {
  606. uni.uploadFile({
  607. url: `${globalConfig.uploadURL}`,
  608. filePath: path,
  609. name: 'file',
  610. header: {
  611. 'token': apiToken
  612. },
  613. formData: {
  614. 'billid': pk
  615. },
  616. success: (uploadRes) => {
  617. if (uploadRes.statusCode === 200) {
  618. currentSuccessCount++;
  619. //更新数据库
  620. let updatedData = " uploadFlag = 1 "
  621. updateData('app_task_photo', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  622. console.log(`更新图片记录的上传标识 ${sxid}`)
  623. });
  624. console.log(`重试上传完成,当前成功: ${currentSuccessCount}, 当前失败: ${currentFailedImages.length}`);
  625. resolve();
  626. } else {
  627. currentFailedImages.push({ sxid, pk, path });
  628. }
  629. },
  630. fail: (err) => {
  631. console.error(`重试文件${path}上传失败`, err);
  632. currentFailedImages.push({ sxid, pk, path });
  633. resolve();
  634. },
  635. complete: () => {
  636. // console.log(`重试文件${path}上传操作完成`);
  637. // 更新进度
  638. uni.hideLoading();
  639. uni.showLoading({ title: `第${retryCount}次重试 (${i + 1}/${retryImages.length})` });
  640. }
  641. });
  642. });
  643. // 在两次上传之间增加一个短暂的延迟,避免请求过于频繁
  644. if (i < retryImages.length - 1) {
  645. await new Promise<void>((resolve) => {
  646. setTimeout(() => {
  647. resolve()
  648. }, 1000)
  649. })
  650. }
  651. }
  652. // 更新成功数量
  653. successCount += currentSuccessCount;
  654. // 更新下一次重试的图片列表为本次失败的图片
  655. retryImages = currentFailedImages;
  656. }
  657. // 5. 显示总结信息
  658. const finalFailedCount = retryImages.length;
  659. console.log(`上传总结: 总共${totalImages}张图片, 成功${successCount}张, 失败${finalFailedCount}张`);
  660. // 三次重试后如果仍有失败的图片,显示提示
  661. if (finalFailedCount > 0) {
  662. uni.hideLoading();
  663. uni.showModal({
  664. title: '上传提示',
  665. content: `总共需要上传${totalImages}张图片,成功${successCount}张,失败${finalFailedCount}张。\n经过${maxRetries}次重试后,仍有${finalFailedCount}张图片上传失败,请检查网络后重新上传。`,
  666. showCancel: false
  667. });
  668. }
  669. if (finalFailedCount > 0) {
  670. canContinueFlag = false
  671. }
  672. }
  673. //执行照片上传以外的逻辑
  674. if (!canContinueFlag) {
  675. uni.showToast({
  676. title: `图片上传失败,请重新上传`,
  677. icon: 'error'
  678. });
  679. }
  680. taskInfoJson.set('photolist', Array<UTSJSONObject>())
  681. taskInfoJson.set('lastupdatetime', null)
  682. taskInfoJson.set('user', getCurrentUserNameSync())
  683. taskInfoJson.set('username', getCurrentUserSync())
  684. //1.填充关键工序数据
  685. let keyRes = await getList('app_task_keyprocess', 'pdid', taskInfo?.pdid.toString(), null, null, null)
  686. let keyList = keyRes?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
  687. if (keyList != null && keyList.length > 0) {
  688. let keyObjectList = [] as AppTaskKeyProcess[]
  689. keyList.forEach(item => {
  690. let keyObject = JSON.parse<AppTaskKeyProcess>(item.toJSONString());
  691. if (keyObject != null) {
  692. keyObjectList.push(keyObject)
  693. }
  694. })
  695. taskInfoJson.set('keyprocesslist', keyObjectList)
  696. }
  697. //2.填充检验任务数据
  698. let qcRecoerdRes = await getList('app_task_record', 'pdid', taskInfo?.pdid.toString(), null, null, null)
  699. let qcRecordList = qcRecoerdRes?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
  700. if (qcRecordList != null && qcRecordList.length > 0) {
  701. let qcRecordJson = qcRecordList[0]
  702. let sxid = qcRecordJson.getString("sxid")
  703. // 3.填充检验任务item 数据据
  704. let qcRecoerdItemRes = await getList('app_task_record_item', 'psxid', sxid, null, null, null)
  705. let qcRecordItemList = qcRecoerdItemRes?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
  706. if (qcRecordItemList != null && qcRecordItemList.length > 0) {
  707. let itemList = [] as AppTaskRecordItem[]
  708. qcRecordItemList.forEach(item => {
  709. let itemObj = JSON.parse<AppTaskRecordItem>(item.toJSONString());
  710. if (itemObj != null) {
  711. itemList.push(itemObj)
  712. }
  713. })
  714. qcRecordJson.set('items', itemList)
  715. }
  716. let qcRecord = JSON.parse<AppTaskRecord>(qcRecordJson.toJSONString());
  717. taskInfoJson.set("qcrecord", qcRecord)
  718. }
  719. let requestTask = JSON.parse<AppTaskInfo>(taskInfoJson.toJSONString());
  720. console.log("请求体:", requestTask)
  721. const requestResult = await new Promise<UTSJSONObject>((resolve, reject) => {
  722. // Ensure we properly stringify the JSON object and set the correct content-type
  723. uni.request({
  724. url: `${globalConfig.uploadTaskURL}`,
  725. method: 'POST',
  726. header: {
  727. 'token': apiToken,
  728. 'content-type': 'application/json'
  729. },
  730. data: JSON.stringify(requestTask), // Convert object to JSON string
  731. success: (res) => resolve(res?.['data'] as UTSJSONObject ?? {} as UTSJSONObject),
  732. fail: (err) => reject(err)
  733. });
  734. });
  735. // 检查返回的code值
  736. const code = requestResult?.['code'] as number;
  737. if (code === 666) {
  738. let updatedData = " uploadFlag = 1, uploadtime = strftime('%Y-%m-%d %H:%M:%S', 'now', 'localtime') "
  739. updateData('app_task_info', updatedData, 'pdid', taskInfo?.pdid.toString()).then((res : UTSJSONObject) => {
  740. console.log(`更新检验任务记录的上传标识 ${taskInfo?.pdid.toString()}`)
  741. });
  742. addOperateLog({ module: '检验任务', title: '上传检验任务', content: `上传检验任务,工序码:${gxpk}`, msg: null, createuser: getCurrentUserSync()??'' })
  743. uni.showToast({
  744. title: `上传成功`,
  745. icon: 'success'
  746. });
  747. } else {
  748. const errorMsg = requestResult?.['msg'] as string ?? '未知错误';
  749. console.error(`上传失败,错误码: ${code}, 错误信息: ${errorMsg}`);
  750. uni.showToast({
  751. title: `上传失败: ${errorMsg}`,
  752. icon: 'error'
  753. });
  754. addOperateLog({ module: '检验任务', title: '上传检验任务失败', content: `上传检验任务失败,工序码:${gxpk}`, msg: `错误信息Err:${errorMsg}`, createuser: getCurrentUserSync()??'' })
  755. }
  756. if (callback != null) {
  757. callback();
  758. }
  759. }
  760. return true;
  761. } catch (error) {
  762. console.error(error);
  763. uni.showToast({ title: '上传失败,请重试', icon: 'error' });
  764. uni.hideLoading();
  765. addOperateLog({ module: '检验任务', title: '上传检验任务失败', content: `上传检验任务失败,工序码:${gxpk}`, msg: `错误信息Err:${error}`, createuser: getCurrentUserSync()??'' })
  766. uni.showModal({
  767. content: `文件上传失败:${error}`,
  768. title: '图片上传失败'
  769. })
  770. return false;
  771. }
  772. }