dataProcessor.uts 15 KB

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