dataProcessor.uts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. import { getToken, getTokenFromApi } from './auth'
  2. import { saveMediaInfo, saveMediaRecord, getLatestRecord, removeInfoAndRecord } from '@/api/work'
  3. import { globalConfig } from '@/config'
  4. // 类型定义保持不变
  5. export type ApiResponse = {
  6. code : number;
  7. msg : string;
  8. data : MediaInfoData[];
  9. }
  10. export type MediaInfoData = {
  11. pk : string;
  12. workorder ?: string;
  13. invname ?: string;
  14. productcode ?: string;
  15. cardno ?: string;
  16. model ?: string;
  17. graphid ?: string;
  18. ver ?: string;
  19. phase ?: string;
  20. processno ?: string;
  21. createtime ?: string;
  22. createuser ?: string;
  23. updatetime ?: string;
  24. updateuser ?: string;
  25. qmImageTaskClist ?: MediaRecordData[];
  26. }
  27. export type MediaRecordData = {
  28. senum ?: string;
  29. photoitem ?: string;
  30. part ?: string;
  31. partno ?: string;
  32. pk : string;
  33. exampleid ?: string;
  34. descb ?: string;
  35. num ?: number;
  36. urlspl ?: string;
  37. imgname ?: string;
  38. urlpdt ?: string;
  39. createtime ?: string;
  40. createuser ?: string;
  41. updatetime ?: string;
  42. updateuser ?: string;
  43. photoFiles_example ?: PhotoFilesExample[];
  44. }
  45. export type PhotoFilesExample = {
  46. _id ?: string,
  47. }
  48. export const downloadDataFromAPI = async (productCode : string, callback ?: () => void) : Promise<boolean> => {
  49. try {
  50. //校验是否已经存在未执行的产品号,若已经存在则提示用户该产品号是否需要被覆盖,
  51. //如果没有则直接保存。如果有存在已经在执行中的产品号,则提示已存在执行中的任务
  52. const infoJson = await getLatestRecord(productCode, null);
  53. if (infoJson?.['data'] != null) {
  54. let info = infoJson?.['data'] as UTSJSONObject ?? {} as UTSJSONObject
  55. let ingNum = parseInt(info?.['statusRecordCount'] as string);
  56. //覆盖标识位
  57. let overwiteFlag = ref(false);
  58. // 先检查是否有任务正在执行中
  59. if (info != null && ingNum > 0) {
  60. uni.showToast({ title: `当前产品号已有任务在执行中!`, icon: 'error' });
  61. return false;
  62. }
  63. // 使用Promise来处理异步流程
  64. let deleteDataPromise = new Promise<boolean>((resolve) => {
  65. if (info != null && ingNum == 0) {
  66. //可以被覆盖,需要有提示框,给用户确认
  67. uni.showModal({
  68. title: '系统提示',
  69. content: '该产品号已存在任务是否覆盖掉?',
  70. cancelText: '取消',
  71. confirmText: '确定',
  72. success: function (res) {
  73. if (res.confirm) {
  74. // 标记为需要覆盖
  75. overwiteFlag.value = true;
  76. // 执行删除数据操作
  77. let pid = info?.['pdid'] as string;
  78. removeInfoAndRecord(pid).then((recordDelResponse) => {
  79. console.log('删除数据响应:', recordDelResponse);
  80. // 删除成功,解析Promise并允许继续执行
  81. // 确保模态框已完全关闭后再解析Promise
  82. setTimeout(() => {
  83. resolve(true);
  84. }, 300);
  85. }).catch((error) => {
  86. console.error('删除数据失败:', error);
  87. uni.showToast({ title: '删除旧数据失败', icon: 'error' });
  88. resolve(false);
  89. });
  90. } else {
  91. // 用户取消覆盖
  92. overwiteFlag.value = false;
  93. resolve(false);
  94. }
  95. }
  96. });
  97. } else {
  98. // 不需要显示确认框,直接解析Promise
  99. resolve(true);
  100. }
  101. });
  102. // 等待删除数据操作完成
  103. const canContinue : boolean = await deleteDataPromise;
  104. if (!canContinue) {
  105. // 如果不能继续(删除失败或用户取消),则终止函数执行
  106. return false;
  107. }
  108. }
  109. // 继续执行后续代码...
  110. const apiToken = await getTokenFromApi();
  111. // uni.showLoading({ title: '数据下载中...' });
  112. // 创建进度条 - 适配Android设备的解决方案
  113. const showProgress = (index : number) => {
  114. // 在Android设备上,需要给hideLoading和showLoading之间添加延迟
  115. // 先隐藏之前的加载提示
  116. uni.hideLoading();
  117. // 添加50ms的延迟,确保hideLoading完全执行后再显示新的进度
  118. setTimeout(() => {
  119. uni.showLoading({
  120. title: `正在下载第${index}个任务数据`,
  121. mask: true
  122. });
  123. }, 50);
  124. };
  125. // 使用Promise处理HTTP请求,避免嵌套Promise
  126. return new Promise<boolean>((resolve) => {
  127. uni.request({
  128. url: `${globalConfig.apiUrl}/loadQmImagetask?prodcode=${productCode}`,
  129. method: 'GET',
  130. header: {
  131. 'token': apiToken
  132. },
  133. success: (res) => {
  134. let singleObject = res?.['data'] as UTSJSONObject ?? {} as UTSJSONObject;
  135. if (singleObject != null && singleObject.code == 666) {
  136. let mediaInfoList = singleObject?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  137. if (mediaInfoList != null && mediaInfoList.length > 0) {
  138. mediaInfoList.forEach(item => {
  139. if (item != null) {
  140. let data = JSON.parse<MediaInfoData>(item.toJSONString());
  141. if (data != null) {
  142. saveMediaInfo(item).then((resSave : UTSJSONObject) => {
  143. const lastIdStr = resSave?.['lastId'] as string | null;
  144. const lastId = lastIdStr != null ? parseInt(lastIdStr) : null;
  145. if (lastId != null) {
  146. let recordList = data?.['qmImageTaskClist'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  147. if (recordList != null && recordList.length > 0) {
  148. const totalRecords = recordList.length;
  149. let processedRecords = 0;
  150. // 使用async/await处理循环中的异步操作
  151. const processAllRecords = async () => {
  152. for (var i = 0; i < recordList.length; i++) {
  153. // 更新进度
  154. processedRecords++;
  155. showProgress(processedRecords);
  156. const record : MediaRecordData = recordList[i] as MediaRecordData;
  157. // 获取各个字段的值
  158. const senum = record.senum;
  159. const photoitem = record.photoitem;
  160. const part = record.part;
  161. const partno = record.partno;
  162. const pk = record.pk;
  163. const descb = record.descb;
  164. const num = record.num;
  165. const urlspl = record.urlspl;
  166. const imgname = record.imgname;
  167. const urlpdt = record.urlpdt;
  168. const createtime = record.createtime;
  169. const createuser = record.createuser;
  170. const updatetime = record.updatetime;
  171. const updateuser = record.updateuser;
  172. // 创建数组来存储图片ID和保存路径
  173. var exampleidArr = [] as string[];
  174. var imagePathsArr = [] as string[];
  175. let exampleList = record?.['photoFiles_example'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  176. if (exampleList != null && exampleList.length > 0) {
  177. // 下载所有图片并等待完成
  178. const imageDownloadPromises = [] as Promise<void>[];
  179. // 顺序下载和保存图片,避免并行导致的随机失败
  180. for (var j = 0; j < exampleList.length; j++) {
  181. const example : PhotoFilesExample = exampleList[j] as PhotoFilesExample;
  182. if (example._id != null) {
  183. exampleidArr.push(example._id);
  184. try {
  185. // 串行执行,等待前一张图片处理完成再处理下一张
  186. await new Promise<void>((resolve, reject) => {
  187. // 使用uni.downloadFile下载图片
  188. uni.downloadFile({
  189. url: `http://192.168.5.124:8080/api/images/getImage?fileId=${example._id}`,
  190. header: {
  191. 'token': apiToken
  192. },
  193. success: (res) => {
  194. if (res.statusCode === 200) {
  195. // 等待一小段时间确保文件完全下载
  196. setTimeout(() => {
  197. // 图片下载成功,使用uni.saveImageToPhotosAlbum保存到相册
  198. uni.saveImageToPhotosAlbum({
  199. filePath: res.tempFilePath,
  200. success: () => {
  201. console.log('图片保存成功:', res.tempFilePath);
  202. // 将保存路径添加到数组中
  203. imagePathsArr.push(res.tempFilePath);
  204. // 保存成功后等待1秒再处理下一张
  205. setTimeout(() => {
  206. resolve();
  207. }, 1000);
  208. },
  209. fail: (err) => {
  210. console.error('保存图片失败:', err);
  211. // 保存失败也继续处理下一张,但记录错误
  212. setTimeout(() => {
  213. reject(err);
  214. }, 1000);
  215. }
  216. });
  217. }, 500); // 等待500ms确保文件完全下载
  218. } else {
  219. console.error('下载图片失败,状态码:', res.statusCode);
  220. reject(new Error(`下载图片失败,状态码: ${res.statusCode}`));
  221. }
  222. },
  223. fail: (err) => {
  224. console.error('请求图片失败:', err);
  225. reject(err);
  226. }
  227. });
  228. });
  229. } catch (error) {
  230. console.error(`处理第${j + 1}张图片时出错:`, error);
  231. // 出错后继续处理下一张图片
  232. }
  233. }
  234. }
  235. }
  236. // 拼接图片ID和路径
  237. const exampleid = exampleidArr.join(",");
  238. const imagePaths = imagePathsArr.join(",");
  239. console.log("=========================================>");
  240. console.log(imagePaths);
  241. // 使用三目运算符判断,当值为null时直接插入null,否则用单引号括起来
  242. var values = `${senum === null ? '1' : `'${senum}'`}, ${photoitem === null ? 'null' : `'${photoitem}'`}, ${data?.['productcode'] === null ? 'null' : `'${data?.['productcode']}'`},${part === null ? 'null' : `'${part}'`},${partno === null ? 'null' : `'${partno}'`},${pk === null ? 'null' : `'${pk}'`},${exampleid === null ? 'null' : `'${exampleid}'`},${descb === null ? 'null' : `'${descb}'`},${num === null ? 0 : num},1,'', ${imagePaths === null ? 'null' : `'${imagePaths}'`},${imgname === null ? 'null' : `'${imgname}'`},${urlpdt === null ? 'null' : `'${urlpdt}'`}, ${createtime === null ? 'null' : `'${createtime}'`}, ${createuser === null ? 'null' : `'${createuser}'`}, ${updatetime === null ? 'null' : `'${updatetime}'`}, ${updateuser === null ? 'null' : `'${updateuser}'`}, ${lastId === null ? 0 : lastId}`;
  243. // 只有在所有图片下载完成后才调用saveMediaRecord
  244. saveMediaRecord(values);
  245. }
  246. // 所有记录处理完成,显示完成提示
  247. setTimeout(() => {
  248. uni.hideLoading();
  249. uni.showToast({ title: `下载完成`, icon: 'success' });
  250. if (callback != null) {
  251. callback();
  252. }
  253. }, 500);
  254. };
  255. // 开始处理所有记录
  256. processAllRecords();
  257. }
  258. } else {
  259. console.log('保存媒体信息成功,但未获取到主键ID');
  260. }
  261. })
  262. }
  263. }
  264. });
  265. resolve(true);
  266. } else {
  267. uni.hideLoading();
  268. uni.showToast({ title: '未获取到数据', icon: 'error' });
  269. resolve(false);
  270. }
  271. } else {
  272. const errorMsg = singleObject.msg != null ? singleObject.msg : '未知错误';
  273. uni.hideLoading();
  274. uni.showToast({ title: `请求失败: ${errorMsg}`, icon: 'error' });
  275. resolve(false);
  276. }
  277. },
  278. fail: (err) => {
  279. console.error('请求数据失败:', err);
  280. uni.hideLoading();
  281. uni.showToast({ title: `请求失败: ${err.errMsg}`, icon: 'error' });
  282. resolve(false);
  283. }
  284. });
  285. });
  286. } catch (error) {
  287. console.error(error);
  288. uni.showToast({ title: '下载失败,请重试', icon: 'error' });
  289. uni.hideLoading();
  290. return false;
  291. }
  292. }