dataProcessor.uts 16 KB

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