dataProcessor.uts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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 showProgress = (index : number, title : string) => {
  50. // 在Android设备上,需要给hideLoading和showLoading之间添加延迟
  51. // 先隐藏之前的加载提示
  52. uni.hideLoading();
  53. // 添加50ms的延迟,确保hideLoading完全执行后再显示新的进度
  54. setTimeout(() => {
  55. uni.showLoading({
  56. title: `正在${title}第${index}个任务数据`,
  57. mask: true
  58. });
  59. }, 50);
  60. }
  61. //声像任务下载
  62. export const downloadDataFromAPI = async (productCode : string, callback ?: () => void) : Promise<boolean> => {
  63. try {
  64. uni.showLoading({ title: '任务开始下载' });
  65. const apiToken = await getTokenFromApi();
  66. if (apiToken == null || apiToken == '') {
  67. uni.hideLoading();
  68. uni.showToast({ title: `获取Token失败,请联系技术IT`, icon: 'error' });
  69. return false
  70. }
  71. //校验是否已经存在未执行的产品号,若已经存在则提示用户该产品号是否需要被覆盖,
  72. //如果没有则直接保存。如果有存在已经在执行中的产品号,则提示已存在执行中的任务
  73. const infoJson = await getLatestRecord(productCode, null);
  74. if (infoJson?.['data'] != null) {
  75. let info = infoJson?.['data'] as UTSJSONObject ?? {} as UTSJSONObject
  76. let ingNum = parseInt(info?.['statusRecordCount'] as string);
  77. //覆盖标识位
  78. let overwiteFlag = ref(false);
  79. // 先检查是否有任务正在执行中
  80. if (info != null && ingNum > 0) {
  81. uni.showToast({ title: `当前产品号已有任务在执行中!`, icon: 'error' });
  82. return false;
  83. }
  84. // 使用Promise来处理异步流程
  85. let deleteDataPromise = new Promise<boolean>((resolve) => {
  86. if (info != null && ingNum == 0) {
  87. //可以被覆盖,需要有提示框,给用户确认
  88. uni.showModal({
  89. title: '系统提示',
  90. content: '该产品号已存在任务是否覆盖掉?',
  91. cancelText: '取消',
  92. confirmText: '确定',
  93. success: function (res) {
  94. if (res.confirm) {
  95. // 标记为需要覆盖
  96. overwiteFlag.value = true;
  97. // 执行删除数据操作
  98. let pid = info?.['pdid'] as string;
  99. removeInfoAndRecord(pid).then((recordDelResponse) => {
  100. console.log('删除数据响应:', recordDelResponse);
  101. // 删除成功,解析Promise并允许继续执行
  102. // 确保模态框已完全关闭后再解析Promise
  103. setTimeout(() => {
  104. resolve(true);
  105. }, 300);
  106. }).catch((error) => {
  107. console.error('删除数据失败:', error);
  108. uni.showToast({ title: '删除旧数据失败', icon: 'error' });
  109. resolve(false);
  110. });
  111. } else {
  112. // 用户取消覆盖
  113. overwiteFlag.value = false;
  114. resolve(false);
  115. }
  116. }
  117. });
  118. } else {
  119. // 不需要显示确认框,直接解析Promise
  120. resolve(true);
  121. }
  122. });
  123. // 等待删除数据操作完成
  124. const canContinue : boolean = await deleteDataPromise;
  125. if (!canContinue) {
  126. // 如果不能继续(删除失败或用户取消),则终止函数执行
  127. return false;
  128. }
  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. }, 500);
  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. //声像任务上传
  308. export const uploadDataToAPI = async (productCode : string, callback ?: () => void) : Promise<boolean> => {
  309. try {
  310. //暂定需要上传的数据文件
  311. //const infoJson = await getLatestRecord(productCode, null);
  312. const apiToken = await getTokenFromApi();
  313. if (apiToken == null || apiToken == '') {
  314. uni.hideLoading();
  315. uni.showToast({ title: `获取Token失败,请联系技术IT`, icon: 'error' });
  316. return false
  317. }
  318. getJoinList('app_media_record as r', 'app_media_info as i', 'r.*,i.productno', 'r.pid=i.pdid', 'i.productno', productCode, null).then(async (res : UTSJSONObject) => {
  319. let dataList = res?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
  320. console.log(dataList);
  321. if (dataList != null && dataList.length > 0) {
  322. let doneRecordList = dataList.filter(item => item.getString("status") == '3')
  323. // console.log("uploadFiles", uploadFiles);
  324. if (doneRecordList.length === 0) {
  325. uni.showToast({ title: '上传图片数据为空', icon: 'error' });
  326. return;
  327. }
  328. let processStep = 1;
  329. for (let index = 0; index < dataList.length; index++) {
  330. const record = dataList[index];
  331. if (record.getString('urlpdt') == '' || record.getString('urlpdt') == null
  332. || record.getString('pk') == '' || record.getString('pk') == null) {
  333. continue
  334. }
  335. showProgress(processStep, '上传');
  336. //文件上传
  337. let urlpdtStr = record.getString('urlpdt')
  338. let pk = record.getString('pk')
  339. let urlArr = urlpdtStr?.split(",") ?? []
  340. for (let j = 0; j < urlArr.length; j++) {
  341. let path = urlArr[j];
  342. const fullFilePath = `${uni.env.USER_DATA_PATH}` + path;
  343. console.log(`开始上传文件: ${fullFilePath}, 索引: ${j}, apiToken: ${apiToken}, billid: ${pk}`);
  344. await new Promise<void>((resolve, reject) => {
  345. // 使用uni.uploadFile进行文件上传
  346. uni.uploadFile({
  347. url: 'http://192.168.43.62:8080/api/images/upload',
  348. filePath: fullFilePath,
  349. name: 'file', // 文件参数名
  350. header: {
  351. 'token': apiToken
  352. },
  353. formData: {
  354. 'billid': pk
  355. },
  356. success: (uploadRes) => {
  357. if (uploadRes.statusCode === 200) {
  358. console.log(`文件${path}上传成功`, uploadRes);
  359. // 解析响应数据
  360. const resData = JSON.parse(uploadRes.data) as UTSJSONObject;
  361. console.log(resData)
  362. if (resData?.['_id'] != null && resData?.['_id'] != '') {
  363. setTimeout(() => {
  364. resolve();
  365. }, 3000);
  366. } else {
  367. setTimeout(() => {
  368. reject('');
  369. }, 500);
  370. }
  371. }
  372. },
  373. fail: (err) => {
  374. console.error(`文件${path}上传失败`, err);
  375. uni.showToast({
  376. title: `文件${j}上传失败: ${err.errMsg != null ? err.errMsg : '网络错误'}`,
  377. icon: 'error'
  378. });
  379. setTimeout(() => {
  380. reject(err); // 在fail回调中调用reject
  381. }, 500);
  382. },
  383. complete: () => {
  384. console.log(`文件${path}上传完成`);
  385. }
  386. });
  387. }).catch(err => {
  388. // 捕获上传失败的错误,但继续上传下一个文件
  389. console.log(`当前文件上传失败,但继续下一个文件上传,异常 ${err}`);
  390. });
  391. }
  392. processStep++;
  393. }
  394. }
  395. })
  396. } catch (error) {
  397. console.error(error);
  398. // uni.showToast({ title: '上传失败,请重试', icon: 'error' });
  399. uni.hideLoading();
  400. return false;
  401. }
  402. uni.hideLoading();
  403. return true;
  404. }