dataProcessor.uts 15 KB

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